diff options
author | chai <215380520@qq.com> | 2024-03-13 11:00:58 +0800 |
---|---|---|
committer | chai <215380520@qq.com> | 2024-03-13 11:00:58 +0800 |
commit | 6ce8b9e22fc13be34b442c7b6af48b42cd44275a (patch) | |
tree | b38119d2acf0a982cb67e381f146924b9bfc3b3f |
+init
246 files changed, 21283 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a4da27a --- /dev/null +++ b/.gitignore @@ -0,0 +1,399 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.vs @@ -0,0 +1,49 @@ +using System.Collections; +using UnityEngine; + +public class ADS : MonoBehaviour +{ + public Vector3 recoilMovement; + + public Vector3 randomRecoilMovement; + + public AnimationCurve curve; + + public float animationSpeed = 1f; + + private Vector3 startPosition; + + private void Start() + { + startPosition = base.transform.localPosition; + } + + private void Update() + { + } + + public void PlayRecoilAnimation() + { + StartCoroutine(ApplyRecoil()); + } + + private IEnumerator ApplyRecoil() + { + float counter = 0f; + float lastValue = curve.Evaluate(0f); + float animtionTime = curve.keys[curve.length - 1].time; + Vector3 v = recoilMovement + new Vector3(Random.Range(0f - randomRecoilMovement.x, randomRecoilMovement.x), Random.Range(0f - randomRecoilMovement.y, randomRecoilMovement.y), Random.Range(0f - randomRecoilMovement.z, randomRecoilMovement.z)); + while (counter < animtionTime) + { + counter += Time.deltaTime * animationSpeed; + if (counter > animtionTime) + { + counter = animtionTime; + } + float deltaForce = curve.Evaluate(counter) - lastValue; + lastValue = curve.Evaluate(counter); + base.transform.localPosition += deltaForce * v * 0.001f; + yield return null; + } + } +} diff --git a/AddCameraMovementByRig.cs b/AddCameraMovementByRig.cs new file mode 100644 index 0000000..905b69a --- /dev/null +++ b/AddCameraMovementByRig.cs @@ -0,0 +1,31 @@ +using UnityEngine; + +public class AddCameraMovementByRig : MonoBehaviour +{ + public Rigidbody rig; + + public float movementMultiplier = 1f; + + public float returnForce; + + public float rigForce; + + public float friction = 0.97f; + + private Vector3 velocity; + + private Vector3 startPos; + + private void Start() + { + startPos = base.transform.localPosition; + } + + private void FixedUpdate() + { + velocity -= rig.velocity * rigForce; + velocity += (base.transform.parent.TransformPoint(startPos) - base.transform.position) * returnForce; + velocity *= friction; + base.transform.position += velocity * movementMultiplier; + } +} diff --git a/AddForceByCollision.cs b/AddForceByCollision.cs new file mode 100644 index 0000000..8392efa --- /dev/null +++ b/AddForceByCollision.cs @@ -0,0 +1,34 @@ +using UnityEngine; + +public class AddForceByCollision : MonoBehaviour +{ + public Rigidbody rig; + + public float amout; + + private void Start() + { + } + + private void Update() + { + } + + private void OnCollisionEnter(Collision collision) + { + Collide(collision); + } + + private void OnCollisionStay(Collision collision) + { + Collide(collision); + } + + private void Collide(Collision collision) + { + if (collision.gameObject.layer == 9) + { + rig.AddForce(collision.contacts[0].normal * collision.impactForceSum.magnitude * amout, ForceMode.Acceleration); + } + } +} diff --git a/AddForceToTarget.cs b/AddForceToTarget.cs new file mode 100644 index 0000000..9464c97 --- /dev/null +++ b/AddForceToTarget.cs @@ -0,0 +1,26 @@ +using UnityEngine; + +public class AddForceToTarget : MonoBehaviour +{ + public AnimationCurve forceByRangeCurve; + + public Rigidbody target; + + public float force; + + private Transform head; + + private void Start() + { + head = GetComponentInChildren<Head>().transform; + } + + private void FixedUpdate() + { + float num = forceByRangeCurve.Evaluate(Vector3.Distance(head.position, target.position)) * force; + if (num > 0f) + { + target.AddForce((head.position - target.position).normalized * num, ForceMode.Force); + } + } +} diff --git a/AddScreenShake.cs b/AddScreenShake.cs new file mode 100644 index 0000000..1d7a2a4 --- /dev/null +++ b/AddScreenShake.cs @@ -0,0 +1,29 @@ +using UnityEngine; + +public class AddScreenShake : MonoBehaviour +{ + public float friction = 0.75f; + + public Vector3 shake = Vector2.zero; + + public Vector3 additionalRandom = Vector3.zero; + + [HideInInspector] + public WobbleShake wobbleShake; + + private void Start() + { + } + + private void Update() + { + } + + public void DoShake() + { + if ((bool)wobbleShake) + { + wobbleShake.AddShake(new Vector3(shake.x + Random.Range(0f - additionalRandom.x, additionalRandom.x), shake.y + Random.Range(0f - additionalRandom.y, additionalRandom.y), shake.z + Random.Range(0f - additionalRandom.z, additionalRandom.z)), friction); + } + } +} diff --git a/AmplifyOcclusion/VersionInfo.cs b/AmplifyOcclusion/VersionInfo.cs new file mode 100644 index 0000000..c460b70 --- /dev/null +++ b/AmplifyOcclusion/VersionInfo.cs @@ -0,0 +1,61 @@ +using System; +using UnityEngine; + +namespace AmplifyOcclusion; + +[Serializable] +public class VersionInfo +{ + public const byte Major = 1; + + public const byte Minor = 2; + + public const byte Release = 3; + + private static string StageSuffix = "_dev001"; + + [SerializeField] + private int m_major; + + [SerializeField] + private int m_minor; + + [SerializeField] + private int m_release; + + public int Number => m_major * 100 + m_minor * 10 + m_release; + + private VersionInfo() + { + m_major = 1; + m_minor = 2; + m_release = 3; + } + + private VersionInfo(byte major, byte minor, byte release) + { + m_major = major; + m_minor = minor; + m_release = release; + } + + public static string StaticToString() + { + return $"{(byte)1}.{(byte)2}.{(byte)3}" + StageSuffix; + } + + public override string ToString() + { + return $"{m_major}.{m_minor}.{m_release}" + StageSuffix; + } + + public static VersionInfo Current() + { + return new VersionInfo(1, 2, 3); + } + + public static bool Matches(VersionInfo version) + { + return version.m_major == 1 && version.m_minor == 2 && 3 == version.m_release; + } +} diff --git a/AmplifyOcclusionBase.cs b/AmplifyOcclusionBase.cs new file mode 100644 index 0000000..e429102 --- /dev/null +++ b/AmplifyOcclusionBase.cs @@ -0,0 +1,951 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Rendering; + +[AddComponentMenu("")] +public class AmplifyOcclusionBase : MonoBehaviour +{ + public enum ApplicationMethod + { + PostEffect, + Deferred, + Debug + } + + public enum PerPixelNormalSource + { + None, + Camera, + GBuffer, + GBufferOctaEncoded + } + + public enum SampleCountLevel + { + Low, + Medium, + High, + VeryHigh + } + + private static class ShaderPass + { + public const int FullDepth = 0; + + public const int FullNormal_None = 1; + + public const int FullNormal_Camera = 2; + + public const int FullNormal_GBuffer = 3; + + public const int FullNormal_GBufferOctaEncoded = 4; + + public const int DeinterleaveDepth1 = 5; + + public const int DeinterleaveNormal1_None = 6; + + public const int DeinterleaveNormal1_Camera = 7; + + public const int DeinterleaveNormal1_GBuffer = 8; + + public const int DeinterleaveNormal1_GBufferOctaEncoded = 9; + + public const int DeinterleaveDepth4 = 10; + + public const int DeinterleaveNormal4_None = 11; + + public const int DeinterleaveNormal4_Camera = 12; + + public const int DeinterleaveNormal4_GBuffer = 13; + + public const int DeinterleaveNormal4_GBufferOctaEncoded = 14; + + public const int OcclusionCache_Low = 15; + + public const int OcclusionCache_Medium = 16; + + public const int OcclusionCache_High = 17; + + public const int OcclusionCache_VeryHigh = 18; + + public const int Reinterleave = 19; + + public const int OcclusionLow_None = 20; + + public const int OcclusionLow_Camera = 21; + + public const int OcclusionLow_GBuffer = 22; + + public const int OcclusionLow_GBufferOctaEncoded = 23; + + public const int OcclusionMedium_None = 24; + + public const int OcclusionMedium_Camera = 25; + + public const int OcclusionMedium_GBuffer = 26; + + public const int OcclusionMedium_GBufferOctaEncoded = 27; + + public const int OcclusionHigh_None = 28; + + public const int OcclusionHigh_Camera = 29; + + public const int OcclusionHigh_GBuffer = 30; + + public const int OcclusionHigh_GBufferOctaEncoded = 31; + + public const int OcclusionVeryHigh_None = 32; + + public const int OcclusionVeryHigh_Camera = 33; + + public const int OcclusionVeryHigh_GBuffer = 34; + + public const int OcclusionVeryHigh_GBufferNormalEncoded = 35; + + public const int ApplyDebug = 36; + + public const int ApplyDeferred = 37; + + public const int ApplyDeferredLog = 38; + + public const int ApplyPostEffect = 39; + + public const int ApplyPostEffectLog = 40; + + public const int CombineDownsampledOcclusionDepth = 41; + + public const int BlurHorizontal1 = 0; + + public const int BlurVertical1 = 1; + + public const int BlurHorizontal2 = 2; + + public const int BlurVertical2 = 3; + + public const int BlurHorizontal3 = 4; + + public const int BlurVertical3 = 5; + + public const int BlurHorizontal4 = 6; + + public const int BlurVertical4 = 7; + + public const int Copy = 0; + } + + private struct TargetDesc + { + public int fullWidth; + + public int fullHeight; + + public RenderTextureFormat format; + + public int width; + + public int height; + + public int quarterWidth; + + public int quarterHeight; + + public float padRatioWidth; + + public float padRatioHeight; + } + + [Header("Ambient Occlusion")] + public ApplicationMethod ApplyMethod; + + public SampleCountLevel SampleCount = SampleCountLevel.Medium; + + public PerPixelNormalSource PerPixelNormals; + + [Range(0f, 1f)] + public float Intensity = 1f; + + public Color Tint = Color.black; + + [Range(0f, 16f)] + public float Radius = 1f; + + [Range(0f, 16f)] + public float PowerExponent = 1.8f; + + [Range(0f, 0.99f)] + public float Bias = 0.05f; + + public bool CacheAware; + + public bool Downsample; + + [Header("Distance Fade")] + public bool FadeEnabled; + + public float FadeStart = 100f; + + public float FadeLength = 50f; + + [Range(0f, 1f)] + public float FadeToIntensity = 1f; + + [Range(0f, 16f)] + public float FadeToRadius = 1f; + + [Range(0f, 16f)] + public float FadeToPowerExponent = 1.8f; + + [Header("Bilateral Blur")] + public bool BlurEnabled = true; + + [Range(1f, 4f)] + public int BlurRadius = 2; + + [Range(1f, 4f)] + public int BlurPasses = 1; + + [Range(0f, 20f)] + public float BlurSharpness = 10f; + + private const int PerPixelNormalSourceCount = 4; + + private int prevScreenWidth; + + private int prevScreenHeight; + + private bool prevHDR; + + private ApplicationMethod prevApplyMethod; + + private SampleCountLevel prevSampleCount; + + private PerPixelNormalSource prevPerPixelNormals; + + private bool prevCacheAware; + + private bool prevDownscale; + + private bool prevFadeEnabled; + + private float prevFadeToIntensity; + + private float prevFadeToRadius; + + private float prevFadeToPowerExponent; + + private float prevFadeStart; + + private float prevFadeLength; + + private bool prevBlurEnabled; + + private int prevBlurRadius; + + private int prevBlurPasses; + + private Camera m_camera; + + private Material m_occlusionMat; + + private Material m_blurMat; + + private Material m_copyMat; + + private const int RandomSize = 4; + + private const int DirectionCount = 8; + + private Color[] m_randomData; + + private Texture2D m_randomTex; + + private string[] m_layerOffsetNames; + + private string[] m_layerRandomNames; + + private string[] m_layerDepthNames; + + private string[] m_layerNormalNames; + + private string[] m_layerOcclusionNames; + + private RenderTextureFormat m_depthRTFormat = RenderTextureFormat.RFloat; + + private RenderTextureFormat m_normalRTFormat = RenderTextureFormat.ARGB2101010; + + private RenderTextureFormat m_occlusionRTFormat = RenderTextureFormat.RGHalf; + + private RenderTexture m_occlusionRT; + + private int[] m_depthLayerRT; + + private int[] m_normalLayerRT; + + private int[] m_occlusionLayerRT; + + private int m_mrtCount; + + private RenderTargetIdentifier[] m_depthTargets; + + private RenderTargetIdentifier[] m_normalTargets; + + private int m_deinterleaveDepthPass; + + private int m_deinterleaveNormalPass; + + private RenderTargetIdentifier[] m_applyDeferredTargets; + + private Mesh m_blitMesh; + + private TargetDesc m_target = default(TargetDesc); + + private Dictionary<CameraEvent, CommandBuffer> m_registeredCommandBuffers = new Dictionary<CameraEvent, CommandBuffer>(); + + private bool CheckParamsChanged() + { + return prevScreenWidth != m_camera.pixelWidth || prevScreenHeight != m_camera.pixelHeight || prevHDR != m_camera.allowHDR || prevApplyMethod != ApplyMethod || prevSampleCount != SampleCount || prevPerPixelNormals != PerPixelNormals || prevCacheAware != CacheAware || prevDownscale != Downsample || prevFadeEnabled != FadeEnabled || prevFadeToIntensity != FadeToIntensity || prevFadeToRadius != FadeToRadius || prevFadeToPowerExponent != FadeToPowerExponent || prevFadeStart != FadeStart || prevFadeLength != FadeLength || prevBlurEnabled != BlurEnabled || prevBlurRadius != BlurRadius || prevBlurPasses != BlurPasses; + } + + private void UpdateParams() + { + prevScreenWidth = m_camera.pixelWidth; + prevScreenHeight = m_camera.pixelHeight; + prevHDR = m_camera.allowHDR; + prevApplyMethod = ApplyMethod; + prevSampleCount = SampleCount; + prevPerPixelNormals = PerPixelNormals; + prevCacheAware = CacheAware; + prevDownscale = Downsample; + prevFadeEnabled = FadeEnabled; + prevFadeToIntensity = FadeToIntensity; + prevFadeToRadius = FadeToRadius; + prevFadeToPowerExponent = FadeToPowerExponent; + prevFadeStart = FadeStart; + prevFadeLength = FadeLength; + prevBlurEnabled = BlurEnabled; + prevBlurRadius = BlurRadius; + prevBlurPasses = BlurPasses; + } + + private void Warmup() + { + CheckMaterial(); + CheckRandomData(); + m_depthLayerRT = new int[16]; + m_normalLayerRT = new int[16]; + m_occlusionLayerRT = new int[16]; + m_mrtCount = Mathf.Min(SystemInfo.supportedRenderTargetCount, 4); + m_layerOffsetNames = new string[m_mrtCount]; + m_layerRandomNames = new string[m_mrtCount]; + for (int i = 0; i < m_mrtCount; i++) + { + m_layerOffsetNames[i] = "_AO_LayerOffset" + i; + m_layerRandomNames[i] = "_AO_LayerRandom" + i; + } + m_layerDepthNames = new string[16]; + m_layerNormalNames = new string[16]; + m_layerOcclusionNames = new string[16]; + for (int j = 0; j < 16; j++) + { + m_layerDepthNames[j] = "_AO_DepthLayer" + j; + m_layerNormalNames[j] = "_AO_NormalLayer" + j; + m_layerOcclusionNames[j] = "_AO_OcclusionLayer" + j; + } + m_depthTargets = new RenderTargetIdentifier[m_mrtCount]; + m_normalTargets = new RenderTargetIdentifier[m_mrtCount]; + int mrtCount = m_mrtCount; + if (mrtCount == 4) + { + m_deinterleaveDepthPass = 10; + m_deinterleaveNormalPass = 11; + } + else + { + m_deinterleaveDepthPass = 5; + m_deinterleaveNormalPass = 6; + } + m_applyDeferredTargets = new RenderTargetIdentifier[2]; + if (m_blitMesh != null) + { + UnityEngine.Object.DestroyImmediate(m_blitMesh); + } + m_blitMesh = new Mesh(); + m_blitMesh.vertices = new Vector3[4] + { + new Vector3(0f, 0f, 0f), + new Vector3(0f, 1f, 0f), + new Vector3(1f, 1f, 0f), + new Vector3(1f, 0f, 0f) + }; + m_blitMesh.uv = new Vector2[4] + { + new Vector2(0f, 0f), + new Vector2(0f, 1f), + new Vector2(1f, 1f), + new Vector2(1f, 0f) + }; + m_blitMesh.triangles = new int[6] { 0, 1, 2, 0, 2, 3 }; + } + + private void Shutdown() + { + CommandBuffer_UnregisterAll(); + SafeReleaseRT(ref m_occlusionRT); + if (m_occlusionMat != null) + { + UnityEngine.Object.DestroyImmediate(m_occlusionMat); + } + if (m_blurMat != null) + { + UnityEngine.Object.DestroyImmediate(m_blurMat); + } + if (m_copyMat != null) + { + UnityEngine.Object.DestroyImmediate(m_copyMat); + } + if (m_blitMesh != null) + { + UnityEngine.Object.DestroyImmediate(m_blitMesh); + } + } + + private bool CheckRenderTextureFormats() + { + if (SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGB32) && SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf)) + { + m_depthRTFormat = RenderTextureFormat.RFloat; + if (!SystemInfo.SupportsRenderTextureFormat(m_depthRTFormat)) + { + m_depthRTFormat = RenderTextureFormat.RHalf; + if (!SystemInfo.SupportsRenderTextureFormat(m_depthRTFormat)) + { + m_depthRTFormat = RenderTextureFormat.ARGBHalf; + } + } + m_normalRTFormat = RenderTextureFormat.ARGB2101010; + if (!SystemInfo.SupportsRenderTextureFormat(m_normalRTFormat)) + { + m_normalRTFormat = RenderTextureFormat.ARGB32; + } + m_occlusionRTFormat = RenderTextureFormat.RGHalf; + if (!SystemInfo.SupportsRenderTextureFormat(m_occlusionRTFormat)) + { + m_occlusionRTFormat = RenderTextureFormat.RGFloat; + if (!SystemInfo.SupportsRenderTextureFormat(m_occlusionRTFormat)) + { + m_occlusionRTFormat = RenderTextureFormat.ARGBHalf; + } + } + return true; + } + return false; + } + + private void OnEnable() + { + if (!CheckRenderTextureFormats()) + { + Debug.LogError("[AmplifyOcclusion] Target platform does not meet the minimum requirements for this effect to work properly."); + base.enabled = false; + } + else + { + m_camera = GetComponent<Camera>(); + Warmup(); + CommandBuffer_UnregisterAll(); + } + } + + private void OnDisable() + { + Shutdown(); + } + + private void OnDestroy() + { + Shutdown(); + } + + private void Update() + { + if (m_camera.actualRenderingPath != RenderingPath.DeferredShading) + { + if (PerPixelNormals != 0 && PerPixelNormals != PerPixelNormalSource.Camera) + { + PerPixelNormals = PerPixelNormalSource.Camera; + Debug.LogWarning("[AmplifyOcclusion] GBuffer Normals only available in Camera Deferred Shading mode. Switched to Camera source."); + } + if (ApplyMethod == ApplicationMethod.Deferred) + { + ApplyMethod = ApplicationMethod.PostEffect; + Debug.LogWarning("[AmplifyOcclusion] Deferred Method requires a Deferred Shading path. Switching to Post Effect Method."); + } + } + if (ApplyMethod == ApplicationMethod.Deferred && PerPixelNormals == PerPixelNormalSource.Camera) + { + PerPixelNormals = PerPixelNormalSource.GBuffer; + Debug.LogWarning("[AmplifyOcclusion] Camera Normals not supported for Deferred Method. Switching to GBuffer Normals."); + } + if ((m_camera.depthTextureMode & DepthTextureMode.Depth) == 0) + { + m_camera.depthTextureMode |= DepthTextureMode.Depth; + } + if (PerPixelNormals == PerPixelNormalSource.Camera && (m_camera.depthTextureMode & DepthTextureMode.DepthNormals) == 0) + { + m_camera.depthTextureMode |= DepthTextureMode.DepthNormals; + } + CheckMaterial(); + CheckRandomData(); + } + + private void CheckMaterial() + { + if (m_occlusionMat == null) + { + m_occlusionMat = new Material(Shader.Find("Hidden/Amplify Occlusion/Occlusion")) + { + hideFlags = HideFlags.DontSave + }; + } + if (m_blurMat == null) + { + m_blurMat = new Material(Shader.Find("Hidden/Amplify Occlusion/Blur")) + { + hideFlags = HideFlags.DontSave + }; + } + if (m_copyMat == null) + { + m_copyMat = new Material(Shader.Find("Hidden/Amplify Occlusion/Copy")) + { + hideFlags = HideFlags.DontSave + }; + } + } + + private void CheckRandomData() + { + if (m_randomData == null) + { + m_randomData = GenerateRandomizationData(); + } + if (m_randomTex == null) + { + m_randomTex = Resources.Load<Texture2D>("Random4x4"); + } + } + + public static Color[] GenerateRandomizationData() + { + Color[] array = new Color[16]; + int i = 0; + int num = 0; + for (; i < 16; i++) + { + float num2 = RandomTable.Values[num++]; + float b = RandomTable.Values[num++]; + float f = (float)Math.PI * 2f * num2 / 8f; + array[i].r = Mathf.Cos(f); + array[i].g = Mathf.Sin(f); + array[i].b = b; + array[i].a = 0f; + } + return array; + } + + public static Texture2D GenerateRandomizationTexture(Color[] randomPixels) + { + Texture2D texture2D = new Texture2D(4, 4, TextureFormat.ARGB32, mipmap: false, linear: true); + texture2D.hideFlags = HideFlags.DontSave; + Texture2D texture2D2 = texture2D; + texture2D2.name = "RandomTexture"; + texture2D2.filterMode = FilterMode.Point; + texture2D2.wrapMode = TextureWrapMode.Repeat; + texture2D2.SetPixels(randomPixels); + texture2D2.Apply(); + return texture2D2; + } + + private RenderTexture SafeAllocateRT(string name, int width, int height, RenderTextureFormat format, RenderTextureReadWrite readWrite) + { + width = Mathf.Max(width, 1); + height = Mathf.Max(height, 1); + RenderTexture renderTexture = new RenderTexture(width, height, 0, format, readWrite); + renderTexture.hideFlags = HideFlags.DontSave; + RenderTexture renderTexture2 = renderTexture; + renderTexture2.name = name; + renderTexture2.filterMode = FilterMode.Point; + renderTexture2.wrapMode = TextureWrapMode.Clamp; + renderTexture2.Create(); + return renderTexture2; + } + + private void SafeReleaseRT(ref RenderTexture rt) + { + if (rt != null) + { + RenderTexture.active = null; + rt.Release(); + UnityEngine.Object.DestroyImmediate(rt); + rt = null; + } + } + + private int SafeAllocateTemporaryRT(CommandBuffer cb, string propertyName, int width, int height, RenderTextureFormat format = RenderTextureFormat.Default, RenderTextureReadWrite readWrite = RenderTextureReadWrite.Default, FilterMode filterMode = FilterMode.Point) + { + int num = Shader.PropertyToID(propertyName); + cb.GetTemporaryRT(num, width, height, 0, filterMode, format, readWrite); + return num; + } + + private void SafeReleaseTemporaryRT(CommandBuffer cb, int id) + { + cb.ReleaseTemporaryRT(id); + } + + private void SetBlitTarget(CommandBuffer cb, RenderTargetIdentifier[] targets, int targetWidth, int targetHeight) + { + cb.SetGlobalVector("_AO_Target_TexelSize", new Vector4(1f / (float)targetWidth, 1f / (float)targetHeight, targetWidth, targetHeight)); + cb.SetGlobalVector("_AO_Target_Position", Vector2.zero); + cb.SetRenderTarget(targets, targets[0]); + } + + private void SetBlitTarget(CommandBuffer cb, RenderTargetIdentifier target, int targetWidth, int targetHeight) + { + cb.SetGlobalVector("_AO_Target_TexelSize", new Vector4(1f / (float)targetWidth, 1f / (float)targetHeight, targetWidth, targetHeight)); + cb.SetRenderTarget(target); + } + + private void PerformBlit(CommandBuffer cb, Material mat, int pass) + { + cb.DrawMesh(m_blitMesh, Matrix4x4.identity, mat, 0, pass); + } + + private void PerformBlit(CommandBuffer cb, Material mat, int pass, int x, int y) + { + cb.SetGlobalVector("_AO_Target_Position", new Vector2(x, y)); + PerformBlit(cb, mat, pass); + } + + private void PerformBlit(CommandBuffer cb, RenderTargetIdentifier source, int sourceWidth, int sourceHeight, Material mat, int pass) + { + cb.SetGlobalTexture("_AO_Source", source); + cb.SetGlobalVector("_AO_Source_TexelSize", new Vector4(1f / (float)sourceWidth, 1f / (float)sourceHeight, sourceWidth, sourceHeight)); + PerformBlit(cb, mat, pass); + } + + private void PerformBlit(CommandBuffer cb, RenderTargetIdentifier source, int sourceWidth, int sourceHeight, Material mat, int pass, int x, int y) + { + cb.SetGlobalVector("_AO_Target_Position", new Vector2(x, y)); + PerformBlit(cb, source, sourceWidth, sourceHeight, mat, pass); + } + + private CommandBuffer CommandBuffer_Allocate(string name) + { + CommandBuffer commandBuffer = new CommandBuffer(); + commandBuffer.name = name; + return commandBuffer; + } + + private void CommandBuffer_Register(CameraEvent cameraEvent, CommandBuffer commandBuffer) + { + m_camera.AddCommandBuffer(cameraEvent, commandBuffer); + m_registeredCommandBuffers.Add(cameraEvent, commandBuffer); + } + + private void CommandBuffer_Unregister(CameraEvent cameraEvent, CommandBuffer commandBuffer) + { + if (!(m_camera != null)) + { + return; + } + CommandBuffer[] commandBuffers = m_camera.GetCommandBuffers(cameraEvent); + CommandBuffer[] array = commandBuffers; + foreach (CommandBuffer commandBuffer2 in array) + { + if (commandBuffer2.name == commandBuffer.name) + { + m_camera.RemoveCommandBuffer(cameraEvent, commandBuffer2); + } + } + } + + private CommandBuffer CommandBuffer_AllocateRegister(CameraEvent cameraEvent) + { + string text = string.Empty; + switch (cameraEvent) + { + case CameraEvent.BeforeReflections: + text = "AO-BeforeRefl"; + break; + case CameraEvent.AfterLighting: + text = "AO-AfterLighting"; + break; + case CameraEvent.BeforeImageEffectsOpaque: + text = "AO-BeforePostOpaque"; + break; + default: + Debug.LogError("[AmplifyOcclusion] Unsupported CameraEvent. Please contact support."); + break; + } + CommandBuffer commandBuffer = CommandBuffer_Allocate(text); + CommandBuffer_Register(cameraEvent, commandBuffer); + return commandBuffer; + } + + private void CommandBuffer_UnregisterAll() + { + foreach (KeyValuePair<CameraEvent, CommandBuffer> registeredCommandBuffer in m_registeredCommandBuffers) + { + CommandBuffer_Unregister(registeredCommandBuffer.Key, registeredCommandBuffer.Value); + } + m_registeredCommandBuffers.Clear(); + } + + private void UpdateLocalMaterialConstants() + { + if (m_occlusionMat != null) + { + m_occlusionMat.SetTexture("_AO_RandomTexture", m_randomTex); + } + } + + private void UpdateGlobalShaderConstants(TargetDesc target) + { + float num = m_camera.fieldOfView * ((float)Math.PI / 180f); + Vector2 vector = new Vector2(1f / Mathf.Tan(num * 0.5f) * ((float)target.height / (float)target.width), 1f / Mathf.Tan(num * 0.5f)); + Vector2 vector2 = new Vector2(1f / vector.x, 1f / vector.y); + float num2 = ((!m_camera.orthographic) ? ((float)target.height / (Mathf.Tan(num * 0.5f) * 2f)) : ((float)target.height / m_camera.orthographicSize)); + float num3 = Mathf.Clamp(Bias, 0f, 1f); + FadeStart = Mathf.Max(0f, FadeStart); + FadeLength = Mathf.Max(0.01f, FadeLength); + float y = ((!FadeEnabled) ? 0f : (1f / FadeLength)); + Shader.SetGlobalMatrix("_AO_CameraProj", GL.GetGPUProjectionMatrix(Matrix4x4.Ortho(0f, 1f, 0f, 1f, -1f, 100f), renderIntoTexture: false)); + Shader.SetGlobalMatrix("_AO_CameraView", m_camera.worldToCameraMatrix); + Shader.SetGlobalVector("_AO_UVToView", new Vector4(2f * vector2.x, -2f * vector2.y, -1f * vector2.x, 1f * vector2.y)); + Shader.SetGlobalFloat("_AO_HalfProjScale", 0.5f * num2); + Shader.SetGlobalFloat("_AO_Radius", Radius); + Shader.SetGlobalFloat("_AO_PowExponent", PowerExponent); + Shader.SetGlobalFloat("_AO_Bias", num3); + Shader.SetGlobalFloat("_AO_Multiplier", 1f / (1f - num3)); + Shader.SetGlobalFloat("_AO_BlurSharpness", BlurSharpness); + Shader.SetGlobalColor("_AO_Levels", new Color(Tint.r, Tint.g, Tint.b, Intensity)); + Shader.SetGlobalVector("_AO_FadeParams", new Vector2(FadeStart, y)); + Shader.SetGlobalVector("_AO_FadeValues", new Vector3(FadeToIntensity, FadeToRadius, FadeToPowerExponent)); + } + + private void CommandBuffer_FillComputeOcclusion(CommandBuffer cb, TargetDesc target) + { + CheckMaterial(); + CheckRandomData(); + cb.SetGlobalVector("_AO_Buffer_PadScale", new Vector4(target.padRatioWidth, target.padRatioHeight, 1f / target.padRatioWidth, 1f / target.padRatioHeight)); + cb.SetGlobalVector("_AO_Buffer_TexelSize", new Vector4(1f / (float)target.width, 1f / (float)target.height, target.width, target.height)); + cb.SetGlobalVector("_AO_QuarterBuffer_TexelSize", new Vector4(1f / (float)target.quarterWidth, 1f / (float)target.quarterHeight, target.quarterWidth, target.quarterHeight)); + cb.SetGlobalFloat("_AO_MaxRadiusPixels", Mathf.Min(target.width, target.height)); + if (m_occlusionRT == null || m_occlusionRT.width != target.width || m_occlusionRT.height != target.height || !m_occlusionRT.IsCreated()) + { + SafeReleaseRT(ref m_occlusionRT); + m_occlusionRT = SafeAllocateRT("_AO_OcclusionTexture", target.width, target.height, m_occlusionRTFormat, RenderTextureReadWrite.Linear); + } + int num = -1; + if (Downsample) + { + num = SafeAllocateTemporaryRT(cb, "_AO_SmallOcclusionTexture", target.width / 2, target.height / 2, m_occlusionRTFormat, RenderTextureReadWrite.Linear, FilterMode.Bilinear); + } + if (CacheAware && !Downsample) + { + int num2 = SafeAllocateTemporaryRT(cb, "_AO_OcclusionAtlas", target.width, target.height, m_occlusionRTFormat, RenderTextureReadWrite.Linear); + for (int i = 0; i < 16; i++) + { + m_depthLayerRT[i] = SafeAllocateTemporaryRT(cb, m_layerDepthNames[i], target.quarterWidth, target.quarterHeight, m_depthRTFormat, RenderTextureReadWrite.Linear); + m_normalLayerRT[i] = SafeAllocateTemporaryRT(cb, m_layerNormalNames[i], target.quarterWidth, target.quarterHeight, m_normalRTFormat, RenderTextureReadWrite.Linear); + m_occlusionLayerRT[i] = SafeAllocateTemporaryRT(cb, m_layerOcclusionNames[i], target.quarterWidth, target.quarterHeight, m_occlusionRTFormat, RenderTextureReadWrite.Linear); + } + for (int j = 0; j < 16; j += m_mrtCount) + { + for (int k = 0; k < m_mrtCount; k++) + { + int num3 = k + j; + int num4 = num3 & 3; + int num5 = num3 >> 2; + cb.SetGlobalVector(m_layerOffsetNames[k], new Vector2((float)num4 + 0.5f, (float)num5 + 0.5f)); + ref RenderTargetIdentifier reference = ref m_depthTargets[k]; + reference = m_depthLayerRT[num3]; + ref RenderTargetIdentifier reference2 = ref m_normalTargets[k]; + reference2 = m_normalLayerRT[num3]; + } + SetBlitTarget(cb, m_depthTargets, target.quarterWidth, target.quarterHeight); + PerformBlit(cb, m_occlusionMat, m_deinterleaveDepthPass); + SetBlitTarget(cb, m_normalTargets, target.quarterWidth, target.quarterHeight); + PerformBlit(cb, m_occlusionMat, (int)(m_deinterleaveNormalPass + PerPixelNormals)); + } + for (int l = 0; l < 16; l++) + { + cb.SetGlobalVector("_AO_LayerOffset", new Vector2((float)(l & 3) + 0.5f, (float)(l >> 2) + 0.5f)); + cb.SetGlobalVector("_AO_LayerRandom", m_randomData[l]); + cb.SetGlobalTexture("_AO_NormalTexture", m_normalLayerRT[l]); + cb.SetGlobalTexture("_AO_DepthTexture", m_depthLayerRT[l]); + SetBlitTarget(cb, m_occlusionLayerRT[l], target.quarterWidth, target.quarterHeight); + PerformBlit(cb, m_occlusionMat, (int)(15 + SampleCount)); + } + SetBlitTarget(cb, num2, target.width, target.height); + for (int m = 0; m < 16; m++) + { + int x = (m & 3) * target.quarterWidth; + int y = (m >> 2) * target.quarterHeight; + PerformBlit(cb, m_occlusionLayerRT[m], target.quarterWidth, target.quarterHeight, m_copyMat, 0, x, y); + } + cb.SetGlobalTexture("_AO_OcclusionAtlas", num2); + SetBlitTarget(cb, m_occlusionRT, target.width, target.height); + PerformBlit(cb, m_occlusionMat, 19); + for (int n = 0; n < 16; n++) + { + SafeReleaseTemporaryRT(cb, m_occlusionLayerRT[n]); + SafeReleaseTemporaryRT(cb, m_normalLayerRT[n]); + SafeReleaseTemporaryRT(cb, m_depthLayerRT[n]); + } + SafeReleaseTemporaryRT(cb, num2); + } + else + { + int pass = (int)(20 + (int)SampleCount * 4 + PerPixelNormals); + if (Downsample) + { + cb.Blit(null, new RenderTargetIdentifier(num), m_occlusionMat, pass); + SetBlitTarget(cb, m_occlusionRT, target.width, target.height); + PerformBlit(cb, num, target.width / 2, target.height / 2, m_occlusionMat, 41); + } + else + { + cb.Blit(null, m_occlusionRT, m_occlusionMat, pass); + } + } + if (BlurEnabled) + { + int num6 = SafeAllocateTemporaryRT(cb, "_AO_TEMP", target.width, target.height, m_occlusionRTFormat, RenderTextureReadWrite.Linear); + for (int num7 = 0; num7 < BlurPasses; num7++) + { + SetBlitTarget(cb, num6, target.width, target.height); + PerformBlit(cb, m_occlusionRT, target.width, target.height, m_blurMat, (BlurRadius - 1) * 2); + SetBlitTarget(cb, m_occlusionRT, target.width, target.height); + PerformBlit(cb, num6, target.width, target.height, m_blurMat, 1 + (BlurRadius - 1) * 2); + } + SafeReleaseTemporaryRT(cb, num6); + } + if (Downsample && num >= 0) + { + SafeReleaseTemporaryRT(cb, num); + } + cb.SetRenderTarget((Texture)null); + } + + private void CommandBuffer_FillApplyDeferred(CommandBuffer cb, TargetDesc target, bool logTarget) + { + cb.SetGlobalTexture("_AO_OcclusionTexture", m_occlusionRT); + ref RenderTargetIdentifier reference = ref m_applyDeferredTargets[0]; + reference = BuiltinRenderTextureType.GBuffer0; + ref RenderTargetIdentifier reference2 = ref m_applyDeferredTargets[1]; + reference2 = ((!logTarget) ? BuiltinRenderTextureType.CameraTarget : BuiltinRenderTextureType.GBuffer3); + if (!logTarget) + { + SetBlitTarget(cb, m_applyDeferredTargets, target.fullWidth, target.fullHeight); + PerformBlit(cb, m_occlusionMat, 37); + } + else + { + int num = SafeAllocateTemporaryRT(cb, "_AO_GBufferAlbedo", target.fullWidth, target.fullHeight, RenderTextureFormat.ARGB32); + int num2 = SafeAllocateTemporaryRT(cb, "_AO_GBufferEmission", target.fullWidth, target.fullHeight, RenderTextureFormat.ARGB32); + cb.Blit(m_applyDeferredTargets[0], num); + cb.Blit(m_applyDeferredTargets[1], num2); + cb.SetGlobalTexture("_AO_GBufferAlbedo", num); + cb.SetGlobalTexture("_AO_GBufferEmission", num2); + SetBlitTarget(cb, m_applyDeferredTargets, target.fullWidth, target.fullHeight); + PerformBlit(cb, m_occlusionMat, 38); + SafeReleaseTemporaryRT(cb, num); + SafeReleaseTemporaryRT(cb, num2); + } + cb.SetRenderTarget((Texture)null); + } + + private void CommandBuffer_FillApplyPostEffect(CommandBuffer cb, TargetDesc target, bool logTarget) + { + cb.SetGlobalTexture("_AO_OcclusionTexture", m_occlusionRT); + if (!logTarget) + { + SetBlitTarget(cb, BuiltinRenderTextureType.CameraTarget, target.fullWidth, target.fullHeight); + PerformBlit(cb, m_occlusionMat, 39); + } + else + { + int num = SafeAllocateTemporaryRT(cb, "_AO_GBufferEmission", target.fullWidth, target.fullHeight, RenderTextureFormat.ARGB32); + cb.Blit(BuiltinRenderTextureType.GBuffer3, num); + cb.SetGlobalTexture("_AO_GBufferEmission", num); + SetBlitTarget(cb, BuiltinRenderTextureType.GBuffer3, target.fullWidth, target.fullHeight); + PerformBlit(cb, m_occlusionMat, 40); + SafeReleaseTemporaryRT(cb, num); + } + cb.SetRenderTarget((Texture)null); + } + + private void CommandBuffer_FillApplyDebug(CommandBuffer cb, TargetDesc target) + { + cb.SetGlobalTexture("_AO_OcclusionTexture", m_occlusionRT); + SetBlitTarget(cb, BuiltinRenderTextureType.CameraTarget, target.fullWidth, target.fullHeight); + PerformBlit(cb, m_occlusionMat, 36); + cb.SetRenderTarget((Texture)null); + } + + private void CommandBuffer_Rebuild(TargetDesc target) + { + bool flag = PerPixelNormals == PerPixelNormalSource.GBuffer || PerPixelNormals == PerPixelNormalSource.GBufferOctaEncoded; + CommandBuffer commandBuffer = null; + CameraEvent cameraEvent = ((!flag) ? CameraEvent.BeforeImageEffectsOpaque : CameraEvent.AfterLighting); + if (ApplyMethod == ApplicationMethod.Debug) + { + commandBuffer = CommandBuffer_AllocateRegister(cameraEvent); + CommandBuffer_FillComputeOcclusion(commandBuffer, target); + CommandBuffer_FillApplyDebug(commandBuffer, target); + return; + } + bool logTarget = !m_camera.allowHDR && flag; + cameraEvent = ((ApplyMethod != ApplicationMethod.Deferred) ? cameraEvent : CameraEvent.BeforeReflections); + commandBuffer = CommandBuffer_AllocateRegister(cameraEvent); + CommandBuffer_FillComputeOcclusion(commandBuffer, target); + if (ApplyMethod == ApplicationMethod.PostEffect) + { + CommandBuffer_FillApplyPostEffect(commandBuffer, target, logTarget); + } + else if (ApplyMethod == ApplicationMethod.Deferred) + { + CommandBuffer_FillApplyDeferred(commandBuffer, target, logTarget); + } + } + + private void OnPreRender() + { + bool allowHDR = m_camera.allowHDR; + m_target.fullWidth = m_camera.pixelWidth; + m_target.fullHeight = m_camera.pixelHeight; + m_target.format = (allowHDR ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32); + m_target.width = ((!CacheAware) ? m_target.fullWidth : ((m_target.fullWidth + 3) & -4)); + m_target.height = ((!CacheAware) ? m_target.fullHeight : ((m_target.fullHeight + 3) & -4)); + m_target.quarterWidth = m_target.width / 4; + m_target.quarterHeight = m_target.height / 4; + m_target.padRatioWidth = (float)m_target.width / (float)m_target.fullWidth; + m_target.padRatioHeight = (float)m_target.height / (float)m_target.fullHeight; + UpdateLocalMaterialConstants(); + UpdateGlobalShaderConstants(m_target); + if (CheckParamsChanged() || m_registeredCommandBuffers.Count == 0) + { + CommandBuffer_UnregisterAll(); + CommandBuffer_Rebuild(m_target); + UpdateParams(); + } + } + + private void OnPostRender() + { + m_occlusionRT.MarkRestoreExpected(); + } +} diff --git a/AmplifyOcclusionEffect.cs b/AmplifyOcclusionEffect.cs new file mode 100644 index 0000000..302526c --- /dev/null +++ b/AmplifyOcclusionEffect.cs @@ -0,0 +1,7 @@ +using UnityEngine; + +[ExecuteInEditMode] +[AddComponentMenu("Image Effects/Amplify Occlusion")] +public class AmplifyOcclusionEffect : AmplifyOcclusionBase +{ +} diff --git a/AnimationHandler.cs b/AnimationHandler.cs new file mode 100644 index 0000000..6011e47 --- /dev/null +++ b/AnimationHandler.cs @@ -0,0 +1,14 @@ +using UnityEngine; + +public class AnimationHandler : MonoBehaviour +{ + public int animationState; + + private void Start() + { + } + + private void Update() + { + } +} diff --git a/AnimationObject.cs b/AnimationObject.cs new file mode 100644 index 0000000..0c2d636 --- /dev/null +++ b/AnimationObject.cs @@ -0,0 +1,140 @@ +using UnityEngine; +using UnityEngine.Events; + +public class AnimationObject : MonoBehaviour +{ + public PhysicsAnimation[] animations; + + private Rigidbody rig; + + private StepHandler stepHandler; + + private Transform hip; + + public float smoothing; + + public float multiplier = 1f; + + private bool isCurrentlyLeft; + + public bool isLeft; + + public UnityEvent switchToForwardEvent; + + public UnityEvent switchToBackwardsEvent; + + public bool dontAnimateIfHoldingSomething; + + private Holding holding; + + private AnimationHandler animationHandler; + + private PlayerDeath death; + + private float muscleMultiplier = 1f; + + private void Start() + { + animationHandler = base.transform.root.GetComponent<AnimationHandler>(); + rig = GetComponent<Rigidbody>(); + stepHandler = base.transform.root.GetComponent<StepHandler>(); + holding = base.transform.root.GetComponent<Holding>(); + death = base.transform.root.GetComponent<PlayerDeath>(); + Hip componentInChildren = base.transform.root.GetComponentInChildren<Hip>(); + if ((bool)componentInChildren) + { + hip = componentInChildren.transform; + } + } + + private void FixedUpdate() + { + if ((bool)death) + { + if (death.muscleFunction < 0f) + { + return; + } + muscleMultiplier = death.muscleFunction; + } + if ((!holding || !dontAnimateIfHoldingSomething || !holding.heldObject) && animationHandler.animationState < animations.Length) + { + SetMultiplier(); + AddTorque(); + AddForce(); + } + } + + private void AddForce() + { + Vector3 vector = Vector3.zero; + if (isCurrentlyLeft == isLeft) + { + Vector3 forwardForce = animations[animationHandler.animationState].forwardForce; + if (animations[animationHandler.animationState].forceSpace == PhysicsAnimation.ForceSpace.World) + { + vector = forwardForce; + } + if (animations[animationHandler.animationState].forceSpace == PhysicsAnimation.ForceSpace.Hip) + { + vector = hip.TransformDirection(forwardForce); + } + } + else + { + Vector3 backwardsForce = animations[animationHandler.animationState].backwardsForce; + if (animations[animationHandler.animationState].forceSpace == PhysicsAnimation.ForceSpace.World) + { + vector = backwardsForce; + } + if (animations[animationHandler.animationState].forceSpace == PhysicsAnimation.ForceSpace.Hip) + { + vector = hip.TransformDirection(backwardsForce); + } + } + rig.AddForce(vector * muscleMultiplier * multiplier, ForceMode.Acceleration); + } + + private void AddTorque() + { + Vector3 vector = ((isCurrentlyLeft != isLeft) ? hip.TransformDirection(animations[animationHandler.animationState].backwardsTorque) : hip.TransformDirection(animations[animationHandler.animationState].forwardTorque)); + rig.AddTorque(vector * muscleMultiplier * multiplier, ForceMode.Acceleration); + } + + private void SetMultiplier() + { + if (smoothing != 0f) + { + float b = 1f; + if (isCurrentlyLeft != stepHandler.isLeft) + { + b = 0f; + } + multiplier = Mathf.Lerp(multiplier, b, 1f / smoothing); + if (multiplier < 0.1f) + { + ChangeStep(); + } + } + else + { + ChangeStep(); + } + } + + private void ChangeStep() + { + if (isCurrentlyLeft != stepHandler.isLeft) + { + if (stepHandler.isLeft == isLeft) + { + switchToForwardEvent.Invoke(); + } + else + { + switchToBackwardsEvent.Invoke(); + } + isCurrentlyLeft = stepHandler.isLeft; + } + } +} diff --git a/ArchiveScript.cs b/ArchiveScript.cs new file mode 100644 index 0000000..1f23c24 --- /dev/null +++ b/ArchiveScript.cs @@ -0,0 +1,61 @@ +using UnityEngine; +using UnityEngine.UI; + +public class ArchiveScript : MonoBehaviour +{ + private static ArchiveScript intance; + + public Image bar; + + public CanvasGroup escapeCG; + + public CanvasGroup wholeCG; + + private bool hide; + + private float escapeCounter; + + private void Start() + { + if (intance == null) + { + intance = this; + Object.DontDestroyOnLoad(base.gameObject); + } + else + { + Object.Destroy(intance.gameObject); + } + } + + private void Update() + { + if (Input.GetKeyDown(KeyCode.H)) + { + hide = !hide; + if (hide) + { + wholeCG.alpha = 0f; + } + else + { + wholeCG.alpha = 1f; + } + } + if (Input.GetKey(KeyCode.Escape)) + { + escapeCounter += Time.deltaTime; + if (escapeCounter > 1f) + { + Application.Quit(); + } + } + else + { + escapeCounter -= Time.deltaTime; + } + escapeCounter = Mathf.Clamp(escapeCounter, 0f, 2f); + escapeCG.alpha = escapeCounter * 2f; + bar.fillAmount = escapeCounter; + } +} diff --git a/ArmLeft.cs b/ArmLeft.cs new file mode 100644 index 0000000..b7ee14c --- /dev/null +++ b/ArmLeft.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class ArmLeft : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/ArmRight.cs b/ArmRight.cs new file mode 100644 index 0000000..735d646 --- /dev/null +++ b/ArmRight.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class ArmRight : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/AvaragePosition.cs b/AvaragePosition.cs new file mode 100644 index 0000000..cea74d6 --- /dev/null +++ b/AvaragePosition.cs @@ -0,0 +1,26 @@ +using UnityEngine; + +public class AvaragePosition : MonoBehaviour +{ + public Transform[] transforms; + + private Transform rotationHelper; + + public Vector3 offset; + + private void Start() + { + rotationHelper = base.transform.root.GetComponentInChildren<RotationTarget>().transform; + } + + private void LateUpdate() + { + Vector3 zero = Vector3.zero; + for (int i = 0; i < transforms.Length; i++) + { + zero += transforms[i].position; + } + zero /= (float)transforms.Length; + base.transform.position = zero + rotationHelper.TransformDirection(offset); + } +} diff --git a/Balance.cs b/Balance.cs new file mode 100644 index 0000000..dc9ae60 --- /dev/null +++ b/Balance.cs @@ -0,0 +1,101 @@ +using UnityEngine; + +public class Balance : MonoBehaviour +{ + private Rigidbody handLeft; + + private Rigidbody handRight; + + private Rigidbody footLeft; + + private Rigidbody footRight; + + private Rigidbody hip; + + private Vector3 centerOfMass; + + private Rigidbody[] allRigs; + + public float[] balanceForce; + + public float[] footCenterForces; + + private AnimationHandler animationHandler; + + private PlayerDeath death; + + private Strength str; + + private float muscleMultiplier; + + private void Start() + { + death = GetComponent<PlayerDeath>(); + str = GetComponent<Strength>(); + allRigs = GetComponentsInChildren<Rigidbody>(); + HandLeft componentInChildren = GetComponentInChildren<HandLeft>(); + if ((bool)componentInChildren) + { + handLeft = componentInChildren.GetComponent<Rigidbody>(); + } + HandRight componentInChildren2 = GetComponentInChildren<HandRight>(); + if ((bool)componentInChildren2) + { + handRight = componentInChildren2.GetComponent<Rigidbody>(); + } + footLeft = GetComponentInChildren<KneeLeft>().GetComponent<Rigidbody>(); + footRight = GetComponentInChildren<KneeRight>().GetComponent<Rigidbody>(); + hip = GetComponentInChildren<Hip>().GetComponent<Rigidbody>(); + animationHandler = GetComponent<AnimationHandler>(); + } + + private void FixedUpdate() + { + if (!death.dead) + { + muscleMultiplier = str.strength; + centerOfMass = Vector3.zero; + Rigidbody[] array = allRigs; + foreach (Rigidbody rigidbody in array) + { + centerOfMass += rigidbody.worldCenterOfMass; + } + centerOfMass /= (float)allRigs.Length; + centerOfMass.y = 0f; + BalanceLegs(); + CenterLegs(); + } + } + + private void CenterLegs() + { + Vector3 vector = footLeft.transform.position + footLeft.transform.forward * 0.5f; + Vector3 vector2 = footRight.transform.position + footRight.transform.forward * 0.5f; + Vector3 vector3 = vector; + if (vector.y + 0.3f < hip.worldCenterOfMass.y) + { + vector3.y = 0f; + footLeft.AddForceAtPosition((centerOfMass - vector3) * muscleMultiplier * footCenterForces[animationHandler.animationState], vector, ForceMode.Acceleration); + } + Vector3 vector4 = vector2; + if (vector4.y + 0.3f < hip.worldCenterOfMass.y) + { + vector4.y = 0f; + footRight.AddForceAtPosition((centerOfMass - vector4) * muscleMultiplier * footCenterForces[animationHandler.animationState], vector2, ForceMode.Acceleration); + } + } + + private void BalanceLegs() + { + Vector3 vector = footLeft.transform.position + footLeft.transform.forward * 0.5f; + Vector3 vector2 = footRight.transform.position + footRight.transform.forward * 0.5f; + Vector3 vector3 = (vector + vector2) / 2f; + if (!(vector3.y + 0.3f > hip.worldCenterOfMass.y)) + { + vector3.y = 0f; + Vector3 vector4 = centerOfMass - vector3; + footLeft.AddForceAtPosition(vector4 * muscleMultiplier * balanceForce[animationHandler.animationState], vector, ForceMode.Acceleration); + footRight.AddForceAtPosition(vector4 * muscleMultiplier * balanceForce[animationHandler.animationState], vector2, ForceMode.Acceleration); + } + } +} diff --git a/CameraMovement.cs b/CameraMovement.cs new file mode 100644 index 0000000..a94012a --- /dev/null +++ b/CameraMovement.cs @@ -0,0 +1,136 @@ +using UnityEngine; + +public class CameraMovement : MonoBehaviour +{ + public Camera camera; + + public Transform positionTarget; + + public Transform headPosition; + + public Transform rotationTarget; + + public Transform bobberTarget; + + private StandingDataHandler standingData; + + private float fallingValue; + + private float fallingEffectValue; + + private float minBobble = 0.02f; + + public bool ADS; + + public DamageEffects effects; + + private WeaponHandler weaponHandler; + + private Rigidbody hip; + + private HasControl hasControl; + + private HeadCollisionHandler headCollisionHandler; + + private MovementDataHandler movementData; + + private Rigidbody torso; + + private PlayerDeath death; + + private Strength str; + + private Vector3 cameraCurrentRelativeADSPosition = Vector3.zero; + + private Vector3 movementADSVelocity = Vector3.zero; + + private Vector3 ADSMovementPosition = Vector3.zero; + + private void Start() + { + torso = base.transform.root.GetComponentInChildren<Torso>().GetComponent<Rigidbody>(); + headCollisionHandler = base.transform.root.GetComponentInChildren<HeadCollisionHandler>(); + standingData = base.transform.GetComponentInParent<StandingDataHandler>(); + movementData = base.transform.GetComponentInParent<MovementDataHandler>(); + weaponHandler = base.transform.GetComponentInParent<WeaponHandler>(); + camera = GetComponentInChildren<Camera>(); + hip = base.transform.root.GetComponentInChildren<Hip>().GetComponent<Rigidbody>(); + hasControl = base.transform.root.GetComponent<HasControl>(); + death = base.transform.root.GetComponent<PlayerDeath>(); + str = base.transform.root.GetComponent<Strength>(); + effects = base.transform.root.GetComponent<DamageEffects>(); + } + + private void LateUpdate() + { + if (hasControl.hasControl) + { + headCollisionHandler.collisionValue = 0f; + if (standingData.sinceLanded > 1f) + { + fallingValue = Mathf.Clamp(standingData.sinceGrounded - 0.5f, 0f, 10f) * 0.5f; + } + if (standingData.sinceGrounded > 0.5f || standingData.sinceLanded < 0.5f) + { + fallingEffectValue = Mathf.Lerp(fallingEffectValue, fallingValue, Time.smoothDeltaTime * 15f); + } + else + { + fallingEffectValue = Mathf.Lerp(fallingEffectValue, minBobble, Time.smoothDeltaTime * 3f); + } + float physicsValue = GetPhysicsValue(); + Vector3 vector = Vector3.Lerp(positionTarget.position, bobberTarget.position, Mathf.Clamp(physicsValue + headCollisionHandler.collisionValue, 0f, 1f)); + Vector3 position = vector; + position.y = base.transform.position.y; + base.transform.position = position; + base.transform.position = vector; + base.transform.rotation = Quaternion.Lerp(rotationTarget.rotation, bobberTarget.rotation, Mathf.Clamp(physicsValue + Mathf.Clamp(headCollisionHandler.collisionValue, 0f, 0.4f), 0f, 1f)); + SetCameraPosition(); + } + } + + private void SetCameraPosition() + { + if (ADS && (bool)weaponHandler.gunADS) + { + cameraCurrentRelativeADSPosition = Vector3.Lerp(cameraCurrentRelativeADSPosition, Vector3.zero, Time.deltaTime * 20f); + camera.transform.position = weaponHandler.gunADS.TransformPoint(cameraCurrentRelativeADSPosition) + ADSMovementPosition; + camera.fieldOfView = Mathf.Lerp(camera.fieldOfView, weaponHandler.ADSFOV, Time.deltaTime * 20f); + return; + } + if ((bool)weaponHandler && (bool)weaponHandler.gunADS) + { + cameraCurrentRelativeADSPosition = weaponHandler.gunADS.InverseTransformPoint(camera.transform.position); + } + camera.transform.localPosition = Vector3.Lerp(camera.transform.localPosition, Vector3.zero, Time.deltaTime * 20f); + camera.fieldOfView = Mathf.Lerp(camera.fieldOfView, 90f, Time.deltaTime * 20f); + } + + private void FixedUpdate() + { + if (hasControl.hasControl && (bool)weaponHandler && (bool)weaponHandler.rightGun) + { + movementADSVelocity += (weaponHandler.rightGun.rig.velocity - hip.velocity) * 0.01f; + movementADSVelocity += -ADSMovementPosition * 3f; + movementADSVelocity *= 0.8f; + } + } + + private void Update() + { + if (hasControl.hasControl) + { + ADSMovementPosition += movementADSVelocity * Time.deltaTime; + } + } + + private float GetPhysicsValue() + { + float result = fallingEffectValue * 0.3f + (1f - str.strength) + effects.damageValue; + if (death.dead) + { + result = 1f; + } + return result; + } +} diff --git a/CameraRecoil.cs b/CameraRecoil.cs new file mode 100644 index 0000000..e82532a --- /dev/null +++ b/CameraRecoil.cs @@ -0,0 +1,49 @@ +using UnityEngine; + +public class CameraRecoil : MonoBehaviour +{ + public Transform yRotation; + + public Transform xRotation; + + private float counter; + + private float lastValue; + + private AnimationCurve usedCurve; + + private float deltaValue; + + private float xRecoil; + + private float yRecoil; + + private bool hasCurve; + + private void Start() + { + } + + private void Update() + { + if (hasCurve && counter < usedCurve.keys[usedCurve.length - 1].time) + { + float num = usedCurve.Evaluate(counter); + counter += Time.deltaTime; + deltaValue = num - lastValue; + lastValue = num; + xRotation.Rotate(Vector3.up * Time.deltaTime * xRecoil * deltaValue, Space.World); + yRotation.Rotate(Vector3.right * Time.deltaTime * yRecoil * deltaValue, Space.Self); + } + } + + public void AddRecoil(Vector2 recoil, AnimationCurve curve) + { + counter = 0f; + lastValue = curve.Evaluate(0f); + usedCurve = curve; + xRecoil = recoil.x * 30f; + yRecoil = recoil.y * -30f; + hasCurve = true; + } +} diff --git a/CameraWobble.cs b/CameraWobble.cs new file mode 100644 index 0000000..2bd1236 --- /dev/null +++ b/CameraWobble.cs @@ -0,0 +1,18 @@ +using UnityEngine; + +public class CameraWobble : MonoBehaviour +{ + public Transform target; + + private void Start() + { + } + + private void LateUpdate() + { + if ((bool)target) + { + base.transform.localRotation = target.rotation; + } + } +} @@ -0,0 +1,143 @@ +using UnityEngine; + +public class Car : MonoBehaviour +{ + public float forwardForceMultiplier = 1f; + + public float breakForce = 1f; + + public float glide = 1f; + + private float thrust; + + public AnimationCurve driftCurveGas; + + public AnimationCurve driftBreakForceCurve; + + public AnimationCurve driftVecloityForceCurve; + + public AnimationCurve driftTurnCurve; + + public AnimationCurve lowSpeedGripCurve; + + public AnimationCurve speedTurnCurve; + + public AnimationCurve useWheelToTurnCurve; + + private float driftAmount; + + private WobbleShake shake; + + public Rigidbody mainRig; + + public float turnTorque = 1f; + + public float downwardsForce; + + private GenericInputHandler input; + + private CollisionChecker[] checkers; + + private Collider[] wheelColliders; + + private float sinceGrounded; + + private Wheel[] wheels; + + private void Start() + { + checkers = GetComponentsInChildren<CollisionChecker>(); + wheels = GetComponentsInChildren<Wheel>(); + input = GetComponent<GenericInputHandler>(); + shake = base.transform.root.GetComponentInChildren<WobbleShake>(); + Transform parent = GetComponentInChildren<Wheel>().transform.parent; + wheelColliders = parent.GetComponentsInChildren<Collider>(); + } + + private void FixedUpdate() + { + float num = 1f; + if (mainRig.transform.InverseTransformDirection(mainRig.velocity).z < 0f) + { + num = -1f; + } + float num2 = Mathf.Clamp(Vector3.Angle(mainRig.velocity, mainRig.transform.forward * num), 10f, 90f); + float num3 = Mathf.Clamp(Vector3.Angle(mainRig.velocity, mainRig.transform.forward * num), 1f, 90f); + float z = mainRig.transform.InverseTransformDirection(mainRig.velocity).z; + thrust = Mathf.Clamp(input.inputDirection.z, -0.7f, 1f); + float num4 = speedTurnCurve.Evaluate(z); + float num5 = 1f; + num5 = 0f; + for (int i = 0; i < checkers.Length; i++) + { + if (checkers[i].sinceGrounded < 0.1f) + { + num5 += 1f / (float)checkers.Length; + } + } + if (num5 == 0f) + { + sinceGrounded += Time.deltaTime; + } + else + { + if ((double)sinceGrounded > 0.5) + { + shake.AddShake(base.transform.forward * 0.5f * Mathf.Clamp(sinceGrounded, 0f, 5f), 0.9f); + } + sinceGrounded = 0f; + } + if (num5 > 0f) + { + mainRig.angularVelocity *= 0.98f; + if (input.space) + { + driftAmount = Mathf.Lerp(driftAmount, 1f, Time.fixedDeltaTime * 2f); + if (driftAmount > 0.7f) + { + mainRig.angularVelocity *= 0.98f; + } + } + else + { + driftAmount = Mathf.Lerp(driftAmount, 0f, Time.fixedDeltaTime * 3f); + } + } + float num6 = driftCurveGas.Evaluate(Mathf.Clamp(num3, driftAmount * 45f, 999f) / 10f); + Collider[] array = wheelColliders; + foreach (Collider collider in array) + { + collider.material.dynamicFriction = Mathf.Clamp(5f / mainRig.velocity.magnitude - 0.2f, 0f, 0.5f); + } + if (mainRig.velocity.magnitude > 10f) + { + shake.AddShakeWorld(Random.insideUnitSphere * (Mathf.Clamp(num3 / 10f - 1f, 0f, 40f) * mainRig.velocity.magnitude * 0.01f) * 0.5f, 0.8f); + shake.AddShake(Vector3.up * (Mathf.Clamp(num3 / 10f - 1f, 0f, 90f) * mainRig.velocity.magnitude * -0.03f) * 0.1f, 0.8f); + } + Wheel[] array2 = wheels; + foreach (Wheel wheel in array2) + { + if (wheel.isActive) + { + mainRig.AddForce(-mainRig.transform.up * mainRig.velocity.magnitude * downwardsForce * num5, ForceMode.Acceleration); + mainRig.AddTorque(mainRig.transform.up * (1f + driftAmount * 0.5f) * input.inputDirection.x * driftTurnCurve.Evaluate(num3 / 90f) * num4 * turnTorque * num5, ForceMode.Acceleration); + Vector3 normalized = Vector3.Lerp(mainRig.transform.forward, wheel.forward, useWheelToTurnCurve.Evaluate(mainRig.velocity.magnitude)).normalized; + Vector3 vector = normalized * forwardForceMultiplier * num5 * (1f + Mathf.Clamp(Vector3.Angle(mainRig.transform.forward, mainRig.velocity), 0f, 20f) * 0.01f); + if (thrust != 0f) + { + vector *= thrust; + } + Vector3 vector2 = Vector3.ProjectOnPlane(vector, mainRig.velocity); + Vector3 force = vector - vector2; + mainRig.AddForceAtPosition(vector2, wheel.transform.position, ForceMode.Acceleration); + if (thrust != 0f) + { + mainRig.AddForceAtPosition(force, wheel.transform.position, ForceMode.Acceleration); + } + mainRig.AddForceAtPosition(-mainRig.velocity * forwardForceMultiplier * 0.02f * num5, wheel.transform.position, ForceMode.Acceleration); + mainRig.AddForce(mainRig.velocity * breakForce * -1f * driftBreakForceCurve.Evaluate(num3 / 10f) * num5, ForceMode.Acceleration); + mainRig.AddForce(-mainRig.transform.right * mainRig.transform.InverseTransformDirection(mainRig.velocity).x * 0.2f * num5 * glide * 10f / num6, ForceMode.Acceleration); + } + } + } +} diff --git a/CenterOfMass.cs b/CenterOfMass.cs new file mode 100644 index 0000000..9acb727 --- /dev/null +++ b/CenterOfMass.cs @@ -0,0 +1,14 @@ +using UnityEngine; + +public class CenterOfMass : MonoBehaviour +{ + private void Start() + { + Rigidbody componentInParent = GetComponentInParent<Rigidbody>(); + componentInParent.centerOfMass = componentInParent.transform.InverseTransformPoint(base.transform.position); + } + + private void Update() + { + } +} diff --git a/ChatController.cs b/ChatController.cs new file mode 100644 index 0000000..d98a965 --- /dev/null +++ b/ChatController.cs @@ -0,0 +1,34 @@ +using System; +using TMPro; +using UnityEngine; +using UnityEngine.UI; + +public class ChatController : MonoBehaviour +{ + public TMP_InputField TMP_ChatInput; + + public TMP_Text TMP_ChatOutput; + + public Scrollbar ChatScrollbar; + + private void OnEnable() + { + TMP_ChatInput.onSubmit.AddListener(AddToChatOutput); + } + + private void OnDisable() + { + TMP_ChatInput.onSubmit.RemoveListener(AddToChatOutput); + } + + private void AddToChatOutput(string newText) + { + TMP_ChatInput.text = string.Empty; + DateTime now = DateTime.Now; + TMP_Text tMP_ChatOutput = TMP_ChatOutput; + string text = tMP_ChatOutput.text; + tMP_ChatOutput.text = text + "[<#FFFF80>" + now.Hour.ToString("d2") + ":" + now.Minute.ToString("d2") + ":" + now.Second.ToString("d2") + "</color>] " + newText + "\n"; + TMP_ChatInput.ActivateInputField(); + ChatScrollbar.value = 0f; + } +} diff --git a/CodeAnimation.cs b/CodeAnimation.cs new file mode 100644 index 0000000..a4d6244 --- /dev/null +++ b/CodeAnimation.cs @@ -0,0 +1,63 @@ +using System.Collections; +using UnityEngine; + +public class CodeAnimation : MonoBehaviour +{ + public bool x = true; + + public bool y = true; + + public bool z = true; + + public AnimationCurve curve; + + public bool loop; + + public bool playOnAwake; + + private void Start() + { + if (playOnAwake) + { + Play(); + } + } + + private void Update() + { + } + + public void Play() + { + StartCoroutine(PlayAnimation()); + } + + private IEnumerator PlayAnimation() + { + float t = 0f; + float lastFrameValue = curve.Evaluate(0f); + while (t < curve.keys[curve.length - 1].time) + { + t += Time.deltaTime; + float deltaValue = curve.Evaluate(t) - lastFrameValue; + lastFrameValue = curve.Evaluate(t); + if (x) + { + base.transform.localScale = new Vector3(base.transform.localScale.x + deltaValue, base.transform.localScale.y, base.transform.localScale.z); + } + if (y) + { + base.transform.localScale = new Vector3(base.transform.localScale.x, base.transform.localScale.y + deltaValue, base.transform.localScale.z); + } + if (z) + { + base.transform.localScale = new Vector3(base.transform.localScale.x, base.transform.localScale.y, base.transform.localScale.z + deltaValue); + } + yield return null; + } + if (loop) + { + Play(); + } + } +} diff --git a/CollisionChecker.cs b/CollisionChecker.cs new file mode 100644 index 0000000..83c247a --- /dev/null +++ b/CollisionChecker.cs @@ -0,0 +1,85 @@ +using UnityEngine; + +public class CollisionChecker : MonoBehaviour +{ + private Transform head; + + private Transform hip; + + private StandingDataHandler data; + + public bool active = true; + + public float sinceGrounded; + + private PickupHandler pickupHandler; + + private HasControl hasControl; + + public float allowedSteepnesAngle = 60f; + + private void Start() + { + pickupHandler = base.transform.root.GetComponent<PickupHandler>(); + hasControl = base.transform.root.GetComponent<HasControl>(); + data = GetComponentInParent<StandingDataHandler>(); + Head componentInChildren = base.transform.root.GetComponentInChildren<Head>(); + if ((bool)componentInChildren) + { + head = componentInChildren.transform; + } + Hip componentInChildren2 = base.transform.root.GetComponentInChildren<Hip>(); + if ((bool)componentInChildren2) + { + hip = componentInChildren2.transform; + } + } + + private void Update() + { + sinceGrounded += Time.deltaTime; + } + + private void OnCollisionStay(Collision collision) + { + Collide(collision); + } + + private void OnCollisionEnter(Collision collision) + { + Collide(collision); + } + + private void Collide(Collision collision) + { + if (collision.transform.root == base.transform.root) + { + return; + } + if ((bool)collision.rigidbody) + { + Pickup component = collision.gameObject.GetComponent<Pickup>(); + if ((bool)component && !component.GetComponent<HoldableObject>().isHeld && hasControl.hasControl) + { + pickupHandler.PickUp(component); + } + if (collision.rigidbody.mass < 100f || collision.rigidbody.velocity.magnitude > 1f) + { + return; + } + } + if (active && Vector3.Angle(Vector3.up, collision.contacts[0].normal) < allowedSteepnesAngle) + { + if ((bool)data) + { + data.TouchGround(Mathf.Abs(hip.position.y - collision.contacts[0].point.y), collision.contacts[0].normal); + } + sinceGrounded = 0f; + } + } + + public void SwitchActive(bool setActive) + { + active = setActive; + } +} diff --git a/ConfigurableJointExtensions.cs b/ConfigurableJointExtensions.cs new file mode 100644 index 0000000..1fcbf91 --- /dev/null +++ b/ConfigurableJointExtensions.cs @@ -0,0 +1,41 @@ +using UnityEngine; + +public static class ConfigurableJointExtensions +{ + public static void SetTargetRotationLocal(this ConfigurableJoint joint, Quaternion targetLocalRotation, Quaternion startLocalRotation) + { + if (joint.configuredInWorldSpace) + { + Debug.LogError("SetTargetRotationLocal should not be used with joints that are configured in world space. For world space joints, use SetTargetRotation.", joint); + } + joint.SetTargetRotationInternal(targetLocalRotation, startLocalRotation, Space.Self); + } + + public static void SetTargetRotation(this ConfigurableJoint joint, Quaternion targetWorldRotation, Quaternion startWorldRotation) + { + if (!joint.configuredInWorldSpace) + { + Debug.LogError("SetTargetRotation must be used with joints that are configured in world space. For local space joints, use SetTargetRotationLocal.", joint); + } + joint.SetTargetRotationInternal(targetWorldRotation, startWorldRotation, Space.World); + } + + private static void SetTargetRotationInternal(this ConfigurableJoint joint, Quaternion targetRotation, Quaternion startRotation, Space space) + { + Vector3 axis = joint.axis; + Vector3 normalized = Vector3.Cross(joint.axis, joint.secondaryAxis).normalized; + Vector3 normalized2 = Vector3.Cross(normalized, axis).normalized; + Quaternion quaternion = Quaternion.LookRotation(normalized, normalized2); + Quaternion targetRotation2 = Quaternion.Inverse(quaternion); + if (space == Space.World) + { + targetRotation2 *= startRotation * Quaternion.Inverse(targetRotation); + } + else + { + targetRotation2 *= Quaternion.Inverse(targetRotation) * startRotation; + } + targetRotation2 *= quaternion; + joint.targetRotation = targetRotation2; + } +} diff --git a/ContextSwitcher.cs b/ContextSwitcher.cs new file mode 100644 index 0000000..592c809 --- /dev/null +++ b/ContextSwitcher.cs @@ -0,0 +1,31 @@ +using System.Collections.Generic; +using DeepSky.Haze; +using UnityEngine; + +public class ContextSwitcher : MonoBehaviour +{ + public List<DS_HazeContextAsset> contexts = new List<DS_HazeContextAsset>(); + + private DS_HazeView _view; + + private int _contextIndex; + + private void Start() + { + _view = GetComponent<DS_HazeView>(); + } + + private void Update() + { + if (contexts.Count > 0 && _view != null && Input.GetKeyUp(KeyCode.C)) + { + _contextIndex++; + if (_contextIndex == contexts.Count) + { + _contextIndex = 0; + } + _view.ContextAsset = contexts[_contextIndex]; + _view.OverrideContextAsset = true; + } + } +} diff --git a/Controls.cs b/Controls.cs new file mode 100644 index 0000000..bce2325 --- /dev/null +++ b/Controls.cs @@ -0,0 +1,85 @@ +using UnityEngine; + +[ExecuteInEditMode] +public class Controls : MonoBehaviour +{ + public AmplifyOcclusionEffect occlusion; + + private const AmplifyOcclusionBase.ApplicationMethod POST = AmplifyOcclusionBase.ApplicationMethod.PostEffect; + + private const AmplifyOcclusionBase.ApplicationMethod DEFERRED = AmplifyOcclusionBase.ApplicationMethod.Deferred; + + private const AmplifyOcclusionBase.ApplicationMethod DEBUG = AmplifyOcclusionBase.ApplicationMethod.Debug; + + private void OnGUI() + { + GUILayout.BeginArea(new Rect(0f, 0f, Screen.width, Screen.height)); + GUILayout.BeginHorizontal(); + GUILayout.Space(5f); + GUILayout.BeginVertical(); + occlusion.enabled = GUILayout.Toggle(occlusion.enabled, " Amplify Occlusion Enabled"); + GUILayout.Space(5f); + occlusion.ApplyMethod = ((!GUILayout.Toggle(occlusion.ApplyMethod == AmplifyOcclusionBase.ApplicationMethod.PostEffect, " Standard Post-effect")) ? occlusion.ApplyMethod : AmplifyOcclusionBase.ApplicationMethod.PostEffect); + occlusion.ApplyMethod = (GUILayout.Toggle(occlusion.ApplyMethod == AmplifyOcclusionBase.ApplicationMethod.Deferred, " Deferred Injection") ? AmplifyOcclusionBase.ApplicationMethod.Deferred : occlusion.ApplyMethod); + occlusion.ApplyMethod = ((!GUILayout.Toggle(occlusion.ApplyMethod == AmplifyOcclusionBase.ApplicationMethod.Debug, " Debug Mode")) ? occlusion.ApplyMethod : AmplifyOcclusionBase.ApplicationMethod.Debug); + GUILayout.EndVertical(); + GUILayout.FlexibleSpace(); + GUILayout.BeginVertical(); + GUILayout.Space(5f); + GUILayout.BeginHorizontal(); + GUILayout.BeginVertical(); + GUILayout.Space(-3f); + GUILayout.Label("Intensity "); + GUILayout.EndVertical(); + occlusion.Intensity = GUILayout.HorizontalSlider(occlusion.Intensity, 0f, 1f, GUILayout.Width(100f)); + GUILayout.Space(5f); + GUILayout.BeginVertical(); + GUILayout.Space(-3f); + GUILayout.Label(" " + occlusion.Intensity.ToString("0.00")); + GUILayout.EndVertical(); + GUILayout.Space(5f); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(); + GUILayout.BeginVertical(); + GUILayout.Space(-3f); + GUILayout.Label("Power Exp. "); + GUILayout.EndVertical(); + occlusion.PowerExponent = GUILayout.HorizontalSlider(occlusion.PowerExponent, 0.0001f, 6f, GUILayout.Width(100f)); + GUILayout.Space(5f); + GUILayout.BeginVertical(); + GUILayout.Space(-3f); + GUILayout.Label(" " + occlusion.PowerExponent.ToString("0.00")); + GUILayout.EndVertical(); + GUILayout.Space(5f); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(); + GUILayout.BeginVertical(); + GUILayout.Space(-3f); + GUILayout.Label("Radius "); + GUILayout.EndVertical(); + occlusion.Radius = GUILayout.HorizontalSlider(occlusion.Radius, 0.1f, 10f, GUILayout.Width(100f)); + GUILayout.Space(5f); + GUILayout.BeginVertical(); + GUILayout.Space(-3f); + GUILayout.Label(" " + occlusion.Radius.ToString("0.00")); + GUILayout.EndVertical(); + GUILayout.Space(5f); + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(); + GUILayout.BeginVertical(); + GUILayout.Space(-3f); + GUILayout.Label("Quality "); + GUILayout.EndVertical(); + occlusion.SampleCount = (AmplifyOcclusionBase.SampleCountLevel)GUILayout.HorizontalSlider((float)occlusion.SampleCount, 0f, 3f, GUILayout.Width(100f)); + GUILayout.Space(5f); + GUILayout.BeginVertical(); + GUILayout.Space(-3f); + GUILayout.Label(" "); + GUILayout.EndVertical(); + GUILayout.Space(5f); + GUILayout.EndHorizontal(); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + GUILayout.EndArea(); + } +} diff --git a/CreepyRobots.csproj b/CreepyRobots.csproj new file mode 100644 index 0000000..9d5de2a --- /dev/null +++ b/CreepyRobots.csproj @@ -0,0 +1,183 @@ +<Project Sdk="Microsoft.NET.Sdk"> + <PropertyGroup> + <AssemblyName>Assembly-CSharp</AssemblyName> + <GenerateAssemblyInfo>False</GenerateAssemblyInfo> + <TargetFramework>net35</TargetFramework> + </PropertyGroup> + <PropertyGroup> + <LangVersion>11.0</LangVersion> + <AllowUnsafeBlocks>True</AllowUnsafeBlocks> + </PropertyGroup> + <PropertyGroup /> + <ItemGroup> + <Reference Include="UnityEngine"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.AccessibilityModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.AccessibilityModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.Analytics"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.Analytics.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.AnimationModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.AnimationModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.ARModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.ARModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.AssetBundleModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.AssetBundleModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.ClothModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.ClothModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.ClusterInputModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.ClusterInputModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.ClusterRendererModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.ClusterRendererModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.CrashReportingModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.CrashReportingModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.DirectorModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.DirectorModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.GameCenterModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.GameCenterModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.GridModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.GridModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.ImageConversionModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.ImageConversionModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.InputModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.InputModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.JSONSerializeModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.JSONSerializeModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.Networking"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.Networking.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.ParticlesLegacyModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.ParticlesLegacyModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.PerformanceReportingModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.PerformanceReportingModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.Physics2DModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.Physics2DModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.ScreenCaptureModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.ScreenCaptureModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.SharedInternalsModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.SharedInternalsModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.SpatialTracking"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.SpatialTracking.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.SpriteMaskModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.SpriteMaskModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.SpriteShapeModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.SpriteShapeModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.StandardEvents"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.StandardEvents.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.StyleSheetsModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.StyleSheetsModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.TilemapModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.TilemapModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.Timeline"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.Timeline.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.UI"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.UI.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.UIElementsModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.UIElementsModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.UIModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.UIModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.PhysicsModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.PhysicsModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.CoreModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.CoreModule.dll</HintPath> + </Reference> + <Reference Include="System.Core" /> + <Reference Include="UnityEngine.ParticleSystemModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.ParticleSystemModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.AudioModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.AudioModule.dll</HintPath> + </Reference> + <Reference Include="ch.sycoforge.Decal"> + <HintPath>..\CreepyRobots_Data\Managed\ch.sycoforge.Decal.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.AIModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.AIModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.TerrainPhysicsModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.TerrainPhysicsModule.dll</HintPath> + </Reference> + <Reference Include="Lidgren.Network"> + <HintPath>..\CreepyRobots_Data\Managed\Lidgren.Network.dll</HintPath> + </Reference> + <Reference Include="TextMeshPro-1.0.55.2017.2.0b12"> + <HintPath>..\CreepyRobots_Data\Managed\TextMeshPro-1.0.55.2017.2.0b12.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.TextRenderingModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.TextRenderingModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.IMGUIModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.IMGUIModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.TerrainModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.TerrainModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.UNETModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.UNETModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.UnityAnalyticsModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.UnityAnalyticsModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.UnityConnectModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.UnityConnectModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.UnityWebRequestAudioModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.UnityWebRequestAudioModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.UnityWebRequestModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.UnityWebRequestModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.UnityWebRequestTextureModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.UnityWebRequestTextureModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.UnityWebRequestWWWModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.UnityWebRequestWWWModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.VehiclesModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.VehiclesModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.VideoModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.VideoModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.VRModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.VRModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.WebModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.WebModule.dll</HintPath> + </Reference> + <Reference Include="UnityEngine.WindModule"> + <HintPath>..\CreepyRobots_Data\Managed\UnityEngine.WindModule.dll</HintPath> + </Reference> + </ItemGroup> +</Project>
\ No newline at end of file diff --git a/Damagable.cs b/Damagable.cs new file mode 100644 index 0000000..667cd5e --- /dev/null +++ b/Damagable.cs @@ -0,0 +1,54 @@ +using UnityEngine; +using UnityEngine.Events; + +public class Damagable : MonoBehaviour +{ + public float multiplier = 1f; + + private PlayerDeath playerDeath; + + public UnityEvent outOfLiveEvent; + + public UnityEvent damageEvent; + + public float health = 100f; + + private float currentHealth; + + private bool dead; + + private Rigidbody rig; + + private void Start() + { + rig = GetComponent<Rigidbody>(); + currentHealth = health; + playerDeath = base.transform.root.GetComponent<PlayerDeath>(); + } + + private void Update() + { + } + + public void TakeDamage(Vector3 damage, Vector3 hitPoint) + { + damage *= multiplier; + if ((bool)playerDeath) + { + playerDeath.TakeDamage(damage, hitPoint, rig); + return; + } + damageEvent.Invoke(); + currentHealth -= damage.magnitude; + if (currentHealth < 0f && !dead) + { + dead = true; + outOfLiveEvent.Invoke(); + } + } + + public void RefillHP() + { + currentHealth = health; + } +} diff --git a/DamageEffects.cs b/DamageEffects.cs new file mode 100644 index 0000000..305c1d7 --- /dev/null +++ b/DamageEffects.cs @@ -0,0 +1,84 @@ +using UnityEngine; +using UnityEngine.PostProcessing; + +public class DamageEffects : MonoBehaviour +{ + private WobbleShake screenShake; + + private ParticleParent[] particleParents; + + private float counter; + + public AnimationCurve curve; + + public AnimationCurve curve2; + + public PostProcessingProfile post; + + private Camera mainCam; + + public float damageValue; + + private Transform hip; + + private void Start() + { + screenShake = base.transform.root.GetComponentInChildren<WobbleShake>(); + particleParents = GetComponentsInChildren<ParticleParent>(); + mainCam = base.transform.root.GetComponentInChildren<Camera>(); + hip = base.transform.root.GetComponentInChildren<Transform>().transform; + } + + private void Update() + { + VignetteModel.Settings settings = post.vignette.settings; + ChromaticAberrationModel.Settings settings2 = post.chromaticAberration.settings; + counter += Time.deltaTime; + if (damageValue > 0f) + { + damageValue -= Time.deltaTime * 0.3f; + } + if (counter < curve.keys[curve.length - 1].time) + { + float intensity = curve.Evaluate(counter); + settings.intensity = intensity; + } + settings.intensity = Mathf.Lerp(settings.intensity, 0f, Time.deltaTime * 0.5f); + settings.intensity = Mathf.Clamp(settings.intensity, 0f, 9f); + post.vignette.settings = settings; + if (counter < curve2.keys[curve2.length - 1].time) + { + float intensity2 = curve2.Evaluate(counter); + settings2.intensity = intensity2; + } + settings2.intensity = Mathf.Lerp(settings2.intensity, 0f, Time.deltaTime * 0.5f); + settings2.intensity = Mathf.Clamp(settings2.intensity, 0f, 9f); + post.chromaticAberration.settings = settings2; + } + + public void TakeDamage(Vector3 damage, Vector3 hitPoint) + { + counter = 0f; + damageValue += damage.magnitude * 0.02f; + damageValue = Mathf.Clamp(damageValue, 0f, 0.5f); + GetComponentInChildren<Torso>().GetComponent<Rigidbody>().AddForce(damage.normalized * (damage.magnitude * 0.3f + 3f), ForceMode.VelocityChange); + screenShake.AddShakeWorld(damage * 0.4f, 0.8f); + DirectionalParticles(mainCam.transform.InverseTransformDirection(-damage)); + } + + private void DirectionalParticles(Vector3 damage) + { + for (int i = 0; i < particleParents.Length; i++) + { + Vector3 from = particleParents[i].transform.position - particleParents[i].transform.parent.position; + Vector3 to = damage; + from.y = 0f; + to.y = 0f; + if (Vector3.Angle(from, to) < 15f + damage.magnitude * 0.5f) + { + float multi = 1f - Vector3.Angle(from, to) / damage.magnitude * 0.5f; + particleParents[i].Play(damage.magnitude, multi); + } + } + } +} diff --git a/DebugPosition.cs b/DebugPosition.cs new file mode 100644 index 0000000..32cd942 --- /dev/null +++ b/DebugPosition.cs @@ -0,0 +1,13 @@ +using UnityEngine; + +public class DebugPosition : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + Debug.DrawLine(base.transform.position, base.transform.position + Vector3.up, Color.red, 5f); + } +} diff --git a/DeepSky.Haze.Demo/BasicMouseLookControl.cs b/DeepSky.Haze.Demo/BasicMouseLookControl.cs new file mode 100644 index 0000000..8ce6d68 --- /dev/null +++ b/DeepSky.Haze.Demo/BasicMouseLookControl.cs @@ -0,0 +1,52 @@ +using UnityEngine; + +namespace DeepSky.Haze.Demo; + +public class BasicMouseLookControl : MonoBehaviour +{ + [SerializeField] + private float m_XSensitivity = 2.5f; + + [SerializeField] + private float m_YSensitivity = 2.5f; + + private Quaternion m_StartRotation; + + private float m_X; + + private float m_Y; + + private void Start() + { + m_StartRotation = base.transform.localRotation; + } + + private void Update() + { + m_X += Input.GetAxis("Mouse X") * m_XSensitivity; + m_Y += Input.GetAxis("Mouse Y") * m_YSensitivity; + if (m_X > 360f) + { + m_X = 0f; + } + else if (m_X < 0f) + { + m_X = 360f; + } + if (m_Y > 60f) + { + m_Y = 60f; + } + else if (m_Y < -60f) + { + m_Y = -60f; + } + Quaternion quaternion = Quaternion.AngleAxis(m_X, Vector3.up); + Quaternion quaternion2 = Quaternion.AngleAxis(m_Y, Vector3.left); + base.transform.localRotation = m_StartRotation * quaternion * quaternion2; + if (Input.GetKeyUp(KeyCode.Escape)) + { + Application.Quit(); + } + } +} diff --git a/DeepSky.Haze/DS_HazeContext.cs b/DeepSky.Haze/DS_HazeContext.cs new file mode 100644 index 0000000..2294526 --- /dev/null +++ b/DeepSky.Haze/DS_HazeContext.cs @@ -0,0 +1,154 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace DeepSky.Haze; + +[Serializable] +[AddComponentMenu("")] +public class DS_HazeContext +{ + [SerializeField] + public List<DS_HazeContextItem> m_ContextItems; + + [SerializeField] + private int m_SoloItem = -1; + + public int Solo => m_SoloItem; + + public DS_HazeContext() + { + m_ContextItems = new List<DS_HazeContextItem>(); + DS_HazeContextItem item = new DS_HazeContextItem + { + m_Name = "Default" + }; + m_ContextItems.Add(item); + } + + public void DuplicateContextItem(int index) + { + if (index >= 0 && index < m_ContextItems.Count) + { + DS_HazeContextItem dS_HazeContextItem = new DS_HazeContextItem(); + dS_HazeContextItem.CopyFrom(m_ContextItems[index]); + dS_HazeContextItem.m_Name += "_Copy"; + m_ContextItems.Add(dS_HazeContextItem); + } + } + + public void RemoveContextItem(int index) + { + if (index >= 0 && index < m_ContextItems.Count && m_ContextItems.Count != 1) + { + m_ContextItems.RemoveAt(index); + if (m_SoloItem != -1 && m_SoloItem == index) + { + m_SoloItem = -1; + } + } + } + + public void MoveContextItemUp(int index) + { + if (index < 1 || index >= m_ContextItems.Count) + { + return; + } + DS_HazeContextItem item = m_ContextItems[index]; + m_ContextItems.RemoveAt(index); + m_ContextItems.Insert(index - 1, item); + if (m_SoloItem != -1) + { + if (m_SoloItem == index) + { + m_SoloItem--; + } + else if (m_SoloItem == index - 1) + { + m_SoloItem++; + } + } + } + + public void MoveContextItemDown(int index) + { + if (index < 0 || index >= m_ContextItems.Count - 1) + { + return; + } + DS_HazeContextItem item = m_ContextItems[index]; + m_ContextItems.RemoveAt(index); + m_ContextItems.Insert(index + 1, item); + if (m_SoloItem != -1) + { + if (m_SoloItem == index) + { + m_SoloItem++; + } + else if (m_SoloItem == index + 1) + { + m_SoloItem--; + } + } + } + + public DS_HazeContextItem GetContextItemBlended(float time = -1f) + { + DS_HazeContextItem dS_HazeContextItem = new DS_HazeContextItem(); + dS_HazeContextItem.CopyFrom(m_ContextItems[0]); + if (m_ContextItems.Count == 1) + { + return dS_HazeContextItem; + } + time = Mathf.Clamp01(time); + float num = 0f; + for (int i = 1; i < m_ContextItems.Count; i++) + { + num = m_ContextItems[i].m_Weight.Evaluate(time); + dS_HazeContextItem.Lerp(m_ContextItems[i], num); + } + return dS_HazeContextItem; + } + + public DS_HazeContextItem GetItemAtIndex(int index) + { + if (index < 0 || index >= m_ContextItems.Count) + { + return null; + } + return m_ContextItems[index]; + } + + public void CopyFrom(DS_HazeContext other) + { + if (m_ContextItems.Count > 0) + { + m_ContextItems.Clear(); + } + for (int i = 0; i < other.m_ContextItems.Count; i++) + { + DS_HazeContextItem dS_HazeContextItem = new DS_HazeContextItem(); + dS_HazeContextItem.CopyFrom(other.m_ContextItems[i]); + m_ContextItems.Add(dS_HazeContextItem); + } + } + + public DS_HazeContextAsset GetContextAsset() + { + DS_HazeContextAsset dS_HazeContextAsset = ScriptableObject.CreateInstance<DS_HazeContextAsset>(); + dS_HazeContextAsset.Context.CopyFrom(this); + dS_HazeContextAsset.Context.m_SoloItem = -1; + return dS_HazeContextAsset; + } + + public string[] GetItemNames() + { + string[] array = new string[m_ContextItems.Count]; + for (int i = 0; i < m_ContextItems.Count; i++) + { + array[i] = m_ContextItems[i].m_Name; + } + return array; + } +} diff --git a/DeepSky.Haze/DS_HazeContextAsset.cs b/DeepSky.Haze/DS_HazeContextAsset.cs new file mode 100644 index 0000000..5e4e9da --- /dev/null +++ b/DeepSky.Haze/DS_HazeContextAsset.cs @@ -0,0 +1,14 @@ +using System; +using UnityEngine; + +namespace DeepSky.Haze; + +[Serializable] +[AddComponentMenu("")] +public class DS_HazeContextAsset : ScriptableObject +{ + [SerializeField] + private DS_HazeContext m_Context = new DS_HazeContext(); + + public DS_HazeContext Context => m_Context; +} diff --git a/DeepSky.Haze/DS_HazeContextItem.cs b/DeepSky.Haze/DS_HazeContextItem.cs new file mode 100644 index 0000000..d9208c9 --- /dev/null +++ b/DeepSky.Haze/DS_HazeContextItem.cs @@ -0,0 +1,173 @@ +using System; +using System.Reflection; +using UnityEngine; + +namespace DeepSky.Haze; + +[Serializable] +[AddComponentMenu("")] +public class DS_HazeContextItem +{ + public enum Multiplier + { + OneTenth, + OneFifth, + OneHalf, + One, + Two, + Five, + Ten, + OneHundredth + } + + [SerializeField] + public string m_Name; + + [SerializeField] + public AnimationCurve m_Weight; + + [SerializeField] + [Range(0f, 8f)] + public float m_AirScatteringScale = 1f; + + [SerializeField] + public Multiplier m_AirScatteringMultiplier = Multiplier.One; + + [SerializeField] + [Range(0.0001f, 0.1f)] + public float m_AirDensityHeightFalloff = 0.001f; + + [SerializeField] + [Range(0f, 8f)] + public float m_HazeScatteringScale = 1f; + + [SerializeField] + public Multiplier m_HazeScatteringMultiplier = Multiplier.One; + + [SerializeField] + [Range(0.0001f, 0.1f)] + public float m_HazeDensityHeightFalloff = 0.003f; + + [SerializeField] + [Range(-0.99f, 0.99f)] + public float m_HazeScatteringDirection = 0.8f; + + [SerializeField] + [Range(0f, 1f)] + public float m_HazeSecondaryScatteringRatio = 0.8f; + + [SerializeField] + [Range(0f, 1f)] + public float m_FogOpacity = 1f; + + [SerializeField] + [Range(0f, 8f)] + public float m_FogScatteringScale = 1f; + + [SerializeField] + [Range(0f, 8f)] + public float m_FogExtinctionScale = 1f; + + [SerializeField] + public Multiplier m_FogExtinctionMultiplier = Multiplier.One; + + [SerializeField] + [Range(0.0001f, 1f)] + public float m_FogDensityHeightFalloff = 0.01f; + + [SerializeField] + [Range(0f, 1f)] + public float m_FogStartDistance; + + [SerializeField] + [Range(-0.99f, 0.99f)] + public float m_FogScatteringDirection = 0.7f; + + [SerializeField] + [Range(-10000f, 10000f)] + public float m_FogStartHeight; + + [SerializeField] + public Color m_FogAmbientColour = Color.white; + + [SerializeField] + public Color m_FogLightColour = Color.white; + + public DS_HazeContextItem() + { + m_Name = "New"; + m_Weight = new AnimationCurve(new Keyframe(0.25f, 0f), new Keyframe(0.5f, 1f), new Keyframe(0.75f, 0f)); + } + + public static float MultiplierAsFloat(Multiplier mult) + { + return mult switch + { + Multiplier.OneTenth => 0.1f, + Multiplier.OneFifth => 0.2f, + Multiplier.OneHalf => 0.5f, + Multiplier.One => 1f, + Multiplier.Two => 2f, + Multiplier.Five => 5f, + Multiplier.Ten => 10f, + Multiplier.OneHundredth => 0.01f, + _ => 1f, + }; + } + + public static float ParamWithMultiplier(float param, Multiplier mult) + { + return mult switch + { + Multiplier.OneTenth => param * 0.1f, + Multiplier.OneFifth => param * 0.2f, + Multiplier.OneHalf => param * 0.5f, + Multiplier.One => param * 1f, + Multiplier.Two => param * 2f, + Multiplier.Five => param * 5f, + Multiplier.Ten => param * 10f, + Multiplier.OneHundredth => param * 0.01f, + _ => param * 1f, + }; + } + + public void Lerp(DS_HazeContextItem other, float dt) + { + if (other != null) + { + dt = Mathf.Clamp01(dt); + float num = 1f - dt; + m_AirScatteringScale = m_AirScatteringScale * num + other.m_AirScatteringScale * dt; + m_AirDensityHeightFalloff = m_AirDensityHeightFalloff * num + other.m_AirDensityHeightFalloff * dt; + m_HazeScatteringScale = m_HazeScatteringScale * num + other.m_HazeScatteringScale * dt; + m_HazeDensityHeightFalloff = m_HazeDensityHeightFalloff * num + other.m_HazeDensityHeightFalloff * dt; + m_HazeScatteringDirection = m_HazeScatteringDirection * num + other.m_HazeScatteringDirection * dt; + m_HazeSecondaryScatteringRatio = m_HazeSecondaryScatteringRatio * num + other.m_HazeSecondaryScatteringRatio * dt; + m_FogOpacity = m_FogOpacity * num + other.m_FogOpacity * dt; + m_FogScatteringScale = m_FogScatteringScale * num + other.m_FogScatteringScale * dt; + m_FogExtinctionScale = m_FogExtinctionScale * num + other.m_FogExtinctionScale * dt; + m_FogDensityHeightFalloff = m_FogDensityHeightFalloff * num + other.m_FogDensityHeightFalloff * dt; + m_FogStartDistance = m_FogStartDistance * num + other.m_FogStartDistance * dt; + m_FogScatteringDirection = m_FogScatteringDirection * num + other.m_FogScatteringDirection * dt; + m_FogStartHeight = m_FogStartHeight * num + other.m_FogStartHeight * dt; + m_FogAmbientColour = m_FogAmbientColour * num + other.m_FogAmbientColour * dt; + m_FogLightColour = m_FogLightColour * num + other.m_FogLightColour * dt; + } + } + + public void CopyFrom(DS_HazeContextItem other) + { + if (other != null) + { + Type type = GetType(); + Type type2 = other.GetType(); + FieldInfo[] fields = type.GetFields(); + foreach (FieldInfo fieldInfo in fields) + { + FieldInfo field = type2.GetField(fieldInfo.Name); + fieldInfo.SetValue(this, field.GetValue(other)); + } + m_Weight = new AnimationCurve(m_Weight.keys); + } + } +} diff --git a/DeepSky.Haze/DS_HazeCore.cs b/DeepSky.Haze/DS_HazeCore.cs new file mode 100644 index 0000000..30b3486 --- /dev/null +++ b/DeepSky.Haze/DS_HazeCore.cs @@ -0,0 +1,218 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace DeepSky.Haze; + +[ExecuteInEditMode] +[AddComponentMenu("DeepSky Haze/Controller", 51)] +public class DS_HazeCore : MonoBehaviour +{ + public enum HeightFalloffType + { + Exponential, + None + } + + public enum NoiseTextureSize + { + x8 = 8, + x16 = 0x10, + x32 = 0x20 + } + + public enum DebugGUIPosition + { + TopLeft, + TopCenter, + TopRight, + CenterLeft, + Center, + CenterRight, + BottomLeft, + BottomCenter, + BottomRight + } + + public static string kVersionStr = "DeepSky Haze v1.4.0"; + + private static int kGUIHeight = 180; + + private static DS_HazeCore instance; + + [SerializeField] + [Range(0f, 1f)] + [Tooltip("The time at which Zones will evaluate their settings. Animate this or set in code to create time-of-day transitions.")] + private float m_Time; + + [SerializeField] + [Tooltip("The height falloff method to use globally (default Exponential).")] + private HeightFalloffType m_HeightFalloff; + + [SerializeField] + private List<DS_HazeZone> m_Zones = new List<DS_HazeZone>(); + + [SerializeField] + private DebugGUIPosition m_DebugGUIPosition; + + private HashSet<DS_HazeLightVolume> m_LightVolumes = new HashSet<DS_HazeLightVolume>(); + + [SerializeField] + private Texture3D m_NoiseLUT; + + [SerializeField] + private bool m_ShowDebugGUI; + + private Vector2 m_GUIScrollPosition; + + private int m_GUISelectedView = -1; + + private bool m_GUISelectionPopup; + + private DS_HazeView m_GUIDisplayedView; + + public static DS_HazeCore Instance + { + get + { + if (instance == null) + { + instance = Object.FindObjectOfType<DS_HazeCore>(); + } + return instance; + } + } + + public float Time + { + get + { + return m_Time; + } + set + { + m_Time = Mathf.Clamp01(value); + } + } + + public Texture3D NoiseLUT => m_NoiseLUT; + + public HeightFalloffType HeightFalloff + { + get + { + return m_HeightFalloff; + } + set + { + m_HeightFalloff = value; + SetGlobalHeightFalloff(); + } + } + + private void SetGlobalHeightFalloff() + { + switch (m_HeightFalloff) + { + case HeightFalloffType.Exponential: + Shader.DisableKeyword("DS_HAZE_HEIGHT_FALLOFF_NONE"); + break; + case HeightFalloffType.None: + Shader.EnableKeyword("DS_HAZE_HEIGHT_FALLOFF_NONE"); + break; + } + } + + private void OnTransformChildrenChanged() + { + m_Zones.Clear(); + DS_HazeZone[] componentsInChildren = GetComponentsInChildren<DS_HazeZone>(includeInactive: true); + m_Zones.AddRange(componentsInChildren); + } + + private void Awake() + { + if (instance == null) + { + instance = this; + } + else if (instance != this) + { + Debug.LogError("DeepSky::DS_HazeCore:Awake - There is more than one Haze Controller in this scene! Disabling " + base.name); + base.enabled = false; + } + } + + private void OnEnable() + { + SetGlobalHeightFalloff(); + Shader.SetGlobalTexture("_SamplingOffsets", m_NoiseLUT); + } + + private void Reset() + { + OnTransformChildrenChanged(); + } + + public void SetGlobalNoiseLUT() + { + Shader.SetGlobalTexture("_SamplingOffsets", m_NoiseLUT); + } + + public void AddLightVolume(DS_HazeLightVolume lightVolume) + { + RemoveLightVolume(lightVolume); + m_LightVolumes.Add(lightVolume); + } + + public void RemoveLightVolume(DS_HazeLightVolume lightVolume) + { + m_LightVolumes.Remove(lightVolume); + } + + public void GetRenderLightVolumes(Vector3 cameraPosition, List<DS_HazeLightVolume> lightVolumes, List<DS_HazeLightVolume> shadowVolumes) + { + foreach (DS_HazeLightVolume lightVolume in m_LightVolumes) + { + if (lightVolume.WillRender(cameraPosition)) + { + if (lightVolume.CastShadows) + { + shadowVolumes.Add(lightVolume); + } + else + { + lightVolumes.Add(lightVolume); + } + } + } + } + + public DS_HazeContextItem GetRenderContextAtPosition(Vector3 position) + { + List<DS_HazeZone> list = new List<DS_HazeZone>(); + for (int i = 0; i < m_Zones.Count; i++) + { + if (m_Zones[i].Contains(position) && m_Zones[i].enabled) + { + list.Add(m_Zones[i]); + } + } + if (list.Count == 0) + { + return null; + } + if (list.Count == 1) + { + return list[0].Context.GetContextItemBlended(m_Time); + } + list.Sort((DS_HazeZone z1, DS_HazeZone z2) => (!(z1 < z2)) ? 1 : (-1)); + DS_HazeContextItem contextItemBlended = list[0].Context.GetContextItemBlended(m_Time); + float num = 0f; + for (int j = 1; j < list.Count; j++) + { + num = list[j].GetBlendWeight(position); + contextItemBlended.Lerp(list[j].Context.GetContextItemBlended(m_Time), num); + } + return contextItemBlended; + } +} diff --git a/DeepSky.Haze/DS_HazeLightVolume.cs b/DeepSky.Haze/DS_HazeLightVolume.cs new file mode 100644 index 0000000..1a9928e --- /dev/null +++ b/DeepSky.Haze/DS_HazeLightVolume.cs @@ -0,0 +1,604 @@ +using System; +using UnityEngine; +using UnityEngine.Rendering; + +namespace DeepSky.Haze; + +[ExecuteInEditMode] +[RequireComponent(typeof(Light))] +[AddComponentMenu("DeepSky Haze/Light Volume", 2)] +public class DS_HazeLightVolume : MonoBehaviour +{ + private static int kConeSubdivisions = 16; + + private static Shader kLightVolumeShader; + + private Light m_Light; + + private Mesh m_ProxyMesh; + + private Matrix4x4 m_LightVolumeTransform; + + private CommandBuffer m_RenderCmd; + + private Material m_VolumeMaterial; + + private Vector3 m_DensityOffset = Vector3.zero; + + [SerializeField] + private DS_SamplingQuality m_Samples = DS_SamplingQuality.x16; + + [SerializeField] + private DS_LightFalloff m_Falloff; + + [SerializeField] + private bool m_UseFog; + + [SerializeField] + [Range(0f, 100f)] + private float m_Scattering = 1f; + + [SerializeField] + [Range(0f, 1f)] + private float m_SecondaryScattering = 0.1f; + + [SerializeField] + [Range(-1f, 1f)] + private float m_ScatteringDirection = 0.75f; + + [SerializeField] + private Texture3D m_DensityTexture; + + [SerializeField] + [Range(0.1f, 10f)] + private float m_DensityTextureScale = 1f; + + [SerializeField] + [Range(0.1f, 3f)] + private float m_DensityTextureContrast = 1f; + + [SerializeField] + private Vector3 m_AnimateDirection = Vector3.zero; + + [SerializeField] + [Range(0f, 10f)] + private float m_AnimateSpeed = 1f; + + [SerializeField] + private float m_StartFade = 25f; + + [SerializeField] + private float m_EndFade = 30f; + + [SerializeField] + [Range(0.01f, 1f)] + private float m_FarClip = 1f; + + private LightType m_PreviousLightType = LightType.Point; + + private float m_PreviousAngle = 45f; + + private LightShadows m_PreviousShadowMode; + + public Light LightSource => m_Light; + + public LightType Type => (!(m_Light != null)) ? LightType.Point : m_Light.type; + + public bool CastShadows => (m_Light.shadows != 0) ? true : false; + + public CommandBuffer RenderCommandBuffer => m_RenderCmd; + + public DS_SamplingQuality Samples + { + get + { + return m_Samples; + } + set + { + m_Samples = value; + } + } + + public DS_LightFalloff Falloff + { + get + { + return m_Falloff; + } + set + { + m_Falloff = value; + } + } + + public bool UseFog + { + get + { + return m_UseFog; + } + set + { + m_UseFog = value; + } + } + + public float Scattering + { + get + { + return m_Scattering; + } + set + { + m_Scattering = Mathf.Clamp01(value); + } + } + + public float ScatteringDirection + { + get + { + return m_ScatteringDirection; + } + set + { + m_ScatteringDirection = Mathf.Clamp(value, -1f, 1f); + } + } + + public Texture3D DensityTexture + { + get + { + return m_DensityTexture; + } + set + { + m_DensityTexture = value; + } + } + + public float DensityTextureScale + { + get + { + return m_DensityTextureScale; + } + set + { + m_DensityTextureScale = Mathf.Clamp01(m_DensityTextureScale); + } + } + + public Vector3 AnimateDirection + { + get + { + return m_AnimateDirection; + } + set + { + m_AnimateDirection = value.normalized; + } + } + + public float AnimateSpeed + { + get + { + return m_AnimateSpeed; + } + set + { + m_AnimateSpeed = Mathf.Clamp01(value); + } + } + + public float StartFade + { + get + { + return m_StartFade; + } + set + { + m_StartFade = ((!(value > 0f)) ? 1f : value); + } + } + + public float EndFade + { + get + { + return m_EndFade; + } + set + { + m_EndFade = ((!(value > m_StartFade)) ? (m_StartFade + 1f) : value); + } + } + + private void CreateProxyMeshCone(Mesh proxyMesh) + { + Vector3[] array = null; + int[] array2 = null; + float num = Mathf.Tan(m_Light.spotAngle / 2f * ((float)Math.PI / 180f)) * m_FarClip; + array = new Vector3[kConeSubdivisions + 2]; + array2 = new int[kConeSubdivisions * 6]; + float num2 = (float)Math.PI * 2f / (float)kConeSubdivisions; + float num3 = 0f; + for (int i = 0; i < kConeSubdivisions; i++) + { + ref Vector3 reference = ref array[i]; + reference = new Vector3(Mathf.Sin(num3) * num, Mathf.Cos(num3) * num, m_FarClip); + num3 += num2; + } + ref Vector3 reference2 = ref array[kConeSubdivisions]; + reference2 = new Vector3(0f, 0f, m_FarClip); + ref Vector3 reference3 = ref array[kConeSubdivisions + 1]; + reference3 = new Vector3(0f, 0f, -0.1f); + for (int j = 0; j < kConeSubdivisions; j++) + { + array2[j * 3] = kConeSubdivisions; + array2[j * 3 + 1] = ((j != kConeSubdivisions - 1) ? (j + 1) : 0); + array2[j * 3 + 2] = j; + array2[kConeSubdivisions * 3 + j * 3] = j; + array2[kConeSubdivisions * 3 + j * 3 + 1] = ((j != kConeSubdivisions - 1) ? (j + 1) : 0); + array2[kConeSubdivisions * 3 + j * 3 + 2] = kConeSubdivisions + 1; + } + proxyMesh.vertices = array; + proxyMesh.triangles = array2; + proxyMesh.hideFlags = HideFlags.HideAndDontSave; + m_PreviousAngle = m_Light.spotAngle; + } + + public bool ProxyMeshRequiresRebuild() + { + if (m_Light == null) + { + return false; + } + if (m_ProxyMesh == null || (m_Light.type == LightType.Spot && m_Light.spotAngle != m_PreviousAngle)) + { + return true; + } + return false; + } + + public bool LightTypeChanged() + { + if (m_Light == null) + { + return false; + } + return m_Light.type != m_PreviousLightType; + } + + public void UpdateLightType() + { + m_VolumeMaterial.DisableKeyword("POINT_COOKIE"); + m_VolumeMaterial.DisableKeyword("SPOT_COOKIE"); + if (m_Light.type == LightType.Point) + { + m_VolumeMaterial.EnableKeyword("POINT"); + m_VolumeMaterial.DisableKeyword("SPOT"); + } + else + { + if (m_Light.type != 0) + { + Debug.LogError("DeepSky::DS_HazeLightVolume: Unsupported light type! " + base.gameObject.name + " will not render volumetrics."); + base.enabled = false; + return; + } + m_VolumeMaterial.EnableKeyword("SPOT"); + m_VolumeMaterial.DisableKeyword("POINT"); + } + RebuildProxyMesh(); + m_PreviousLightType = m_Light.type; + } + + public void RebuildProxyMesh() + { + switch (m_Light.type) + { + case LightType.Point: + if (m_PreviousLightType != LightType.Point) + { + UnityEngine.Object.DestroyImmediate(m_ProxyMesh); + } + m_ProxyMesh = Resources.Load<Mesh>("DS_HazeMeshProxySphere"); + break; + case LightType.Spot: + if (m_PreviousLightType == LightType.Point) + { + m_ProxyMesh = new Mesh(); + } + else if (m_ProxyMesh != null) + { + m_ProxyMesh.Clear(); + } + CreateProxyMeshCone(m_ProxyMesh); + break; + default: + Debug.LogError("DeepSky::DS_HazeLightVolume: Unsupported light type! " + base.gameObject.name + " will not render volumetrics."); + base.enabled = false; + break; + } + } + + public bool ShadowModeChanged() + { + if (m_Light == null) + { + return false; + } + return m_Light.shadows != m_PreviousShadowMode; + } + + public void UpdateShadowMode() + { + if (m_Light.shadows == LightShadows.None) + { + m_VolumeMaterial.DisableKeyword("SHADOWS_DEPTH"); + m_VolumeMaterial.DisableKeyword("SHADOWS_CUBE"); + } + else if (m_Light.type == LightType.Point) + { + m_VolumeMaterial.EnableKeyword("SHADOWS_CUBE"); + m_VolumeMaterial.DisableKeyword("SHADOWS_DEPTH"); + } + else if (m_Light.type == LightType.Spot) + { + m_VolumeMaterial.EnableKeyword("SHADOWS_DEPTH"); + m_VolumeMaterial.DisableKeyword("SHADOWS_CUBE"); + } + m_PreviousShadowMode = m_Light.shadows; + } + + public void Register() + { + DS_HazeCore instance = DS_HazeCore.Instance; + if (instance == null) + { + Debug.LogError("DeepSky::DS_HazeLightVolume: Attempting to add a light volume but no HS_HazeCore found in scene! Please make sure there is a DS_HazeCore object."); + } + else + { + instance.AddLightVolume(this); + } + } + + public void Deregister() + { + DS_HazeCore instance = DS_HazeCore.Instance; + if (instance != null) + { + instance.RemoveLightVolume(this); + } + } + + public bool WillRender(Vector3 cameraPos) + { + return base.isActiveAndEnabled & (Vector3.Distance(cameraPos, base.transform.position) < m_EndFade); + } + + private void Update() + { + m_DensityOffset -= m_AnimateDirection * m_AnimateSpeed * Time.deltaTime * 0.1f; + } + + private void OnEnable() + { + m_Light = GetComponent<Light>(); + if (m_Light == null) + { + Debug.LogError("DeepSky::DS_HazeLightVolume: No Light component found on " + base.gameObject.name); + base.enabled = false; + } + if (kLightVolumeShader == null) + { + kLightVolumeShader = Resources.Load<Shader>("DS_HazeLightVolume"); + } + if (m_VolumeMaterial == null) + { + m_VolumeMaterial = new Material(kLightVolumeShader); + m_VolumeMaterial.hideFlags = HideFlags.HideAndDontSave; + } + if (m_RenderCmd == null) + { + m_RenderCmd = new CommandBuffer(); + m_RenderCmd.name = base.gameObject.name + "_DS_Haze_RenderLightVolume"; + m_Light.AddCommandBuffer(LightEvent.AfterShadowMap, m_RenderCmd); + } + if (LightTypeChanged()) + { + UpdateLightType(); + } + else if (ProxyMeshRequiresRebuild()) + { + RebuildProxyMesh(); + } + if (ShadowModeChanged()) + { + UpdateShadowMode(); + } + Register(); + } + + private void OnDisable() + { + Deregister(); + } + + private void OnDestroy() + { + if (m_RenderCmd != null) + { + m_RenderCmd.Dispose(); + } + Deregister(); + if (m_ProxyMesh != null && m_Light.type != LightType.Point) + { + UnityEngine.Object.DestroyImmediate(m_ProxyMesh); + } + if (m_VolumeMaterial != null) + { + UnityEngine.Object.DestroyImmediate(m_VolumeMaterial); + } + } + + private int SetShaderPassAndMatrix(Transform cameraTransform, int downSampleFactor, out Matrix4x4 worldMtx) + { + worldMtx = Matrix4x4.TRS(base.transform.position, base.transform.rotation, new Vector3(m_Light.range, m_Light.range, m_Light.range)); + int num = 0; + if (m_Light.type == LightType.Spot) + { + float num2 = Mathf.Cos(m_Light.spotAngle / 2f * ((float)Math.PI / 180f)); + Vector3 normalized = (cameraTransform.position - base.transform.position).normalized; + float num3 = Vector3.Dot(normalized, base.transform.forward); + num = ((num3 > num2) ? 1 : 2); + } + if (downSampleFactor == 4) + { + num += 3; + } + if (m_Falloff == DS_LightFalloff.Quadratic) + { + num += 6; + } + if (m_UseFog) + { + num += 12; + } + return num; + } + + public void FillLightCommandBuffer(RenderTexture radianceTarget, Transform cameraTransform, int downSampleFactor) + { + m_RenderCmd.SetGlobalTexture("_ShadowMapTexture", BuiltinRenderTextureType.CurrentActive); + Matrix4x4 worldMtx; + int shaderPass = SetShaderPassAndMatrix(cameraTransform, downSampleFactor, out worldMtx); + m_RenderCmd.SetRenderTarget(radianceTarget); + m_RenderCmd.DrawMesh(m_ProxyMesh, worldMtx, m_VolumeMaterial, 0, shaderPass); + } + + public void AddLightRenderCommand(Transform cameraTransform, CommandBuffer cmd, int downSampleFactor) + { + Matrix4x4 worldMtx; + int shaderPass = SetShaderPassAndMatrix(cameraTransform, downSampleFactor, out worldMtx); + cmd.DrawMesh(m_ProxyMesh, worldMtx, m_VolumeMaterial, 0, shaderPass); + } + + public void SetupMaterialPerFrame(Matrix4x4 viewProjMtx, Matrix4x4 viewMtx, Transform cameraTransform, float offsetIndex) + { + m_VolumeMaterial.DisableKeyword("SAMPLES_4"); + m_VolumeMaterial.DisableKeyword("SAMPLES_8"); + m_VolumeMaterial.DisableKeyword("SAMPLES_16"); + m_VolumeMaterial.DisableKeyword("SAMPLES_32"); + switch (m_Samples) + { + case DS_SamplingQuality.x4: + m_VolumeMaterial.EnableKeyword("SAMPLES_4"); + break; + case DS_SamplingQuality.x8: + m_VolumeMaterial.EnableKeyword("SAMPLES_8"); + break; + case DS_SamplingQuality.x16: + m_VolumeMaterial.EnableKeyword("SAMPLES_16"); + break; + case DS_SamplingQuality.x32: + m_VolumeMaterial.EnableKeyword("SAMPLES_32"); + break; + default: + m_VolumeMaterial.EnableKeyword("SAMPLES_16"); + break; + } + float num = 1f - Mathf.Clamp01((Vector3.Distance(cameraTransform.position, base.transform.position) - m_StartFade) / (m_EndFade - m_StartFade)); + m_VolumeMaterial.SetVector("_DS_HazeSamplingParams", new Vector4(offsetIndex, 0f, m_DensityTextureContrast, 0f)); + m_VolumeMaterial.SetVector("_DS_HazeCameraDirection", new Vector4(cameraTransform.forward.x, cameraTransform.forward.y, cameraTransform.forward.z, 1f)); + m_VolumeMaterial.SetColor("_DS_HazeLightVolumeColour", m_Light.color.linear * m_Light.intensity * num); + m_VolumeMaterial.SetVector("_DS_HazeLightVolumeScattering", new Vector4(m_Scattering, m_SecondaryScattering, m_ScatteringDirection, Mathf.Clamp01(1f - m_SecondaryScattering))); + m_VolumeMaterial.SetVector("_DS_HazeLightVolumeParams0", new Vector4(base.transform.position.x, base.transform.position.y, base.transform.position.z, m_Light.range)); + Matrix4x4 matrix4x = Matrix4x4.TRS(base.transform.position, base.transform.rotation, new Vector3(m_Light.range, m_Light.range, m_Light.range)); + m_VolumeMaterial.SetMatrix("_WorldViewProj", viewProjMtx * matrix4x); + m_VolumeMaterial.SetMatrix("_WorldView", viewMtx * matrix4x); + if ((bool)m_DensityTexture) + { + m_VolumeMaterial.EnableKeyword("DENSITY_TEXTURE"); + m_VolumeMaterial.SetTexture("_DensityTexture", m_DensityTexture); + m_VolumeMaterial.SetVector("_DS_HazeDensityParams", new Vector4(m_DensityOffset.x, m_DensityOffset.y, m_DensityOffset.z, m_DensityTextureScale * 0.01f)); + } + else + { + m_VolumeMaterial.DisableKeyword("DENSITY_TEXTURE"); + } + bool flag = m_Light.shadows != LightShadows.None; + if (m_Light.type == LightType.Point) + { + m_VolumeMaterial.DisableKeyword("SPOT_COOKIE"); + m_VolumeMaterial.DisableKeyword("SHADOWS_DEPTH"); + if (flag) + { + m_VolumeMaterial.EnableKeyword("SHADOWS_CUBE"); + } + else + { + m_VolumeMaterial.DisableKeyword("SHADOWS_CUBE"); + } + if ((bool)m_Light.cookie) + { + m_VolumeMaterial.EnableKeyword("POINT_COOKIE"); + m_VolumeMaterial.SetMatrix("_DS_Haze_WorldToCookie", base.transform.worldToLocalMatrix); + m_VolumeMaterial.SetTexture("_LightTexture0", m_Light.cookie); + } + else + { + m_VolumeMaterial.DisableKeyword("POINT_COOKIE"); + } + } + else if (m_Light.type == LightType.Spot) + { + m_VolumeMaterial.DisableKeyword("POINT_COOKIE"); + m_VolumeMaterial.DisableKeyword("SHADOWS_CUBE"); + if (flag) + { + m_VolumeMaterial.EnableKeyword("SHADOWS_DEPTH"); + Matrix4x4 inverse = Matrix4x4.TRS(base.transform.position, base.transform.rotation, Vector3.one).inverse; + Matrix4x4 matrix4x2 = Matrix4x4.TRS(new Vector3(0.5f, 0.5f, 0.5f), Quaternion.identity, new Vector3(0.5f, 0.5f, 0.5f)); + Matrix4x4 matrix4x3 = Matrix4x4.Perspective(m_Light.spotAngle, 1f, m_Light.range, m_Light.shadowNearPlane); + Matrix4x4 value = matrix4x2 * matrix4x3; + value[0, 2] *= -1f; + value[1, 2] *= -1f; + value[2, 2] *= -1f; + value[3, 2] *= -1f; + value *= inverse; + m_VolumeMaterial.SetMatrix("_DS_Haze_WorldToShadow", value); + } + else + { + m_VolumeMaterial.DisableKeyword("SHADOWS_DEPTH"); + } + float num2 = Mathf.Cos(m_Light.spotAngle / 2f * ((float)Math.PI / 180f)); + Vector3 lhs = base.transform.position + base.transform.forward * m_Light.range; + float z = 0f - Vector3.Dot(lhs, base.transform.forward); + m_VolumeMaterial.SetVector("_DS_HazeLightVolumeParams1", new Vector4(base.transform.forward.x, base.transform.forward.y, base.transform.forward.z, 1f)); + m_VolumeMaterial.SetVector("_DS_HazeLightVolumeParams2", new Vector4(num2, 1f / num2, z, 0f)); + if ((bool)m_Light.cookie) + { + m_VolumeMaterial.EnableKeyword("SPOT_COOKIE"); + Matrix4x4 inverse2 = Matrix4x4.TRS(base.transform.position, base.transform.rotation, Vector3.one).inverse; + Matrix4x4 matrix4x4 = Matrix4x4.TRS(new Vector3(0.5f, 0.5f, 0f), Quaternion.identity, new Vector3(-0.5f, -0.5f, 1f)); + Matrix4x4 matrix4x5 = Matrix4x4.Perspective(m_Light.spotAngle, 1f, 0f, 1f); + m_VolumeMaterial.SetMatrix("_DS_Haze_WorldToCookie", matrix4x4 * matrix4x5 * inverse2); + m_VolumeMaterial.SetTexture("_LightTexture0", m_Light.cookie); + } + else + { + m_VolumeMaterial.DisableKeyword("SPOT_COOKIE"); + } + } + } +} diff --git a/DeepSky.Haze/DS_HazeView.cs b/DeepSky.Haze/DS_HazeView.cs new file mode 100644 index 0000000..925f1a3 --- /dev/null +++ b/DeepSky.Haze/DS_HazeView.cs @@ -0,0 +1,1120 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Rendering; + +namespace DeepSky.Haze; + +[ExecuteInEditMode] +[AddComponentMenu("DeepSky Haze/View", 1)] +public class DS_HazeView : MonoBehaviour +{ + private enum SizeFactor + { + Half = 2, + Quarter = 4 + } + + private enum VolumeSamples + { + x16, + x24, + x32 + } + + private static string kClearRadianceCmdBufferName = "DS_Haze_ClearRadiance"; + + private static string kShadowCascadesCmdBufferName = "DS_Haze_ShadowCascadesCopy"; + + private static string kDirectionalLightCmdBufferName = "DS_Haze_DirectLight"; + + private static string kRenderLightVolumeCmdBufferName = "DS_Haze_RenderLightVolume"; + + private static string kPreviousDepthTargetName = "DS_Haze_PreviousDepthTarget"; + + private static string kRadianceTarget01Name = "DS_Haze_RadianceTarget_01"; + + private static string kRadianceTarget02Name = "DS_Haze_RadianceTarget_02"; + + private static Shader kShader; + + [SerializeField] + private bool m_OverrideTime; + + [SerializeField] + [Range(0f, 1f)] + private float m_Time = 0.5f; + + [SerializeField] + private bool m_OverrideContextAsset; + + [SerializeField] + private DS_HazeContextAsset m_Context; + + [SerializeField] + private bool m_OverrideContextVariant; + + [SerializeField] + private int m_ContextItemIndex; + + [SerializeField] + private Light m_DirectLight; + + [SerializeField] + private bool m_RenderAtmosphereVolumetrics = true; + + [SerializeField] + private bool m_RenderLocalVolumetrics = true; + + [SerializeField] + private bool m_TemporalReprojection = true; + + [SerializeField] + private SizeFactor m_DownsampleFactor = SizeFactor.Half; + + [SerializeField] + private VolumeSamples m_VolumeSamples; + + [SerializeField] + [Range(100f, 5000f)] + private int m_GaussianDepthFalloff = 500; + + [SerializeField] + [Range(0f, 0.5f)] + private float m_UpsampleDepthThreshold = 0.06f; + + [SerializeField] + [Range(0.001f, 1f)] + private float m_TemporalRejectionScale = 0.1f; + + [SerializeField] + [Range(0.1f, 0.9f)] + private float m_TemporalBlendFactor = 0.25f; + + private ShadowProjection m_ShadowProjectionType = ShadowProjection.StableFit; + + [SerializeField] + private bool m_ApplyAirToSkybox; + + [SerializeField] + private bool m_ApplyHazeToSkybox = true; + + [SerializeField] + private bool m_ApplyFogExtinctionToSkybox = true; + + [SerializeField] + private bool m_ApplyFogLightingToSkybox = true; + + [SerializeField] + private bool m_ShowTemporalRejection; + + [SerializeField] + private bool m_ShowUpsampleThreshold; + + private Camera m_Camera; + + private RenderTexture m_PerFrameRadianceTarget; + + private RenderTexture m_RadianceTarget_01; + + private RenderTexture m_RadianceTarget_02; + + private RenderTexture m_CurrentRadianceTarget; + + private RenderTexture m_PreviousRadianceTarget; + + private RenderTexture m_PreviousDepthTarget; + + private CommandBuffer m_ShadowCascadesCmdBuffer; + + private CommandBuffer m_DirectionalLightCmdBuffer; + + private CommandBuffer m_ClearRadianceCmdBuffer; + + private CommandBuffer m_RenderNonShadowVolumes; + + private Material m_Material; + + private Matrix4x4 m_PreviousViewProjMatrix = Matrix4x4.identity; + + private Matrix4x4 m_PreviousInvViewProjMatrix = Matrix4x4.identity; + + private float m_InterleavedOffsetIndex; + + private int m_X; + + private int m_Y; + + private RenderingPath m_PreviousRenderPath; + + private ColorSpace m_ColourSpace; + + private List<DS_HazeLightVolume> m_PerFrameLightVolumes = new List<DS_HazeLightVolume>(); + + private List<DS_HazeLightVolume> m_PerFrameShadowLightVolumes = new List<DS_HazeLightVolume>(); + + private Dictionary<Light, CommandBuffer> m_LightVolumeCmdBuffers = new Dictionary<Light, CommandBuffer>(); + + public bool OverrideTime + { + get + { + return m_OverrideTime; + } + set + { + m_OverrideTime = value; + if (value && m_OverrideContextVariant) + { + m_OverrideContextVariant = false; + } + } + } + + public float Time + { + get + { + return m_Time; + } + set + { + m_Time = value; + } + } + + public bool OverrideContextAsset + { + get + { + return m_OverrideContextAsset; + } + set + { + m_OverrideContextAsset = value; + } + } + + public DS_HazeContextAsset ContextAsset + { + get + { + return m_Context; + } + set + { + m_Context = value; + } + } + + public bool OverrideContextVariant + { + get + { + return m_OverrideContextVariant; + } + set + { + m_OverrideContextVariant = value; + if (value && m_OverrideTime) + { + m_OverrideTime = false; + } + } + } + + public int ContextItemIndex + { + get + { + return m_ContextItemIndex; + } + set + { + m_ContextItemIndex = ((value > 0) ? value : 0); + } + } + + public Light DirectLight + { + get + { + return m_DirectLight; + } + set + { + m_DirectLight = value; + } + } + + public Vector2 RadianceTargetSize => new Vector2(m_X, m_Y); + + public int SampleCount => m_VolumeSamples switch + { + VolumeSamples.x16 => 16, + VolumeSamples.x24 => 24, + VolumeSamples.x32 => 32, + _ => 16, + }; + + public int DownSampleFactor => (m_DownsampleFactor != SizeFactor.Half) ? 4 : 2; + + public bool RenderAtmosphereVolumetrics + { + get + { + return m_RenderAtmosphereVolumetrics; + } + set + { + m_RenderAtmosphereVolumetrics = value; + SetTemporalKeywords(); + } + } + + public bool RenderLocalVolumetrics + { + get + { + return m_RenderLocalVolumetrics; + } + set + { + m_RenderLocalVolumetrics = value; + SetTemporalKeywords(); + } + } + + public bool TemporalReprojection + { + get + { + return m_TemporalReprojection; + } + set + { + m_TemporalReprojection = value; + SetTemporalKeywords(); + } + } + + public bool WillRenderWithTemporalReprojection => m_TemporalReprojection & (m_RenderAtmosphereVolumetrics | m_RenderLocalVolumetrics); + + public int AntiAliasingLevel() + { + int result = 1; + if (m_Camera.actualRenderingPath == RenderingPath.Forward && m_Camera.allowMSAA && QualitySettings.antiAliasing > 0) + { + result = QualitySettings.antiAliasing; + } + return result; + } + + private bool CheckHasSystemSupport() + { + if (!SystemInfo.supportsImageEffects) + { + Debug.LogError("DeepSky::DS_HazeView: Image effects are not supported on this platform."); + base.enabled = false; + return false; + } + if (SystemInfo.graphicsShaderLevel < 30) + { + Debug.LogError("DeepSky::DS_HazeView: Minimum required shader model (3.0) is not supported on this platform."); + base.enabled = false; + return false; + } + if (m_Camera.allowHDR && !SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf)) + { + Debug.LogError("DeepSky::DS_HazeView: ARGBHalf render texture format is not supported on this platform."); + base.enabled = false; + return false; + } + if (!SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.RFloat)) + { + Debug.LogError("DeepSky::DS_HazeView: RFloat render texture format is not supported on this platform."); + base.enabled = false; + return false; + } + return true; + } + + private void SetMaterialFromContext(DS_HazeContextItem ctx) + { + if (WillRenderWithTemporalReprojection) + { + m_InterleavedOffsetIndex += 0.0625f; + if (Mathf.Approximately(m_InterleavedOffsetIndex, 1f)) + { + m_InterleavedOffsetIndex = 0f; + } + } + float x = 1f; + float y = 1f; + float z = 1f; + switch (DS_HazeCore.Instance.HeightFalloff) + { + case DS_HazeCore.HeightFalloffType.None: + x = 1f; + y = 1f; + z = 1f; + break; + case DS_HazeCore.HeightFalloffType.Exponential: + { + float num = Mathf.Abs(base.transform.position.y); + x = Mathf.Exp((0f - ctx.m_AirDensityHeightFalloff) * num); + y = Mathf.Exp((0f - ctx.m_HazeDensityHeightFalloff) * num); + z = Mathf.Exp((0f - ctx.m_FogDensityHeightFalloff) * (num - ctx.m_FogStartHeight)); + break; + } + } + Vector3 vector = ctx.m_AirScatteringScale * new Vector3(0.00116f, 0.0027f, 0.00662f); + float x2 = ctx.m_HazeScatteringScale * 0.0021f; + float fogScatteringScale = ctx.m_FogScatteringScale; + float w = ctx.m_FogExtinctionScale * 0.01f; + Vector4 value = new Vector4(ctx.m_AirDensityHeightFalloff, ctx.m_HazeDensityHeightFalloff, 0f, ctx.m_HazeScatteringDirection); + Vector4 value2 = new Vector4(x2, (!m_RenderAtmosphereVolumetrics) ? 0f : ctx.m_HazeSecondaryScatteringRatio, fogScatteringScale, w); + Vector4 value3 = new Vector4(x, y, z, 0f); + Vector4 value4 = new Vector4(ctx.m_FogStartDistance, ctx.m_FogDensityHeightFalloff, ctx.m_FogOpacity, ctx.m_FogScatteringDirection); + Vector4 value5 = new Vector4(m_GaussianDepthFalloff, m_UpsampleDepthThreshold * 0.01f, m_TemporalRejectionScale, m_TemporalBlendFactor); + m_Material.SetVector("_SamplingParams", value5); + m_Material.SetVector("_InterleavedOffset", new Vector4(m_InterleavedOffsetIndex, 0f, 0f, 0f)); + m_Material.SetMatrix("_PreviousViewProjMatrix", m_PreviousViewProjMatrix); + m_Material.SetMatrix("_PreviousInvViewProjMatrix", m_PreviousInvViewProjMatrix); + Shader.SetGlobalVector("_DS_BetaParams", value2); + Shader.SetGlobalVector("_DS_RBetaS", vector); + Shader.SetGlobalVector("_DS_AirHazeParams", value); + Shader.SetGlobalVector("_DS_FogParams", value4); + Shader.SetGlobalVector("_DS_InitialDensityParams", value3); + Vector3 vector2; + Color color; + if ((bool)m_DirectLight) + { + vector2 = -m_DirectLight.transform.forward; + color = m_DirectLight.color.linear * m_DirectLight.intensity; + Shader.SetGlobalColor("_DS_FogAmbientLight", ctx.m_FogAmbientColour.linear * m_DirectLight.intensity); + Shader.SetGlobalColor("_DS_FogDirectLight", ctx.m_FogLightColour.linear * m_DirectLight.intensity); + } + else + { + vector2 = Vector3.up; + color = Color.white; + Shader.SetGlobalColor("_DS_FogAmbientLight", ctx.m_FogAmbientColour.linear); + Shader.SetGlobalColor("_DS_FogDirectLight", ctx.m_FogLightColour.linear); + } + Shader.SetGlobalVector("_DS_LightDirection", vector2); + Shader.SetGlobalVector("_DS_LightColour", color); + } + + private void SetGlobalParamsToNull() + { + Shader.SetGlobalVector("_DS_BetaParams", Vector4.zero); + Shader.SetGlobalVector("_DS_RBetaS", Vector4.zero); + } + + public void SetDebugKeywords() + { + if (m_ShowTemporalRejection) + { + m_Material.EnableKeyword("SHOW_TEMPORAL_REJECTION"); + } + else + { + m_Material.DisableKeyword("SHOW_TEMPORAL_REJECTION"); + } + if (m_ShowUpsampleThreshold) + { + m_Material.EnableKeyword("SHOW_UPSAMPLE_THRESHOLD"); + } + else + { + m_Material.DisableKeyword("SHOW_UPSAMPLE_THRESHOLD"); + } + } + + public void SetSkyboxKeywords() + { + if (m_ApplyAirToSkybox) + { + m_Material.EnableKeyword("DS_HAZE_APPLY_RAYLEIGH"); + } + else + { + m_Material.DisableKeyword("DS_HAZE_APPLY_RAYLEIGH"); + } + if (m_ApplyHazeToSkybox) + { + m_Material.EnableKeyword("DS_HAZE_APPLY_MIE"); + } + else + { + m_Material.DisableKeyword("DS_HAZE_APPLY_MIE"); + } + if (m_ApplyFogExtinctionToSkybox) + { + m_Material.EnableKeyword("DS_HAZE_APPLY_FOG_EXTINCTION"); + } + else + { + m_Material.DisableKeyword("DS_HAZE_APPLY_FOG_EXTINCTION"); + } + if (m_ApplyFogLightingToSkybox) + { + m_Material.EnableKeyword("DS_HAZE_APPLY_FOG_RADIANCE"); + } + else + { + m_Material.DisableKeyword("DS_HAZE_APPLY_FOG_RADIANCE"); + } + } + + public void SetTemporalKeywords() + { + if (WillRenderWithTemporalReprojection) + { + m_Material.EnableKeyword("DS_HAZE_TEMPORAL"); + return; + } + m_Material.DisableKeyword("DS_HAZE_TEMPORAL"); + if (m_ShowTemporalRejection) + { + m_ShowTemporalRejection = false; + m_Material.DisableKeyword("SHOW_TEMPORAL_REJECTION"); + } + if ((bool)m_RadianceTarget_01) + { + m_RadianceTarget_01.Release(); + UnityEngine.Object.DestroyImmediate(m_RadianceTarget_01); + m_RadianceTarget_01 = null; + } + if ((bool)m_RadianceTarget_02) + { + m_RadianceTarget_02.Release(); + UnityEngine.Object.DestroyImmediate(m_RadianceTarget_02); + m_RadianceTarget_02 = null; + } + if ((bool)m_PreviousDepthTarget) + { + m_PreviousDepthTarget.Release(); + UnityEngine.Object.DestroyImmediate(m_PreviousDepthTarget); + m_PreviousDepthTarget = null; + } + } + + private void SetShaderKeyWords() + { + if (m_ShadowProjectionType == ShadowProjection.CloseFit) + { + m_Material.EnableKeyword("SHADOW_PROJ_CLOSE"); + } + else if (m_ShadowProjectionType == ShadowProjection.StableFit) + { + m_Material.DisableKeyword("SHADOW_PROJ_CLOSE"); + } + if (DS_HazeCore.Instance != null) + { + switch (DS_HazeCore.Instance.HeightFalloff) + { + case DS_HazeCore.HeightFalloffType.None: + m_Material.EnableKeyword("DS_HAZE_HEIGHT_FALLOFF_NONE"); + break; + case DS_HazeCore.HeightFalloffType.Exponential: + m_Material.DisableKeyword("DS_HAZE_HEIGHT_FALLOFF_NONE"); + break; + default: + m_Material.EnableKeyword("DS_HAZE_HEIGHT_FALLOFF_NONE"); + break; + } + } + } + + private void OnEnable() + { + SetGlobalParamsToNull(); + m_Camera = GetComponent<Camera>(); + if (!m_Camera) + { + Debug.LogError("DeepSky::DS_HazeView: GameObject '" + base.gameObject.name + "' does not have a camera component!"); + base.enabled = false; + return; + } + if (!CheckHasSystemSupport()) + { + base.enabled = false; + return; + } + if (kShader == null) + { + kShader = Resources.Load<Shader>("DS_Haze"); + } + if (m_Material == null) + { + m_Material = new Material(kShader); + m_Material.hideFlags = HideFlags.HideAndDontSave; + } + if (m_Camera.actualRenderingPath == RenderingPath.Forward && (m_Camera.depthTextureMode & DepthTextureMode.Depth) != DepthTextureMode.Depth) + { + m_Camera.depthTextureMode |= DepthTextureMode.Depth; + } + if (m_RenderNonShadowVolumes == null) + { + CommandBuffer[] commandBuffers = m_Camera.GetCommandBuffers(CameraEvent.BeforeImageEffectsOpaque); + bool flag = false; + CommandBuffer[] array = commandBuffers; + foreach (CommandBuffer commandBuffer in array) + { + if (commandBuffer.name == kRenderLightVolumeCmdBufferName) + { + m_RenderNonShadowVolumes = commandBuffer; + flag = true; + break; + } + } + if (!flag) + { + m_RenderNonShadowVolumes = new CommandBuffer(); + m_RenderNonShadowVolumes.name = kRenderLightVolumeCmdBufferName; + m_Camera.AddCommandBuffer(CameraEvent.BeforeImageEffectsOpaque, m_RenderNonShadowVolumes); + } + } + m_CurrentRadianceTarget = m_RadianceTarget_01; + m_PreviousRadianceTarget = m_RadianceTarget_02; + SetSkyboxKeywords(); + SetDebugKeywords(); + m_ColourSpace = QualitySettings.activeColorSpace; + m_PreviousRenderPath = m_Camera.actualRenderingPath; + } + + private void CreateRadianceTarget(string name, out RenderTexture radianceTarget) + { + if (m_Camera.allowHDR) + { + radianceTarget = new RenderTexture(m_Camera.pixelWidth, m_Camera.pixelHeight, 0, RenderTextureFormat.ARGBHalf); + } + else + { + radianceTarget = new RenderTexture(m_Camera.pixelWidth, m_Camera.pixelHeight, 0, RenderTextureFormat.ARGB32); + } + radianceTarget.name = name; + radianceTarget.antiAliasing = AntiAliasingLevel(); + radianceTarget.useMipMap = false; + radianceTarget.hideFlags = HideFlags.HideAndDontSave; + radianceTarget.filterMode = FilterMode.Point; + } + + private void CreateDepthTarget(string name, out RenderTexture depthTarget, bool downsample = false) + { + depthTarget = new RenderTexture((!downsample) ? m_Camera.pixelWidth : m_X, (!downsample) ? m_Camera.pixelHeight : m_Y, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear); + depthTarget.name = name; + depthTarget.antiAliasing = 1; + depthTarget.useMipMap = false; + depthTarget.hideFlags = HideFlags.HideAndDontSave; + depthTarget.filterMode = FilterMode.Point; + } + + private bool CameraHasClearRadianceCmdBuffer(out CommandBuffer foundCmd) + { + CommandBuffer[] commandBuffers; + if (m_Camera.actualRenderingPath == RenderingPath.DeferredShading) + { + commandBuffers = m_Camera.GetCommandBuffers(CameraEvent.BeforeGBuffer); + } + else + { + CameraEvent evt = (((m_Camera.depthTextureMode & DepthTextureMode.DepthNormals) == DepthTextureMode.DepthNormals) ? CameraEvent.BeforeDepthNormalsTexture : CameraEvent.BeforeDepthTexture); + commandBuffers = m_Camera.GetCommandBuffers(evt); + } + CommandBuffer[] array = commandBuffers; + foreach (CommandBuffer commandBuffer in array) + { + if (commandBuffer.name == kClearRadianceCmdBufferName) + { + foundCmd = commandBuffer; + return true; + } + } + foundCmd = null; + return false; + } + + private CommandBuffer LightHasCascadesCopyCmdBuffer() + { + CommandBuffer[] commandBuffers = m_DirectLight.GetCommandBuffers(LightEvent.AfterShadowMap); + CommandBuffer[] array = commandBuffers; + foreach (CommandBuffer commandBuffer in array) + { + if (commandBuffer.name == kShadowCascadesCmdBufferName) + { + return commandBuffer; + } + } + return null; + } + + private CommandBuffer LightHasRenderCmdBuffer() + { + CommandBuffer[] commandBuffers = m_DirectLight.GetCommandBuffers(LightEvent.AfterScreenspaceMask); + CommandBuffer[] array = commandBuffers; + foreach (CommandBuffer commandBuffer in array) + { + if (commandBuffer.name == kDirectionalLightCmdBufferName) + { + return commandBuffer; + } + } + return null; + } + + public void RemoveCommandBufferFromLight(Light light) + { + CommandBuffer[] commandBuffers = light.GetCommandBuffers(LightEvent.AfterShadowMap); + for (int i = 0; i < commandBuffers.Length; i++) + { + if (commandBuffers[i].name == kShadowCascadesCmdBufferName) + { + light.RemoveCommandBuffer(LightEvent.AfterShadowMap, commandBuffers[i]); + break; + } + } + commandBuffers = light.GetCommandBuffers(LightEvent.AfterScreenspaceMask); + for (int j = 0; j < commandBuffers.Length; j++) + { + if (commandBuffers[j].name == kDirectionalLightCmdBufferName) + { + light.RemoveCommandBuffer(LightEvent.AfterScreenspaceMask, commandBuffers[j]); + break; + } + } + } + + private void RenderPathChanged() + { + if (m_Camera.actualRenderingPath == RenderingPath.Forward && (m_Camera.depthTextureMode & DepthTextureMode.Depth) != DepthTextureMode.Depth) + { + m_Camera.depthTextureMode |= DepthTextureMode.Depth; + } + if (m_ClearRadianceCmdBuffer != null) + { + CameraEvent evt = ((m_PreviousRenderPath != RenderingPath.DeferredShading) ? (((m_Camera.depthTextureMode & DepthTextureMode.DepthNormals) == DepthTextureMode.DepthNormals) ? CameraEvent.BeforeDepthNormalsTexture : CameraEvent.BeforeDepthTexture) : CameraEvent.BeforeGBuffer); + CommandBuffer[] commandBuffers = m_Camera.GetCommandBuffers(evt); + CommandBuffer[] array = commandBuffers; + foreach (CommandBuffer commandBuffer in array) + { + if (commandBuffer.name == kClearRadianceCmdBufferName) + { + m_Camera.RemoveCommandBuffer(evt, commandBuffer); + break; + } + } + } + m_PreviousRenderPath = m_Camera.actualRenderingPath; + } + + private void UpdateResources() + { + m_X = m_Camera.pixelWidth / (int)m_DownsampleFactor; + m_Y = m_Camera.pixelHeight / (int)m_DownsampleFactor; + if (m_Camera.actualRenderingPath != m_PreviousRenderPath) + { + RenderPathChanged(); + } + RenderTextureFormat renderTextureFormat = (m_Camera.allowHDR ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32); + bool flag = m_ColourSpace != QualitySettings.activeColorSpace; + m_ColourSpace = QualitySettings.activeColorSpace; + if (WillRenderWithTemporalReprojection) + { + if (m_RadianceTarget_01 == null) + { + CreateRadianceTarget(kRadianceTarget01Name, out m_RadianceTarget_01); + m_CurrentRadianceTarget = m_RadianceTarget_01; + } + else if (flag || m_RadianceTarget_01.width != m_Camera.pixelWidth || m_RadianceTarget_01.height != m_Camera.pixelHeight || m_RadianceTarget_01.format != renderTextureFormat) + { + UnityEngine.Object.DestroyImmediate(m_RadianceTarget_01); + CreateRadianceTarget(kRadianceTarget01Name, out m_RadianceTarget_01); + m_CurrentRadianceTarget = m_RadianceTarget_01; + } + if (m_RadianceTarget_02 == null) + { + CreateRadianceTarget(kRadianceTarget02Name, out m_RadianceTarget_02); + m_PreviousRadianceTarget = m_RadianceTarget_02; + } + else if (flag || m_RadianceTarget_02.width != m_Camera.pixelWidth || m_RadianceTarget_02.height != m_Camera.pixelHeight || m_RadianceTarget_02.format != renderTextureFormat) + { + UnityEngine.Object.DestroyImmediate(m_RadianceTarget_02); + CreateRadianceTarget(kRadianceTarget02Name, out m_RadianceTarget_02); + m_PreviousRadianceTarget = m_RadianceTarget_02; + } + if (m_PreviousDepthTarget == null) + { + CreateDepthTarget(kPreviousDepthTargetName, out m_PreviousDepthTarget); + } + else if (m_PreviousDepthTarget.width != m_Camera.pixelWidth || m_PreviousDepthTarget.height != m_Camera.pixelHeight) + { + UnityEngine.Object.DestroyImmediate(m_PreviousDepthTarget); + CreateDepthTarget(kPreviousDepthTargetName, out m_PreviousDepthTarget); + } + } + if (m_ClearRadianceCmdBuffer == null) + { + m_ClearRadianceCmdBuffer = new CommandBuffer(); + m_ClearRadianceCmdBuffer.name = kClearRadianceCmdBufferName; + } + CameraEvent evt = ((m_Camera.actualRenderingPath != RenderingPath.DeferredShading) ? (((m_Camera.depthTextureMode & DepthTextureMode.DepthNormals) == DepthTextureMode.DepthNormals) ? CameraEvent.BeforeDepthNormalsTexture : CameraEvent.BeforeDepthTexture) : CameraEvent.BeforeGBuffer); + if (!CameraHasClearRadianceCmdBuffer(out var foundCmd)) + { + m_Camera.AddCommandBuffer(evt, m_ClearRadianceCmdBuffer); + } + else if (foundCmd != m_ClearRadianceCmdBuffer) + { + m_Camera.RemoveCommandBuffer(evt, foundCmd); + foundCmd.Dispose(); + m_Camera.AddCommandBuffer(evt, m_ClearRadianceCmdBuffer); + } + if ((bool)m_DirectLight) + { + m_ShadowCascadesCmdBuffer = LightHasCascadesCopyCmdBuffer(); + if (m_ShadowCascadesCmdBuffer == null) + { + m_ShadowCascadesCmdBuffer = new CommandBuffer(); + m_ShadowCascadesCmdBuffer.name = kShadowCascadesCmdBufferName; + m_ShadowCascadesCmdBuffer.SetGlobalTexture("_ShadowCascades", new RenderTargetIdentifier(BuiltinRenderTextureType.CurrentActive)); + m_DirectLight.AddCommandBuffer(LightEvent.AfterShadowMap, m_ShadowCascadesCmdBuffer); + } + m_DirectionalLightCmdBuffer = LightHasRenderCmdBuffer(); + if (m_DirectionalLightCmdBuffer == null) + { + m_DirectionalLightCmdBuffer = new CommandBuffer(); + m_DirectionalLightCmdBuffer.name = kDirectionalLightCmdBufferName; + m_DirectLight.AddCommandBuffer(LightEvent.AfterScreenspaceMask, m_DirectionalLightCmdBuffer); + } + if (m_ShadowProjectionType != QualitySettings.shadowProjection) + { + m_ShadowProjectionType = QualitySettings.shadowProjection; + } + } + } + + private void OnDisable() + { + SetGlobalParamsToNull(); + CommandBuffer[] commandBuffers = m_Camera.GetCommandBuffers(CameraEvent.AfterSkybox); + CameraEvent evt = ((m_Camera.actualRenderingPath != RenderingPath.DeferredShading) ? (((m_Camera.depthTextureMode & DepthTextureMode.DepthNormals) == DepthTextureMode.DepthNormals) ? CameraEvent.BeforeDepthNormalsTexture : CameraEvent.BeforeDepthTexture) : CameraEvent.BeforeGBuffer); + commandBuffers = m_Camera.GetCommandBuffers(evt); + CommandBuffer[] array = commandBuffers; + foreach (CommandBuffer commandBuffer in array) + { + if (commandBuffer.name == kClearRadianceCmdBufferName) + { + m_Camera.RemoveCommandBuffer(evt, commandBuffer); + break; + } + } + if ((bool)m_DirectLight) + { + commandBuffers = m_DirectLight.GetCommandBuffers(LightEvent.AfterShadowMap); + CommandBuffer[] array2 = commandBuffers; + foreach (CommandBuffer commandBuffer2 in array2) + { + if (commandBuffer2.name == kShadowCascadesCmdBufferName) + { + m_DirectLight.RemoveCommandBuffer(LightEvent.AfterShadowMap, commandBuffer2); + break; + } + } + commandBuffers = m_DirectLight.GetCommandBuffers(LightEvent.AfterScreenspaceMask); + CommandBuffer[] array3 = commandBuffers; + foreach (CommandBuffer commandBuffer3 in array3) + { + if (commandBuffer3.name == kDirectionalLightCmdBufferName) + { + m_DirectLight.RemoveCommandBuffer(LightEvent.AfterScreenspaceMask, commandBuffer3); + break; + } + } + } + if (m_LightVolumeCmdBuffers.Count > 0) + { + foreach (KeyValuePair<Light, CommandBuffer> lightVolumeCmdBuffer in m_LightVolumeCmdBuffers) + { + lightVolumeCmdBuffer.Key.RemoveCommandBuffer(LightEvent.AfterShadowMap, lightVolumeCmdBuffer.Value); + lightVolumeCmdBuffer.Value.Dispose(); + } + m_LightVolumeCmdBuffers.Clear(); + } + if (m_RenderNonShadowVolumes != null) + { + m_RenderNonShadowVolumes.Clear(); + } + } + + private void OnDestroy() + { + if ((bool)m_RadianceTarget_01) + { + m_RadianceTarget_01.Release(); + UnityEngine.Object.DestroyImmediate(m_RadianceTarget_01); + m_RadianceTarget_01 = null; + } + if ((bool)m_RadianceTarget_02) + { + m_RadianceTarget_02.Release(); + UnityEngine.Object.DestroyImmediate(m_RadianceTarget_02); + m_RadianceTarget_02 = null; + } + if ((bool)m_PreviousDepthTarget) + { + m_PreviousDepthTarget.Release(); + UnityEngine.Object.DestroyImmediate(m_PreviousDepthTarget); + m_PreviousDepthTarget = null; + } + if (m_ClearRadianceCmdBuffer != null) + { + if (m_Camera.actualRenderingPath == RenderingPath.DeferredShading) + { + m_Camera.RemoveCommandBuffer(CameraEvent.BeforeGBuffer, m_ClearRadianceCmdBuffer); + } + else + { + CameraEvent evt = (((m_Camera.depthTextureMode & DepthTextureMode.DepthNormals) == DepthTextureMode.DepthNormals) ? CameraEvent.BeforeDepthNormalsTexture : CameraEvent.BeforeDepthTexture); + m_Camera.RemoveCommandBuffer(evt, m_ClearRadianceCmdBuffer); + } + m_ClearRadianceCmdBuffer.Dispose(); + m_ClearRadianceCmdBuffer = null; + } + if (m_ShadowCascadesCmdBuffer != null) + { + if (m_DirectLight != null) + { + m_DirectLight.RemoveCommandBuffer(LightEvent.AfterShadowMap, m_ShadowCascadesCmdBuffer); + } + m_ShadowCascadesCmdBuffer.Dispose(); + m_ShadowCascadesCmdBuffer = null; + } + if (m_DirectionalLightCmdBuffer != null) + { + if (m_DirectLight != null) + { + m_DirectLight.RemoveCommandBuffer(LightEvent.AfterScreenspaceMask, m_DirectionalLightCmdBuffer); + } + m_DirectionalLightCmdBuffer.Dispose(); + m_DirectionalLightCmdBuffer = null; + } + if (m_LightVolumeCmdBuffers.Count > 0) + { + foreach (KeyValuePair<Light, CommandBuffer> lightVolumeCmdBuffer in m_LightVolumeCmdBuffers) + { + lightVolumeCmdBuffer.Key.RemoveCommandBuffer(LightEvent.AfterShadowMap, lightVolumeCmdBuffer.Value); + lightVolumeCmdBuffer.Value.Dispose(); + } + m_LightVolumeCmdBuffers.Clear(); + } + if (m_RenderNonShadowVolumes != null) + { + m_Camera.RemoveCommandBuffer(CameraEvent.BeforeImageEffectsOpaque, m_RenderNonShadowVolumes); + m_RenderNonShadowVolumes.Dispose(); + m_RenderNonShadowVolumes = null; + } + } + + private void OnPreRender() + { + if (!CheckHasSystemSupport()) + { + base.enabled = false; + } + UpdateResources(); + SetShaderKeyWords(); + RenderTextureFormat format = (m_Camera.allowHDR ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32); + m_PerFrameRadianceTarget = RenderTexture.GetTemporary(m_X, m_Y, 0, format, RenderTextureReadWrite.Linear, AntiAliasingLevel()); + m_PerFrameRadianceTarget.name = "_DS_Haze_PerFrameRadiance"; + m_PerFrameRadianceTarget.filterMode = FilterMode.Point; + m_ClearRadianceCmdBuffer.Clear(); + m_ClearRadianceCmdBuffer.SetRenderTarget(m_PerFrameRadianceTarget); + m_ClearRadianceCmdBuffer.ClearRenderTarget(clearDepth: false, clearColor: true, Color.clear); + DS_HazeCore instance = DS_HazeCore.Instance; + DS_HazeContextItem dS_HazeContextItem = null; + if (m_OverrideContextAsset && m_Context != null) + { + dS_HazeContextItem = ((!m_OverrideContextVariant) ? m_Context.Context.GetContextItemBlended(m_Time) : m_Context.Context.GetItemAtIndex(m_ContextItemIndex)); + } + else + { + if (instance == null) + { + SetGlobalParamsToNull(); + return; + } + dS_HazeContextItem = instance.GetRenderContextAtPosition(base.transform.position); + } + if (dS_HazeContextItem == null) + { + SetGlobalParamsToNull(); + } + else + { + SetMaterialFromContext(dS_HazeContextItem); + float farClipPlane = m_Camera.farClipPlane; + float num = m_Camera.fieldOfView * 0.5f; + float num2 = Mathf.Tan(num * ((float)Math.PI / 180f)); + float num3 = num2 * m_Camera.aspect; + Vector3 vector = base.transform.forward * farClipPlane; + Vector3 vector2 = base.transform.right * num3 * farClipPlane; + Vector3 vector3 = base.transform.up * num2 * farClipPlane; + m_Material.SetVector("_ViewportCorner", vector - vector2 - vector3); + m_Material.SetVector("_ViewportRight", vector2 * 2f); + m_Material.SetVector("_ViewportUp", vector3 * 2f); + if ((bool)m_DirectLight && m_RenderAtmosphereVolumetrics) + { + m_DirectionalLightCmdBuffer.Blit(BuiltinRenderTextureType.None, m_PerFrameRadianceTarget, m_Material, (int)(m_VolumeSamples + ((m_DownsampleFactor != SizeFactor.Half) ? 3 : 0))); + } + } + if (!m_RenderLocalVolumetrics) + { + return; + } + Matrix4x4 gPUProjectionMatrix = GL.GetGPUProjectionMatrix(m_Camera.projectionMatrix, renderIntoTexture: true); + Matrix4x4 viewProjMtx = gPUProjectionMatrix * m_Camera.worldToCameraMatrix; + instance.GetRenderLightVolumes(base.transform.position, m_PerFrameLightVolumes, m_PerFrameShadowLightVolumes); + if (m_PerFrameLightVolumes.Count > 0) + { + m_RenderNonShadowVolumes.SetRenderTarget(m_PerFrameRadianceTarget); + } + foreach (DS_HazeLightVolume perFrameLightVolume in m_PerFrameLightVolumes) + { + perFrameLightVolume.SetupMaterialPerFrame(viewProjMtx, m_Camera.worldToCameraMatrix, base.transform, (!WillRenderWithTemporalReprojection) ? 0f : m_InterleavedOffsetIndex); + perFrameLightVolume.AddLightRenderCommand(base.transform, m_RenderNonShadowVolumes, (int)m_DownsampleFactor); + } + foreach (DS_HazeLightVolume perFrameShadowLightVolume in m_PerFrameShadowLightVolumes) + { + perFrameShadowLightVolume.SetupMaterialPerFrame(viewProjMtx, m_Camera.worldToCameraMatrix, base.transform, (!WillRenderWithTemporalReprojection) ? 0f : m_InterleavedOffsetIndex); + perFrameShadowLightVolume.FillLightCommandBuffer(m_PerFrameRadianceTarget, base.transform, (int)m_DownsampleFactor); + m_LightVolumeCmdBuffers.Add(perFrameShadowLightVolume.LightSource, perFrameShadowLightVolume.RenderCommandBuffer); + } + } + + private void BlitToMRT(RenderTexture source, RenderTexture[] destination, Material mat, int pass) + { + RenderBuffer[] array = new RenderBuffer[destination.Length]; + for (int i = 0; i < destination.Length; i++) + { + ref RenderBuffer reference = ref array[i]; + reference = destination[i].colorBuffer; + } + Graphics.SetRenderTarget(array, destination[0].depthBuffer); + mat.SetTexture("_MainTex", source); + mat.SetPass(pass); + GL.PushMatrix(); + GL.LoadOrtho(); + GL.Begin(7); + GL.MultiTexCoord2(0, 0f, 0f); + GL.Vertex3(0f, 0f, 0.1f); + GL.MultiTexCoord2(0, 1f, 0f); + GL.Vertex3(1f, 0f, 0.1f); + GL.MultiTexCoord2(0, 1f, 1f); + GL.Vertex3(1f, 1f, 0.1f); + GL.MultiTexCoord2(0, 0f, 1f); + GL.Vertex3(0f, 1f, 0.1f); + GL.End(); + GL.PopMatrix(); + } + + [ImageEffectOpaque] + private void OnRenderImage(RenderTexture src, RenderTexture dest) + { + RenderTexture renderTexture = null; + RenderTexture renderTexture2 = null; + if (m_RenderAtmosphereVolumetrics || m_RenderLocalVolumetrics) + { + renderTexture = RenderTexture.GetTemporary(m_X, m_Y, 0, m_Camera.allowHDR ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32); + renderTexture2 = RenderTexture.GetTemporary(m_X, m_Y, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear, 1); + Graphics.Blit(null, renderTexture2, m_Material, (m_DownsampleFactor != SizeFactor.Half) ? 11 : 10); + m_Material.SetTexture("_HalfResDepth", renderTexture2); + Graphics.Blit(m_PerFrameRadianceTarget, renderTexture, m_Material, 6); + Graphics.Blit(renderTexture, m_PerFrameRadianceTarget, m_Material, 7); + if (m_TemporalReprojection) + { + m_Material.SetTexture("_PrevAccumBuffer", m_PreviousRadianceTarget); + m_Material.SetTexture("_PrevDepthBuffer", m_PreviousDepthTarget); + } + } + m_PerFrameRadianceTarget.filterMode = FilterMode.Bilinear; + m_Material.SetTexture("_RadianceBuffer", m_PerFrameRadianceTarget); + if (dest == null) + { + RenderTexture temporary = RenderTexture.GetTemporary(src.width, src.height, src.depth, src.format); + if (WillRenderWithTemporalReprojection) + { + RenderTexture[] destination = new RenderTexture[2] { temporary, m_CurrentRadianceTarget }; + BlitToMRT(src, destination, m_Material, 8); + } + else + { + Graphics.Blit(src, temporary, m_Material, 8); + } + Graphics.Blit((Texture)temporary, (RenderTexture)null); + RenderTexture.ReleaseTemporary(temporary); + } + else if (WillRenderWithTemporalReprojection) + { + RenderTexture[] destination2 = new RenderTexture[2] { dest, m_CurrentRadianceTarget }; + BlitToMRT(src, destination2, m_Material, 8); + } + else + { + Graphics.Blit(src, dest, m_Material, 8); + } + if (WillRenderWithTemporalReprojection) + { + Graphics.Blit(src, m_PreviousDepthTarget, m_Material, 9); + Graphics.SetRenderTarget(dest); + Shader.SetGlobalTexture("_DS_RadianceBuffer", m_CurrentRadianceTarget); + RenderTexture.ReleaseTemporary(m_PerFrameRadianceTarget); + } + else + { + Shader.SetGlobalTexture("_DS_RadianceBuffer", m_PerFrameRadianceTarget); + } + if (renderTexture != null) + { + RenderTexture.ReleaseTemporary(renderTexture); + } + if (renderTexture2 != null) + { + RenderTexture.ReleaseTemporary(renderTexture2); + } + } + + private void OnPostRender() + { + if (WillRenderWithTemporalReprojection) + { + RenderTexture currentRadianceTarget = m_CurrentRadianceTarget; + m_CurrentRadianceTarget = m_PreviousRadianceTarget; + m_PreviousRadianceTarget = currentRadianceTarget; + Matrix4x4 worldToCameraMatrix = m_Camera.worldToCameraMatrix; + Matrix4x4 gPUProjectionMatrix = GL.GetGPUProjectionMatrix(m_Camera.projectionMatrix, renderIntoTexture: true); + m_PreviousViewProjMatrix = gPUProjectionMatrix * worldToCameraMatrix; + m_PreviousInvViewProjMatrix = m_PreviousViewProjMatrix.inverse; + } + else + { + RenderTexture.ReleaseTemporary(m_PerFrameRadianceTarget); + } + if (m_LightVolumeCmdBuffers.Count > 0) + { + foreach (KeyValuePair<Light, CommandBuffer> lightVolumeCmdBuffer in m_LightVolumeCmdBuffers) + { + lightVolumeCmdBuffer.Value.Clear(); + } + m_LightVolumeCmdBuffers.Clear(); + } + if ((bool)m_DirectLight) + { + m_DirectionalLightCmdBuffer.Clear(); + } + m_RenderNonShadowVolumes.Clear(); + m_PerFrameLightVolumes.Clear(); + m_PerFrameShadowLightVolumes.Clear(); + } +} diff --git a/DeepSky.Haze/DS_HazeZone.cs b/DeepSky.Haze/DS_HazeZone.cs new file mode 100644 index 0000000..b4ffabb --- /dev/null +++ b/DeepSky.Haze/DS_HazeZone.cs @@ -0,0 +1,105 @@ +using UnityEngine; + +namespace DeepSky.Haze; + +[ExecuteInEditMode] +[AddComponentMenu("DeepSky Haze/Zone", 52)] +public class DS_HazeZone : MonoBehaviour +{ + [SerializeField] + private DS_HazeContext m_Context = new DS_HazeContext(); + + [SerializeField] + [Range(0f, 250f)] + private int m_Priority; + + [SerializeField] + [Range(0.001f, 1f)] + private float m_BlendRange = 0.1f; + + private Bounds m_AABB; + + private float m_BlendRangeInverse; + + public DS_HazeContext Context => m_Context; + + public int Priority + { + get + { + return m_Priority; + } + set + { + m_Priority = ((value > 0) ? value : 0); + } + } + + public float BlendRange + { + get + { + return m_BlendRange; + } + set + { + m_BlendRange = Mathf.Clamp01(value); + } + } + + private void Setup() + { + m_AABB = new Bounds(Vector3.zero, base.transform.localScale); + m_BlendRangeInverse = 1f / Mathf.Max(Mathf.Min(m_AABB.extents.x, m_AABB.extents.y, m_AABB.extents.z) * m_BlendRange, Mathf.Epsilon); + } + + private void Start() + { + Setup(); + } + + private void OnValidate() + { + Setup(); + } + + public bool Contains(Vector3 position) + { + if (base.transform.hasChanged) + { + Setup(); + } + Vector3 point = base.transform.InverseTransformPoint(position); + point.Scale(base.transform.localScale); + return m_AABB.Contains(point); + } + + public float GetBlendWeight(Vector3 position) + { + Vector3 vector = base.transform.InverseTransformPoint(position); + vector.Scale(base.transform.localScale); + float num = Mathf.Abs(m_AABB.extents.x - Mathf.Abs(vector.x)); + float num2 = Mathf.Abs(m_AABB.extents.y - Mathf.Abs(vector.y)); + float num3 = Mathf.Abs(m_AABB.extents.z - Mathf.Abs(vector.z)); + float num4 = Mathf.Min(num, num2, num3); + return Mathf.Clamp01(num4 * m_BlendRangeInverse); + } + + public static bool operator >(DS_HazeZone c1, DS_HazeZone c2) + { + if (c1.m_Priority == c2.m_Priority) + { + return (Vector3.Dot(c1.m_AABB.extents, c1.m_AABB.extents) > Vector3.Dot(c2.m_AABB.extents, c2.m_AABB.extents)) ? true : false; + } + return (c1.m_Priority > c2.m_Priority) ? true : false; + } + + public static bool operator <(DS_HazeZone c1, DS_HazeZone c2) + { + if (c1.m_Priority == c2.m_Priority) + { + return (Vector3.Dot(c1.m_AABB.extents, c1.m_AABB.extents) < Vector3.Dot(c2.m_AABB.extents, c2.m_AABB.extents)) ? true : false; + } + return (c1.m_Priority < c2.m_Priority) ? true : false; + } +} diff --git a/DeepSky.Haze/DS_LightFalloff.cs b/DeepSky.Haze/DS_LightFalloff.cs new file mode 100644 index 0000000..7aeca76 --- /dev/null +++ b/DeepSky.Haze/DS_LightFalloff.cs @@ -0,0 +1,7 @@ +namespace DeepSky.Haze; + +public enum DS_LightFalloff +{ + Unity, + Quadratic +} diff --git a/DeepSky.Haze/DS_SamplingQuality.cs b/DeepSky.Haze/DS_SamplingQuality.cs new file mode 100644 index 0000000..5ac91e5 --- /dev/null +++ b/DeepSky.Haze/DS_SamplingQuality.cs @@ -0,0 +1,9 @@ +namespace DeepSky.Haze; + +public enum DS_SamplingQuality +{ + x4, + x8, + x16, + x32 +} diff --git a/DoggoMovement.cs b/DoggoMovement.cs new file mode 100644 index 0000000..ea7519b --- /dev/null +++ b/DoggoMovement.cs @@ -0,0 +1,43 @@ +using UnityEngine; + +public class DoggoMovement : MonoBehaviour +{ + public float drag = 0.1f; + + private CollisionChecker[] checkers; + + private Rigidbody rig; + + private Rigidbody[] rigs; + + private MovementHandler move; + + private void Start() + { + move = base.transform.root.GetComponent<MovementHandler>(); + rigs = base.transform.root.GetComponentsInChildren<Rigidbody>(); + checkers = base.transform.root.GetComponentsInChildren<CollisionChecker>(); + rig = GetComponent<Rigidbody>(); + } + + private void FixedUpdate() + { + float num = 1f; + num = 0f; + for (int i = 0; i < checkers.Length; i++) + { + if (checkers[i].sinceGrounded < 0.3f) + { + num += 1f / (float)checkers.Length; + } + } + move.multiplier = num; + Rigidbody[] array = rigs; + foreach (Rigidbody rigidbody in array) + { + rigidbody.velocity *= 1f - drag * num; + rigidbody.angularVelocity *= 1f - drag * num; + } + rig.AddTorque(Vector3.Angle(base.transform.up, Vector3.up) * Vector3.Cross(base.transform.up, Vector3.up) * 50f * num, ForceMode.Acceleration); + } +} diff --git a/DragHandler.cs b/DragHandler.cs new file mode 100644 index 0000000..adb8df4 --- /dev/null +++ b/DragHandler.cs @@ -0,0 +1,25 @@ +using UnityEngine; + +public class DragHandler : MonoBehaviour +{ + private float drag; + + private float angularDrag; + + private Rigidbody rig; + + public float dragAmount = 1f; + + private void Start() + { + rig = GetComponent<Rigidbody>(); + drag = rig.drag; + angularDrag = rig.angularDrag; + } + + private void Update() + { + rig.drag = drag * dragAmount; + rig.angularDrag = angularDrag * dragAmount; + } +} diff --git a/EnemyAI.cs b/EnemyAI.cs new file mode 100644 index 0000000..7337bbe --- /dev/null +++ b/EnemyAI.cs @@ -0,0 +1,103 @@ +using UnityEngine; + +public class EnemyAI : MonoBehaviour +{ + private InputHandler input; + + public Transform target; + + public Transform rotationTarget; + + private Transform hip; + + public Vector3 randomOffset; + + private PlayerDeath death; + + private PlayerDeath ownDeath; + + private float counter; + + private float counter2 = 1f; + + private float deadCounter; + + private bool hasDespawned; + + private void Start() + { + input = GetComponent<InputHandler>(); + hip = GetComponentInChildren<Hip>().transform; + death = target.root.GetComponent<PlayerDeath>(); + ownDeath = GetComponent<PlayerDeath>(); + } + + private void Update() + { + if (ownDeath.dead) + { + deadCounter += Time.deltaTime; + if (deadCounter > 5f && !hasDespawned) + { + Despawn(); + } + if (deadCounter > 8f) + { + Object.Destroy(base.gameObject); + } + } + else + { + Logic(); + } + } + + public bool IsDead() + { + return ownDeath.dead; + } + + private void Despawn() + { + hasDespawned = true; + Rigidbody[] componentsInChildren = GetComponentsInChildren<Rigidbody>(); + Collider[] componentsInChildren2 = GetComponentsInChildren<Collider>(); + MonoBehaviour[] componentsInChildren3 = GetComponentsInChildren<MonoBehaviour>(); + for (int i = 0; i < componentsInChildren.Length; i++) + { + componentsInChildren[i].drag = 5f; + componentsInChildren[i].angularDrag = 5f; + } + for (int j = 0; j < componentsInChildren2.Length; j++) + { + componentsInChildren2[j].enabled = false; + } + for (int k = 0; k < componentsInChildren3.Length; k++) + { + if (componentsInChildren3[k].GetType() != GetType()) + { + componentsInChildren3[k].enabled = false; + } + } + } + + private void Logic() + { + counter2 -= Time.deltaTime; + if (counter2 < 0f) + { + counter2 = Random.Range(1f, 4f); + randomOffset = new Vector3(Random.Range(-1f, 1f), 0f, Random.Range(-1f, 1f)); + } + float num = Vector3.Distance(target.position, hip.position); + input.inputMovementDirection = (target.position + randomOffset * num * 0.7f - hip.position).normalized; + rotationTarget.rotation = Quaternion.LookRotation(input.inputMovementDirection); + input.isSpringting = true; + counter += Time.deltaTime; + if (num < 0.7f && counter > 0.3f) + { + death.TakeDamage(15f * (target.position - hip.position).normalized, Vector3.zero); + counter = 0f; + } + } +} diff --git a/EnemyGroup.cs b/EnemyGroup.cs new file mode 100644 index 0000000..7afbffe --- /dev/null +++ b/EnemyGroup.cs @@ -0,0 +1,15 @@ +using System; + +[Serializable] +public class EnemyGroup +{ + public enum EnemyType + { + DefaultEnemy, + Fast + } + + public EnemyType enemyType; + + public float number = 5f; +} diff --git a/EnemyWave.cs b/EnemyWave.cs new file mode 100644 index 0000000..fff6d4a --- /dev/null +++ b/EnemyWave.cs @@ -0,0 +1,8 @@ +using System; +using System.Collections.Generic; + +[Serializable] +public class EnemyWave +{ + public List<EnemyGroup> groups = new List<EnemyGroup>(); +} diff --git a/EnvMapAnimator.cs b/EnvMapAnimator.cs new file mode 100644 index 0000000..3d19693 --- /dev/null +++ b/EnvMapAnimator.cs @@ -0,0 +1,29 @@ +using System.Collections; +using TMPro; +using UnityEngine; + +public class EnvMapAnimator : MonoBehaviour +{ + public Vector3 RotationSpeeds; + + private TMP_Text m_textMeshPro; + + private Material m_material; + + private void Awake() + { + m_textMeshPro = GetComponent<TMP_Text>(); + m_material = m_textMeshPro.fontSharedMaterial; + } + + private IEnumerator Start() + { + Matrix4x4 matrix = default(Matrix4x4); + while (true) + { + matrix.SetTRS(Vector3.zero, Quaternion.Euler(Time.time * RotationSpeeds.x, Time.time * RotationSpeeds.y, Time.time * RotationSpeeds.z), Vector3.one); + m_material.SetMatrix("_EnvMatrix", matrix); + yield return null; + } + } +} diff --git a/ExampleWheelController.cs b/ExampleWheelController.cs new file mode 100644 index 0000000..a2f05e0 --- /dev/null +++ b/ExampleWheelController.cs @@ -0,0 +1,38 @@ +using UnityEngine; + +public class ExampleWheelController : MonoBehaviour +{ + private static class Uniforms + { + internal static readonly int _MotionAmount = Shader.PropertyToID("_MotionAmount"); + } + + public float acceleration; + + public Renderer motionVectorRenderer; + + private Rigidbody m_Rigidbody; + + private void Start() + { + m_Rigidbody = GetComponent<Rigidbody>(); + m_Rigidbody.maxAngularVelocity = 100f; + } + + private void Update() + { + if (Input.GetKey(KeyCode.UpArrow)) + { + m_Rigidbody.AddRelativeTorque(new Vector3(-1f * acceleration, 0f, 0f), ForceMode.Acceleration); + } + else if (Input.GetKey(KeyCode.DownArrow)) + { + m_Rigidbody.AddRelativeTorque(new Vector3(1f * acceleration, 0f, 0f), ForceMode.Acceleration); + } + float value = (0f - m_Rigidbody.angularVelocity.x) / 100f; + if ((bool)motionVectorRenderer) + { + motionVectorRenderer.material.SetFloat(Uniforms._MotionAmount, Mathf.Clamp(value, -0.25f, 0.25f)); + } + } +} diff --git a/FPSCarCam.cs b/FPSCarCam.cs new file mode 100644 index 0000000..3905c84 --- /dev/null +++ b/FPSCarCam.cs @@ -0,0 +1,42 @@ +using UnityEngine; + +public class FPSCarCam : MonoBehaviour +{ + public Rigidbody rig; + + public float movementAmount = 1f; + + public float returnAmount = 1f; + + public float friction = 0.9f; + + private Vector3 cameraVelocity; + + private Vector3 lastRigVelocity; + + private Vector3 startPos; + + private WobbleShake shake; + + private void Start() + { + startPos = base.transform.localPosition; + shake = base.transform.root.GetComponentInChildren<WobbleShake>(); + } + + private void Update() + { + Vector3 vector = rig.velocity - lastRigVelocity; + cameraVelocity -= vector; + cameraVelocity -= cameraVelocity * Time.deltaTime * friction; + Vector3 vector2 = base.transform.parent.TransformPoint(startPos) - base.transform.position; + cameraVelocity += vector2.normalized * Mathf.Pow(vector2.magnitude, 2f) * Time.deltaTime * returnAmount; + base.transform.position += cameraVelocity * Time.deltaTime * movementAmount; + base.transform.rotation = Quaternion.Lerp(base.transform.rotation, rig.rotation, 10f * Time.deltaTime); + lastRigVelocity = rig.velocity; + } + + private void FixedUpdate() + { + } +} diff --git a/FPSmeter.cs b/FPSmeter.cs new file mode 100644 index 0000000..f762fe7 --- /dev/null +++ b/FPSmeter.cs @@ -0,0 +1,40 @@ +using UnityEngine; + +public class FPSmeter : MonoBehaviour +{ + public float updateInterval = 0.5f; + + private float lastInterval; + + private int frames; + + public static float fps; + + public bool showFPS; + + private void Start() + { + lastInterval = Time.realtimeSinceStartup; + frames = 0; + } + + private void OnGUI() + { + if (showFPS) + { + GUI.Label(new Rect(10f, 10f, 100f, 20f), string.Empty + Mathf.Round(fps * 100f) / 100f); + } + } + + private void Update() + { + frames++; + float realtimeSinceStartup = Time.realtimeSinceStartup; + if (realtimeSinceStartup > lastInterval + updateInterval) + { + fps = (float)frames / (realtimeSinceStartup - lastInterval); + frames = 0; + lastInterval = realtimeSinceStartup; + } + } +} diff --git a/FollowRotation.cs b/FollowRotation.cs new file mode 100644 index 0000000..514281a --- /dev/null +++ b/FollowRotation.cs @@ -0,0 +1,15 @@ +using UnityEngine; + +public class FollowRotation : MonoBehaviour +{ + public Transform target; + + private void Start() + { + } + + private void LateUpdate() + { + base.transform.rotation = target.rotation; + } +} diff --git a/FollowTransform.cs b/FollowTransform.cs new file mode 100644 index 0000000..83a7f2d --- /dev/null +++ b/FollowTransform.cs @@ -0,0 +1,17 @@ +using UnityEngine; + +public class FollowTransform : MonoBehaviour +{ + public Transform target; + + public Vector3 offset; + + private void Start() + { + } + + private void LateUpdate() + { + base.transform.position = target.position + offset; + } +} diff --git a/FollowTransformVelocity.cs b/FollowTransformVelocity.cs new file mode 100644 index 0000000..584846c --- /dev/null +++ b/FollowTransformVelocity.cs @@ -0,0 +1,16 @@ +using UnityEngine; + +public class FollowTransformVelocity : MonoBehaviour +{ + public TransformVelocity transformVelocty; + + private void Start() + { + } + + private void FixedUpdate() + { + base.transform.position = transformVelocty.transform.position + transformVelocty.velocity * 5f; + base.transform.rotation = transformVelocty.transform.rotation; + } +} diff --git a/FootHandler.cs b/FootHandler.cs new file mode 100644 index 0000000..7343e21 --- /dev/null +++ b/FootHandler.cs @@ -0,0 +1,75 @@ +using UnityEngine; + +public class FootHandler : MonoBehaviour +{ + private AnimationHandler animHandler; + + private Collider collider; + + public PhysicMaterial slippery; + + private PhysicMaterial footMaterial; + + private Transform torso; + + private MovementDataHandler moveData; + + private Rigidbody rig; + + private RotationHandler rot; + + private Vector3 rotationDif; + + private AnimationObject anim; + + private StepHandler handler; + + private void Start() + { + animHandler = base.transform.root.GetComponent<AnimationHandler>(); + moveData = base.transform.root.GetComponent<MovementDataHandler>(); + collider = GetComponentInChildren<Collider>(); + rig = GetComponent<Rigidbody>(); + footMaterial = collider.material; + torso = base.transform.root.GetComponentInChildren<Torso>().transform; + rot = base.transform.root.GetComponent<RotationHandler>(); + handler = base.transform.root.GetComponent<StepHandler>(); + anim = GetComponentInChildren<AnimationObject>(); + } + + private void Update() + { + float num = Mathf.Abs(torso.position.x - base.transform.position.x) + Mathf.Abs(torso.position.z - base.transform.position.z); + if (rot.hipCorrectionAmount > 30f || ((bool)anim && anim.isLeft != handler.isLeft)) + { + SetFoot(active: false); + } + else if (animHandler.animationState == 0) + { + if (num > 0.1f || rotationDif.magnitude > 15f) + { + SetFoot(active: false); + } + else + { + SetFoot(active: true); + } + } + else + { + SetFoot(active: true); + } + } + + private void FixedUpdate() + { + } + + private void SetFoot(bool active) + { + if (active) + { + collider.material = footMaterial; + } + } +} diff --git a/FootLeft.cs b/FootLeft.cs new file mode 100644 index 0000000..da0d11f --- /dev/null +++ b/FootLeft.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class FootLeft : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/FootRenderer.cs b/FootRenderer.cs new file mode 100644 index 0000000..a5dc15e --- /dev/null +++ b/FootRenderer.cs @@ -0,0 +1,26 @@ +using UnityEngine; + +public class FootRenderer : MonoBehaviour +{ + private CollisionChecker collisionChecker; + + private MovementDataHandler movementData; + + private void Start() + { + collisionChecker = GetComponentInParent<CollisionChecker>(); + movementData = base.transform.root.GetComponent<MovementDataHandler>(); + } + + private void Update() + { + if (collisionChecker.sinceGrounded < 0.1f) + { + base.transform.rotation = Quaternion.LookRotation(movementData.groundedForward); + } + else + { + base.transform.rotation = Quaternion.identity; + } + } +} diff --git a/FootRight.cs b/FootRight.cs new file mode 100644 index 0000000..c5014db --- /dev/null +++ b/FootRight.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class FootRight : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/ForceLerp.cs b/ForceLerp.cs new file mode 100644 index 0000000..1d5a5b4 --- /dev/null +++ b/ForceLerp.cs @@ -0,0 +1,59 @@ +using UnityEngine; + +public class ForceLerp : MonoBehaviour +{ + public Rigidbody rig; + + public float predictionAmount; + + public Transform target; + + public float movementMultiplier = 1f; + + public float friction = 0.97f; + + private Vector3 velocity; + + public float inputVelocityAmount; + + public float inputFriction; + + private GenericInputHandler input; + + private float inputVelocity; + + private CollisionChecker[] checkers; + + private void Start() + { + input = GetComponentInParent<GenericInputHandler>(); + checkers = base.transform.root.GetComponentsInChildren<CollisionChecker>(); + } + + private void FixedUpdate() + { + } + + private void LateUpdate() + { + float num = Mathf.Clamp(Time.smoothDeltaTime, 0f, 0.1f); + float num2 = 1f; + if (checkers.Length > 0) + { + num2 = 0f; + for (int i = 0; i < checkers.Length; i++) + { + if (checkers[i].sinceGrounded < 0.2f) + { + num2 += 1f / (float)checkers.Length; + } + } + } + inputVelocity += rig.angularVelocity.y * 0.5f * num2 * num - num * inputVelocity * inputFriction; + Vector3 vector = target.position - base.transform.position + rig.transform.right * inputVelocity * inputVelocityAmount + rig.velocity * predictionAmount; + Vector3 vector2 = velocity * friction; + velocity += (vector - vector2) * num; + base.transform.position += velocity * movementMultiplier * num; + base.transform.rotation = Quaternion.Lerp(base.transform.rotation, Quaternion.LookRotation(target.forward), num * 4f); + } +} diff --git a/ForcePosition.cs b/ForcePosition.cs new file mode 100644 index 0000000..ed6dcc3 --- /dev/null +++ b/ForcePosition.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class ForcePosition : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/GameMode.cs b/GameMode.cs new file mode 100644 index 0000000..2d717aa --- /dev/null +++ b/GameMode.cs @@ -0,0 +1,124 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +public class GameMode : MonoBehaviour +{ + public List<EnemyWave> wavesToSpawn = new List<EnemyWave>(); + + public static GameMode instance; + + private int currentWave; + + public List<EnemyAI> enemies = new List<EnemyAI>(); + + public Transform spawnPointParent; + + private List<Transform> spawnPoints = new List<Transform>(); + + public LayerMask mask; + + public GameObject enemy_Default; + + public GameObject enemy_Fast; + + private IEnumerator Start() + { + Screen.fullScreen = false; + Screen.SetResolution(1800, 1000, false); + + Cursor.visible = false; + Cursor.lockState = CursorLockMode.Locked; + + Init(); + while (true) + { + yield return new WaitForSeconds(3f); + //SpawnWave(); + yield return WaitForWaveToEnd(); + } + } + + private IEnumerator WaitForWaveToEnd() + { + while (enemies.Count > 0) + { + yield return null; + } + } + + private void Update() + { + for (int num = enemies.Count - 1; num >= 0; num--) + { + if (enemies[num] == null) + { + enemies.RemoveAt(num); + } + else if (enemies[num].IsDead()) + { + enemies.RemoveAt(num); + } + } + } + + private void Init() + { + mask = LayerMask.GetMask("Map"); + for (int i = 0; i < spawnPointParent.childCount; i++) + { + spawnPoints.Add(spawnPointParent.GetChild(i)); + } + } + + private void SpawnWave() + { + for (int i = 0; i < wavesToSpawn[currentWave].groups.Count; i++) + { + for (int j = 0; (float)j < wavesToSpawn[currentWave].groups[i].number; j++) + { + SpawnEnemy(wavesToSpawn[currentWave].groups[i].enemyType); + } + } + currentWave++; + if (currentWave >= wavesToSpawn.Count) + { + currentWave = wavesToSpawn.Count - 1; + } + } + + private void SpawnEnemy(EnemyGroup.EnemyType enemyType) + { + GameObject gameObject = Object.Instantiate(GetEnemyFromType(enemyType), GetSpawnPos(), Quaternion.identity); + gameObject.GetComponent<EnemyAI>().target = Player.localPlayer.torso; + enemies.Add(gameObject.GetComponent<EnemyAI>()); + } + + private Vector3 GetSpawnPos() + { + bool flag = false; + int num = 100000; + while (true && num > 0) + { + num--; + Vector3 vector = spawnPoints[Random.Range(0, spawnPoints.Count)].position + Vector3.up * 0.3f; + RaycastHit hitInfo = default(RaycastHit); + Ray ray = new Ray(vector, vector - Player.localPlayer.transform.position); + Physics.Raycast(ray, out hitInfo, Vector3.Distance(vector, Player.localPlayer.transform.position), mask); + if (hitInfo.collider == null) + { + return vector; + } + } + return spawnPoints[Random.Range(0, spawnPoints.Count)].position + Vector3.up * 0.3f; + } + + private GameObject GetEnemyFromType(EnemyGroup.EnemyType enemyType) + { + if (enemyType == EnemyGroup.EnemyType.Fast) + { + return enemy_Fast; + } + return enemy_Default; + } +} diff --git a/GenericForceMovement.cs b/GenericForceMovement.cs new file mode 100644 index 0000000..4c8160f --- /dev/null +++ b/GenericForceMovement.cs @@ -0,0 +1,40 @@ +using UnityEngine; + +public class GenericForceMovement : MonoBehaviour +{ + public Vector3 movementDirection; + + public float forceMultiplier = 1f; + + public MovementRig[] rigs; + + public bool useGroundedMultiplier; + + private CollisionChecker[] checkers; + + private void Start() + { + checkers = GetComponentsInChildren<CollisionChecker>(); + } + + private void FixedUpdate() + { + float num = 1f; + if (useGroundedMultiplier) + { + num = 0f; + for (int i = 0; i < checkers.Length; i++) + { + if (checkers[i].sinceGrounded < 0.1f) + { + num += 1f / (float)checkers.Length; + } + } + } + MovementRig[] array = rigs; + foreach (MovementRig movementRig in array) + { + movementRig.rig.AddForce(movementDirection * num * forceMultiplier * movementRig.multiplier, ForceMode.Acceleration); + } + } +} diff --git a/GenericInputHandler.cs b/GenericInputHandler.cs new file mode 100644 index 0000000..deeed7e --- /dev/null +++ b/GenericInputHandler.cs @@ -0,0 +1,40 @@ +using UnityEngine; + +public class GenericInputHandler : MonoBehaviour +{ + public Vector3 inputDirection; + + public bool normalized; + + public bool space; + + private void Start() + { + } + + private void Update() + { + space = Input.GetKey(KeyCode.Space); + inputDirection = Vector3.zero; + if (Input.GetKey(KeyCode.W)) + { + inputDirection += Vector3.forward; + } + if (Input.GetKey(KeyCode.S)) + { + inputDirection += Vector3.back; + } + if (Input.GetKey(KeyCode.D)) + { + inputDirection += Vector3.right; + } + if (Input.GetKey(KeyCode.A)) + { + inputDirection += Vector3.left; + } + if (normalized) + { + inputDirection = inputDirection.normalized; + } + } +} diff --git a/GeometryVsTerrainBlend.cs b/GeometryVsTerrainBlend.cs new file mode 100644 index 0000000..20ab882 --- /dev/null +++ b/GeometryVsTerrainBlend.cs @@ -0,0 +1,215 @@ +using UnityEngine; + +[AddComponentMenu("Relief Terrain/Geometry Blend")] +[SelectionBase] +[RequireComponent(typeof(MeshFilter))] +public class GeometryVsTerrainBlend : MonoBehaviour +{ + public double UpdTim; + + private int progress_count_max; + + private int progress_count_current; + + private const int progress_granulation = 1000; + + private string progress_description = string.Empty; + + public float blend_distance = 0.1f; + + public GameObject blendedObject; + + public bool VoxelBlendedObject; + + public float _DeferredBlendGloss = 0.8f; + + [HideInInspector] + public bool undo_flag; + + [HideInInspector] + public bool paint_flag; + + [HideInInspector] + public int paint_mode; + + [HideInInspector] + public float paint_size = 0.5f; + + [HideInInspector] + public float paint_smoothness; + + [HideInInspector] + public float paint_opacity = 1f; + + [HideInInspector] + public RTPColorChannels vertex_paint_channel = RTPColorChannels.A; + + [HideInInspector] + public int addTrisSubdivision; + + [HideInInspector] + public float addTrisMinAngle; + + [HideInInspector] + public float addTrisMaxAngle = 90f; + + private Vector3[] paint_vertices; + + private Vector3[] paint_normals; + + private int[] paint_tris; + + private Transform underlying_transform; + + private MeshRenderer underlying_renderer; + + [HideInInspector] + public RaycastHit paintHitInfo; + + [HideInInspector] + public bool paintHitInfo_flag; + + [HideInInspector] + private Texture2D tmp_globalColorMap; + + [HideInInspector] + public Vector3[] normals_orig; + + [HideInInspector] + public Vector4[] tangents_orig; + + [HideInInspector] + public bool baked_normals; + + [HideInInspector] + public Mesh orig_mesh; + + [HideInInspector] + public Mesh pmesh; + + [HideInInspector] + public bool shader_global_blend_capabilities; + + [HideInInspector] + public float StickOffset = 0.03f; + + [HideInInspector] + public bool Sticked; + + [HideInInspector] + public bool StickedOptimized = true; + + [HideInInspector] + public bool ModifyTris; + + [HideInInspector] + public bool BuildMeshFlag; + + [HideInInspector] + public bool RealizePaint_Flag; + + [HideInInspector] + public string save_path = string.Empty; + + [HideInInspector] + public bool isBatched; + + private Renderer _renderer; + + private void Start() + { + SetupValues(); + } + + private void GetRenderer() + { + if (!_renderer) + { + _renderer = GetComponent<Renderer>(); + } + } + + public void SetupValues() + { + if (!blendedObject || (!(blendedObject.GetComponent(typeof(MeshRenderer)) != null) && !(blendedObject.GetComponent(typeof(Terrain)) != null))) + { + return; + } + if (underlying_transform == null) + { + underlying_transform = base.transform.Find("RTP_blend_underlying"); + } + if (underlying_transform != null) + { + GameObject gameObject = underlying_transform.gameObject; + underlying_renderer = (MeshRenderer)gameObject.GetComponent(typeof(MeshRenderer)); + } + if (!(underlying_renderer != null) || !(underlying_renderer.sharedMaterial != null)) + { + return; + } + ReliefTerrain reliefTerrain = (ReliefTerrain)blendedObject.GetComponent(typeof(ReliefTerrain)); + if ((bool)reliefTerrain) + { + Material sharedMaterial = underlying_renderer.sharedMaterial; + reliefTerrain.RefreshTextures(sharedMaterial); + reliefTerrain.globalSettingsHolder.Refresh(sharedMaterial); + if (sharedMaterial.HasProperty("RTP_DeferredAddPassSpec")) + { + sharedMaterial.SetFloat("RTP_DeferredAddPassSpec", _DeferredBlendGloss); + } + if ((bool)reliefTerrain.controlA) + { + sharedMaterial.SetTexture("_Control", reliefTerrain.controlA); + } + if ((bool)reliefTerrain.ColorGlobal) + { + sharedMaterial.SetTexture("_Splat0", reliefTerrain.ColorGlobal); + } + if ((bool)reliefTerrain.NormalGlobal) + { + sharedMaterial.SetTexture("_Splat1", reliefTerrain.NormalGlobal); + } + if ((bool)reliefTerrain.TreesGlobal) + { + sharedMaterial.SetTexture("_Splat2", reliefTerrain.TreesGlobal); + } + if ((bool)reliefTerrain.BumpGlobalCombined) + { + sharedMaterial.SetTexture("_Splat3", reliefTerrain.BumpGlobalCombined); + } + } + Terrain terrain = (Terrain)blendedObject.GetComponent(typeof(Terrain)); + if ((bool)terrain) + { + underlying_renderer.lightmapIndex = terrain.lightmapIndex; + underlying_renderer.lightmapScaleOffset = terrain.lightmapScaleOffset; + underlying_renderer.realtimeLightmapIndex = terrain.realtimeLightmapIndex; + underlying_renderer.realtimeLightmapScaleOffset = terrain.realtimeLightmapScaleOffset; + } + else + { + underlying_renderer.lightmapIndex = blendedObject.GetComponent<Renderer>().lightmapIndex; + underlying_renderer.lightmapScaleOffset = blendedObject.GetComponent<Renderer>().lightmapScaleOffset; + underlying_renderer.realtimeLightmapIndex = blendedObject.GetComponent<Renderer>().realtimeLightmapIndex; + underlying_renderer.realtimeLightmapScaleOffset = blendedObject.GetComponent<Renderer>().realtimeLightmapScaleOffset; + } + if (Sticked) + { + if ((bool)terrain) + { + GetComponent<Renderer>().lightmapIndex = terrain.lightmapIndex; + GetComponent<Renderer>().lightmapScaleOffset = terrain.lightmapScaleOffset; + GetComponent<Renderer>().realtimeLightmapIndex = terrain.realtimeLightmapIndex; + GetComponent<Renderer>().realtimeLightmapScaleOffset = terrain.realtimeLightmapScaleOffset; + } + else + { + GetComponent<Renderer>().lightmapIndex = blendedObject.GetComponent<Renderer>().lightmapIndex; + GetComponent<Renderer>().lightmapScaleOffset = blendedObject.GetComponent<Renderer>().lightmapScaleOffset; + GetComponent<Renderer>().realtimeLightmapIndex = blendedObject.GetComponent<Renderer>().realtimeLightmapIndex; + GetComponent<Renderer>().realtimeLightmapScaleOffset = blendedObject.GetComponent<Renderer>().realtimeLightmapScaleOffset; + } + } + } +} diff --git a/Gravity.cs b/Gravity.cs new file mode 100644 index 0000000..f646f0c --- /dev/null +++ b/Gravity.cs @@ -0,0 +1,47 @@ +using UnityEngine; + +public class Gravity : MonoBehaviour +{ + public float baseGravity; + + public float scalingGravity; + + private RigidbodyHolder allRigs; + + private StandingDataHandler standingData; + + private Holding holding; + + private PlayerDeath death; + + private void Start() + { + death = GetComponent<PlayerDeath>(); + allRigs = GetComponent<RigidbodyHolder>(); + standingData = GetComponent<StandingDataHandler>(); + holding = GetComponent<Holding>(); + } + + private void FixedUpdate() + { + if (death.dead) + { + return; + } + for (int i = 0; i < allRigs.GetAllRigs().Length; i++) + { + allRigs.GetAllRigs()[i].AddForce(Vector3.down * baseGravity + Vector3.down * scalingGravity * standingData.sinceGrounded, ForceMode.Acceleration); + } + if ((bool)holding) + { + if ((bool)holding.heldObject) + { + holding.heldObject.rig.AddForce(Vector3.down * baseGravity + Vector3.down * scalingGravity * standingData.sinceGrounded, ForceMode.Acceleration); + } + if ((bool)holding.heldObjectOffHand) + { + holding.heldObjectOffHand.rig.AddForce(Vector3.down * baseGravity + Vector3.down * scalingGravity * standingData.sinceGrounded, ForceMode.Acceleration); + } + } + } +} @@ -0,0 +1,94 @@ +using UnityEngine; + +public class Gun : MonoBehaviour +{ + public GameObject projectile; + + public float rateOfFire = 0.1f; + + public bool auto = true; + + public int bulletsInMag = 30; + + public float reloadTime = 0.5f; + + public float ADSFOV = 60f; + + [HideInInspector] + public Rigidbody rig; + + private Transform shootPosition; + + private Recoil recoil; + + private AddScreenShake shake; + + private float counter; + + public float extraSpread; + + public float addForceToAllSpawnedRigs; + + private ParticleSystem part; + + private GunSFX sfx; + + private void Start() + { + rig = GetComponent<Rigidbody>(); + sfx = GetComponent<GunSFX>(); + recoil = GetComponent<Recoil>(); + shake = GetComponent<AddScreenShake>(); + shootPosition = GetComponentInChildren<ShootPosition>().transform; + part = GetComponentInChildren<ParticleSystem>(); + } + + private void Update() + { + counter += Time.deltaTime; + } + + public void Shoot(Transform shooter, bool ADS) + { + if (counter < rateOfFire) + { + return; + } + counter = 0f; + if ((bool)part) + { + part.Play(); + } + GameObject gameObject = Object.Instantiate(projectile, shootPosition.position, shootPosition.rotation); + RandomizeRotation component = gameObject.GetComponent<RandomizeRotation>(); + if ((bool)component) + { + component.spread += extraSpread; + } + SpawnerHolder component2 = gameObject.GetComponent<SpawnerHolder>(); + if ((bool)component2) + { + component2.spawner = shooter; + } + if ((bool)recoil) + { + recoil.AddRecoil(ADS); + } + if ((bool)shake) + { + shake.DoShake(); + } + if ((bool)sfx) + { + sfx.PlayShootSound(); + } + if (addForceToAllSpawnedRigs != 0f) + { + Rigidbody[] componentsInChildren = gameObject.GetComponentsInChildren<Rigidbody>(); + foreach (Rigidbody rigidbody in componentsInChildren) + { + rigidbody.AddForce(shootPosition.forward * addForceToAllSpawnedRigs, ForceMode.VelocityChange); + } + } + } +} diff --git a/GunSFX.cs b/GunSFX.cs new file mode 100644 index 0000000..a00422c --- /dev/null +++ b/GunSFX.cs @@ -0,0 +1,23 @@ +using UnityEngine; + +public class GunSFX : MonoBehaviour +{ + public AudioClip[] shootClips; + + private AudioSource au; + + private void Start() + { + au = GetComponent<AudioSource>(); + au.mute = true; + } + + private void Update() + { + } + + public void PlayShootSound() + { + //au.PlayOneShot(shootClips[Random.Range(0, shootClips.Length)]); + } +} diff --git a/HandLeft.cs b/HandLeft.cs new file mode 100644 index 0000000..5f92108 --- /dev/null +++ b/HandLeft.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class HandLeft : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/HandRight.cs b/HandRight.cs new file mode 100644 index 0000000..cb78d06 --- /dev/null +++ b/HandRight.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class HandRight : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/HardAnimation.cs b/HardAnimation.cs new file mode 100644 index 0000000..3821be6 --- /dev/null +++ b/HardAnimation.cs @@ -0,0 +1,61 @@ +using UnityEngine; + +public class HardAnimation : MonoBehaviour +{ + public bool isLeft; + + public Vector3 targetRotationForward; + + public Vector3 targetRotationBack; + + private Vector3 currentTarget; + + private Vector3 currentTargetGoal; + + public float friction; + + public float movementAmount; + + public float delay; + + private float counter; + + private Vector3 velocity; + + private StepHandler step; + + private ConfigurableJoint joint; + + private Quaternion startRot; + + private Quaternion startRotLocal; + + private void Start() + { + joint = GetComponent<ConfigurableJoint>(); + step = base.transform.root.GetComponent<StepHandler>(); + startRot = base.transform.rotation; + startRotLocal = base.transform.localRotation; + } + + private void Update() + { + Vector3 vector = ((step.isLeft != isLeft) ? targetRotationBack : targetRotationForward); + if (currentTargetGoal != vector) + { + if (counter >= delay) + { + counter = 0f; + currentTargetGoal = vector; + } + else + { + counter += Time.deltaTime; + } + } + velocity += (currentTargetGoal - currentTarget) * Time.deltaTime; + velocity -= velocity * friction * Time.deltaTime; + currentTarget += velocity * movementAmount * Time.deltaTime; + joint.SetTargetRotationLocal(Quaternion.Euler(currentTarget), startRotLocal); + } +} diff --git a/HardAnimations.cs b/HardAnimations.cs new file mode 100644 index 0000000..b14ab1c --- /dev/null +++ b/HardAnimations.cs @@ -0,0 +1,64 @@ +using UnityEngine; + +public class HardAnimations : MonoBehaviour +{ + public bool isLeft; + + public HardPhysicsAnimation[] animations; + + private AnimationHandler animHandler; + + private Vector3 currentTarget; + + private Vector3 currentTargetGoal; + + private float counter; + + private Vector3 velocity; + + private StepHandler step; + + private ConfigurableJoint joint; + + private Quaternion startRot; + + private Quaternion startRotLocal; + + private CollisionChecker checker; + + private void Start() + { + animHandler = base.transform.root.GetComponent<AnimationHandler>(); + joint = GetComponent<ConfigurableJoint>(); + checker = GetComponent<CollisionChecker>(); + step = base.transform.root.GetComponent<StepHandler>(); + startRot = base.transform.rotation; + startRotLocal = base.transform.localRotation; + } + + private void Update() + { + Vector3 vector = ((step.isLeft != isLeft) ? animations[animHandler.animationState].targetRotationBack : animations[animHandler.animationState].targetRotationForward); + if (currentTargetGoal != vector) + { + if (counter >= animations[animHandler.animationState].delay) + { + counter = 0f; + currentTargetGoal = vector; + } + else + { + counter += Time.deltaTime; + } + } + checker.active = isLeft != step.isLeft; + velocity += (currentTargetGoal - currentTarget) * Time.deltaTime; + velocity *= animations[animHandler.animationState].friction; + currentTarget += velocity * animations[animHandler.animationState].movementAmount * Time.deltaTime; + joint.SetTargetRotationLocal(Quaternion.Euler(currentTarget), startRotLocal); + } + + private void FixedUpdate() + { + } +} diff --git a/HardPhysicsAnimation.cs b/HardPhysicsAnimation.cs new file mode 100644 index 0000000..57796ee --- /dev/null +++ b/HardPhysicsAnimation.cs @@ -0,0 +1,16 @@ +using System; +using UnityEngine; + +[Serializable] +public class HardPhysicsAnimation +{ + public Vector3 targetRotationForward; + + public Vector3 targetRotationBack; + + public float friction; + + public float movementAmount; + + public float delay; +} diff --git a/HasControl.cs b/HasControl.cs new file mode 100644 index 0000000..dde8ad6 --- /dev/null +++ b/HasControl.cs @@ -0,0 +1,28 @@ +using UnityEngine; + +public class HasControl : MonoBehaviour +{ + public bool hasControl = true; + + public GameObject[] objectsToRemove; + + private void Awake() + { + UpdateControl(); + } + + private void UpdateControl() + { + GameObject[] array = objectsToRemove; + foreach (GameObject gameObject in array) + { + gameObject.SetActive(hasControl); + } + } + + public void ChangeControl(bool control) + { + hasControl = control; + UpdateControl(); + } +} @@ -0,0 +1,12 @@ +using UnityEngine; + +public class Head : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/HeadCollisionHandler.cs b/HeadCollisionHandler.cs new file mode 100644 index 0000000..c929f0e --- /dev/null +++ b/HeadCollisionHandler.cs @@ -0,0 +1,31 @@ +using UnityEngine; + +public class HeadCollisionHandler : MonoBehaviour +{ + public float collisionValue; + + private void Start() + { + } + + private void Update() + { + collisionValue = Mathf.Lerp(collisionValue, 0f, Time.deltaTime * 6f); + } + + private void OnCollisionEnter(Collision collision) + { + if (!(collision.transform.root == base.transform.root)) + { + collisionValue += collision.relativeVelocity.magnitude * 0.5f; + } + } + + private void OnCollisionStay(Collision collision) + { + if (!(collision.transform.root == base.transform.root)) + { + collisionValue += collision.relativeVelocity.magnitude * 0.1f; + } + } +} @@ -0,0 +1,12 @@ +using UnityEngine; + +public class Hip : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/HoldableObject.cs b/HoldableObject.cs new file mode 100644 index 0000000..3bfbfc5 --- /dev/null +++ b/HoldableObject.cs @@ -0,0 +1,88 @@ +using UnityEngine; + +public class HoldableObject : MonoBehaviour +{ + public Transform holder; + + public Vector3 holdingPosition; + + public Vector3 holdingRotation; + + public Vector3 holdingUpRotation; + + [HideInInspector] + public Rigidbody rig; + + [HideInInspector] + public Transform leftHandPos; + + [HideInInspector] + public Transform rightHandPos; + + [HideInInspector] + public PID pid; + + [HideInInspector] + public Vector2 swingAngles; + + public float swingSpring; + + public Vector2 twistAngles; + + public float twistSpring; + + public bool isHeld; + + private DragHandler dragHandler; + + public LayerMask mask; + + private void Awake() + { + pid = GetComponent<PID>(); + rig = GetComponent<Rigidbody>(); + RightHandPos componentInChildren = GetComponentInChildren<RightHandPos>(); + if ((bool)componentInChildren) + { + rightHandPos = componentInChildren.transform; + } + LeftHandPos componentInChildren2 = GetComponentInChildren<LeftHandPos>(); + if ((bool)componentInChildren2) + { + leftHandPos = componentInChildren2.transform; + } + dragHandler = GetComponent<DragHandler>(); + mask = LayerMask.GetMask("Map"); + } + + private void Update() + { + if (isHeld) + { + dragHandler.dragAmount = 1f; + } + else + { + dragHandler.dragAmount = 0f; + } + } + + private void FixedUpdate() + { + if (!isHeld) + { + Hover(); + } + } + + private void Hover() + { + RaycastHit hitInfo = default(RaycastHit); + Ray ray = new Ray(base.transform.position, Vector3.down); + Physics.Raycast(ray, out hitInfo, 1.5f, mask); + Vector3 vector = new Vector3(0f, 0f, 0f); + vector.y = 1f - hitInfo.distance; + rig.velocity = Vector3.Lerp(rig.velocity, vector * 2f, Time.fixedDeltaTime * 100f); + rig.angularVelocity = Vector3.Lerp(rig.angularVelocity, Vector3.up * 5f, Time.deltaTime * 100f); + } +} diff --git a/Holding.cs b/Holding.cs new file mode 100644 index 0000000..dafc08b --- /dev/null +++ b/Holding.cs @@ -0,0 +1,288 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +public class Holding : MonoBehaviour +{ + [HideInInspector] + public HoldableObject heldObject; + + [HideInInspector] + public HoldableObject heldObjectOffHand; + + [HideInInspector] + public Transform baseTransform; + + private Rigidbody rightHand; + + private Rigidbody leftHand; + + [HideInInspector] + public ConfigurableJoint leftHandJoint; + + [HideInInspector] + public ConfigurableJoint rightHandJoint; + + public float grabForce; + + [HideInInspector] + public bool isGrabbing; + + private Transform rotaionTarget; + + private bool hasMainHandWeapon; + + private PlayerDeath death; + + public LayerMask mask = default(LayerMask); + + private Strength str; + + private float strength = 1f; + + private PID leftHandPID; + + private PID rightHandPID; + + private StandingDataHandler standingData; + + private void Awake() + { + death = GetComponent<PlayerDeath>(); + standingData = GetComponent<StandingDataHandler>(); + str = GetComponent<Strength>(); + if (!baseTransform) + { + baseTransform = GetComponentInChildren<HoldingBaseTransform>().transform; + } + rightHand = GetComponentInChildren<HandRight>().GetComponent<Rigidbody>(); + leftHand = GetComponentInChildren<HandLeft>().GetComponent<Rigidbody>(); + rotaionTarget = base.transform.GetComponentInChildren<RotationTarget>().transform; + mask = LayerMask.GetMask("Map"); + leftHandPID = leftHand.GetComponent<PID>(); + rightHandPID = rightHand.GetComponent<PID>(); + } + + private void Update() + { + if (!death.dead && (bool)heldObject) + { + strength = str.strength; + if (((bool)rightHandJoint || !heldObject.rightHandPos) && ((bool)leftHandJoint || !heldObject.leftHandPos) && (!heldObjectOffHand || (((bool)rightHandJoint || !heldObjectOffHand.rightHandPos) && ((bool)leftHandJoint || !heldObjectOffHand.leftHandPos)))) + { + isGrabbing = false; + } + } + } + + private void FixedUpdate() + { + if (death.dead || isGrabbing) + { + return; + } + if ((bool)heldObject) + { + HoldObjectInPlace(heldObject.rig, heldObject, offHand: false, rightHand); + if (!heldObjectOffHand && (bool)leftHandJoint) + { + HoldObjectInPlace(heldObject.rig, heldObject, offHand: false, leftHand, justHand: true); + } + } + if ((bool)heldObjectOffHand) + { + HoldObjectInPlace(heldObjectOffHand.rig, heldObjectOffHand, offHand: true, leftHand); + } + } + + private void HoldObjectInPlace(Rigidbody rigi, HoldableObject held, bool offHand, Rigidbody hand, bool justHand = false) + { + Vector3 holdingPosition = held.holdingPosition; + if (offHand) + { + holdingPosition.x *= -1f; + } + holdingPosition = baseTransform.TransformPoint(holdingPosition); + Vector3 holdingRotation = held.holdingRotation; + Vector3 targetRotation = baseTransform.TransformDirection(holdingRotation); + Vector3 targetRotationUp = baseTransform.TransformDirection(held.holdingUpRotation); + if (!justHand) + { + held.pid.DoPID(holdingPosition, targetRotation, targetRotationUp, strength); + } + PID pID = rightHandPID; + Vector3 localPosition = held.rightHandPos.localPosition; + if (hand == leftHand) + { + localPosition = held.leftHandPos.localPosition; + pID = leftHandPID; + } + Vector3 position = held.holdingPosition + localPosition; + if (offHand) + { + position.x *= -1f; + } + position = baseTransform.TransformPoint(position); + Debug.DrawLine(position, position + Vector3.up); + Debug.DrawLine(holdingPosition, holdingPosition + Vector3.up); + pID.DoPID(position, Vector3.zero, Vector3.zero, strength); + } + + public void StartHolding(HoldableObject holdableObject, bool hasOffHand) + { + holdableObject.isHeld = true; + isGrabbing = true; + bool offHand = false; + if (!hasMainHandWeapon) + { + hasMainHandWeapon = true; + heldObject = holdableObject; + if ((bool)heldObject.rightHandPos) + { + StartCoroutine(Grab(mainHand: true, rightHand, heldObject, offHand: false)); + } + if ((bool)heldObject.leftHandPos && !hasOffHand) + { + StartCoroutine(Grab(mainHand: false, leftHand, heldObject, offHand: false)); + } + } + else + { + offHand = true; + heldObjectOffHand = holdableObject; + heldObjectOffHand.leftHandPos = heldObjectOffHand.rightHandPos; + if ((bool)heldObjectOffHand.rightHandPos) + { + StartCoroutine(Grab(mainHand: false, leftHand, heldObjectOffHand, offHand: true)); + } + } + StartCoroutine(HoldweaponStill(holdableObject.rig, offHand, holdableObject)); + } + + private IEnumerator Grab(bool mainHand, Rigidbody hand, HoldableObject held, bool offHand) + { + while (isGrabbing) + { + if (mainHand) + { + if (!rightHandJoint) + { + ReachForPoint(rightHand, rightHand.transform.GetChild(0).position, held.rightHandPos, isLeft: false, held.rig, held, offHand); + rightHand.GetComponentInChildren<Collider>().enabled = false; + } + } + else if (!leftHandJoint) + { + ReachForPoint(leftHand, leftHand.transform.GetChild(0).position, held.leftHandPos, isLeft: true, held.rig, held, offHand); + leftHand.GetComponentInChildren<Collider>().enabled = false; + } + yield return null; + } + leftHand.GetComponentInChildren<Collider>().enabled = true; + rightHand.GetComponentInChildren<Collider>().enabled = true; + } + + private IEnumerator HoldweaponStill(Rigidbody rigToGrab, bool offHand, HoldableObject held) + { + while (isGrabbing) + { + Vector3 pos = held.holdingPosition; + if (offHand) + { + pos.x *= -1f; + } + rigToGrab.transform.position = baseTransform.TransformPoint(pos); + rigToGrab.transform.rotation = Quaternion.LookRotation(baseTransform.TransformDirection(heldObject.holdingRotation)); + yield return null; + } + } + + public void Drop() + { + List<HoldableObject> list = new List<HoldableObject>(); + if ((bool)heldObject) + { + list.Add(heldObject); + } + if ((bool)heldObjectOffHand) + { + list.Add(heldObjectOffHand); + } + for (int i = 0; i < list.Count; i++) + { + list[i].holder = null; + list[i].isHeld = false; + list[i].rig.useGravity = true; + list[i].rig.drag = 0f; + list[i].rig.angularDrag = 0f; + Collider[] componentsInChildren = list[i].GetComponentsInChildren<Collider>(); + foreach (Collider collider in componentsInChildren) + { + collider.material = null; + } + } + heldObject = null; + heldObjectOffHand = null; + if ((bool)rightHandJoint) + { + Object.Destroy(rightHandJoint); + } + if ((bool)leftHandJoint) + { + Object.Destroy(leftHandJoint); + } + hasMainHandWeapon = false; + } + + private void ReachForPoint(Rigidbody rigToReach, Vector3 forcePosition, Transform targetPositionTransform, bool isLeft, Rigidbody rigToGrab, HoldableObject held, bool offHand) + { + Vector3 normalized = (targetPositionTransform.position - forcePosition).normalized; + rigToReach.AddForceAtPosition(normalized * grabForce * Mathf.Clamp(Time.deltaTime, 0f, 0.1f), forcePosition, ForceMode.Acceleration); + if (Vector3.Distance(targetPositionTransform.position, forcePosition) < 0.5f) + { + ConnectRig(rigToReach, rigToGrab, targetPositionTransform, isLeft, held, offHand); + } + } + + private void ConnectRig(Rigidbody startRig, Rigidbody targetRig, Transform targetPositionTransform, bool isLeft, HoldableObject held, bool offHand) + { + ConfigurableJoint configurableJoint = startRig.gameObject.AddComponent<ConfigurableJoint>(); + if (offHand) + { + targetPositionTransform.localRotation = Quaternion.Euler(targetPositionTransform.localEulerAngles.x, 0f - targetPositionTransform.localEulerAngles.y, targetPositionTransform.localEulerAngles.z); + } + startRig.transform.rotation = targetPositionTransform.rotation; + startRig.transform.position += targetPositionTransform.position - startRig.transform.GetChild(0).position; + configurableJoint.connectedBody = targetRig; + configurableJoint.projectionMode = JointProjectionMode.PositionAndRotation; + configurableJoint.xMotion = ConfigurableJointMotion.Locked; + configurableJoint.yMotion = ConfigurableJointMotion.Locked; + configurableJoint.zMotion = ConfigurableJointMotion.Locked; + configurableJoint.angularXMotion = ConfigurableJointMotion.Limited; + configurableJoint.angularYMotion = ConfigurableJointMotion.Limited; + configurableJoint.angularZMotion = ConfigurableJointMotion.Limited; + SoftJointLimit highAngularXLimit = configurableJoint.highAngularXLimit; + highAngularXLimit.limit = held.swingAngles.y; + configurableJoint.highAngularXLimit = highAngularXLimit; + highAngularXLimit.limit = held.swingAngles.x; + configurableJoint.lowAngularXLimit = highAngularXLimit; + highAngularXLimit.limit = held.twistAngles.x; + configurableJoint.angularYLimit = highAngularXLimit; + highAngularXLimit.limit = held.twistAngles.y; + configurableJoint.angularZLimit = highAngularXLimit; + SoftJointLimitSpring angularXLimitSpring = configurableJoint.angularXLimitSpring; + angularXLimitSpring.spring = held.swingSpring; + configurableJoint.angularXLimitSpring = angularXLimitSpring; + angularXLimitSpring.spring = held.twistSpring; + configurableJoint.angularYZLimitSpring = angularXLimitSpring; + configurableJoint.anchor = startRig.transform.InverseTransformPoint(startRig.transform.GetChild(0).position); + if (isLeft) + { + leftHandJoint = configurableJoint; + } + else + { + rightHandJoint = configurableJoint; + } + } +} diff --git a/HoldingBaseTransform.cs b/HoldingBaseTransform.cs new file mode 100644 index 0000000..f28221b --- /dev/null +++ b/HoldingBaseTransform.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class HoldingBaseTransform : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/InfoBubble.cs b/InfoBubble.cs new file mode 100644 index 0000000..3c410c3 --- /dev/null +++ b/InfoBubble.cs @@ -0,0 +1,26 @@ +using UnityEngine; + +public class InfoBubble : MonoBehaviour +{ + public Vector3 WobbleAxis = Vector3.one; + + public float WobbleFrequency = 1f; + + public float WobbleAmplitude = 0.25f; + + public Transform TrackTarget; + + private Vector3 startOffsetTarget; + + private void Start() + { + startOffsetTarget = base.transform.position - TrackTarget.position; + } + + private void Update() + { + Vector3 eulerAngles = Mathf.Sin(WobbleFrequency * Time.timeSinceLevelLoad) * WobbleAxis * WobbleAmplitude; + base.transform.Rotate(eulerAngles); + base.transform.position = TrackTarget.position + startOffsetTarget; + } +} diff --git a/InputHandler.cs b/InputHandler.cs new file mode 100644 index 0000000..27adc82 --- /dev/null +++ b/InputHandler.cs @@ -0,0 +1,120 @@ +using UnityEngine; + +public class InputHandler : MonoBehaviour +{ + public Vector3 inputMovementDirection; + + public Vector3 lastInputDirection; + + public bool isSpringting; + + private WeaponHandler wepaonHandler; + + private MovementDataHandler movementData; + + private WeaponHandler weaponHandler; + + private CameraMovement cameraMovement; + + private PlayerDeath death; + + private HasControl hasControl; + + private MovementHandler movement; + + public bool allowStrafe = true; + + private void Start() + { + death = GetComponent<PlayerDeath>(); + movement = GetComponent<MovementHandler>(); + wepaonHandler = GetComponent<WeaponHandler>(); + hasControl = GetComponent<HasControl>(); + movementData = GetComponent<MovementDataHandler>(); + weaponHandler = GetComponent<WeaponHandler>(); + cameraMovement = GetComponentInChildren<CameraMovement>(); + } + + private void Update() + { + if ((bool)death && death.dead) + { + return; + } + if (!hasControl || hasControl.hasControl) + { + isSpringting = false; + inputMovementDirection = Vector3.zero; + if (Input.GetKey(KeyCode.W)) + { + inputMovementDirection += movementData.groundedForward; + } + if (Input.GetKey(KeyCode.S)) + { + inputMovementDirection += movementData.groundedBack; + } + if (Input.GetKey(KeyCode.D) && allowStrafe) + { + inputMovementDirection += movementData.right; + } + if (Input.GetKey(KeyCode.A) && allowStrafe) + { + inputMovementDirection += movementData.left; + } + if (Input.GetKey(KeyCode.LeftShift) && (!cameraMovement || !cameraMovement.ADS)) + { + isSpringting = true; + } + inputMovementDirection = inputMovementDirection.normalized; + if ((bool)movement && Input.GetKeyDown(KeyCode.Space)) + { + movement.Jump(); + } + if ((bool)weaponHandler) + { + if (weaponHandler.isDualWeilding) + { + if (Input.GetKey(KeyCode.Mouse1)) + { + weaponHandler.HoldAttack(shootWithRightGun: true, ADS: false); + } + if (Input.GetKeyDown(KeyCode.Mouse1)) + { + weaponHandler.PressAttack(shootWithRightGun: true, ADS: false); + } + if (Input.GetKey(KeyCode.Mouse0)) + { + weaponHandler.HoldAttack(shootWithRightGun: false, ADS: false); + } + if (Input.GetKeyDown(KeyCode.Mouse0)) + { + weaponHandler.PressAttack(shootWithRightGun: false, ADS: false); + } + } + else + { + if (Input.GetKey(KeyCode.Mouse1)) + { + cameraMovement.ADS = true; + } + else + { + cameraMovement.ADS = false; + } + if (Input.GetKey(KeyCode.Mouse0)) + { + weaponHandler.HoldAttack(shootWithRightGun: true, cameraMovement.ADS); + } + if (Input.GetKeyDown(KeyCode.Mouse0)) + { + weaponHandler.PressAttack(shootWithRightGun: true, cameraMovement.ADS); + } + } + } + } + if (inputMovementDirection != Vector3.zero) + { + lastInputDirection = inputMovementDirection; + } + } +} diff --git a/KneeLeft.cs b/KneeLeft.cs new file mode 100644 index 0000000..da00140 --- /dev/null +++ b/KneeLeft.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class KneeLeft : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/KneeRight.cs b/KneeRight.cs new file mode 100644 index 0000000..302a4ed --- /dev/null +++ b/KneeRight.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class KneeRight : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/Landfall.Network/LoginInformation.cs b/Landfall.Network/LoginInformation.cs new file mode 100644 index 0000000..989d15e --- /dev/null +++ b/Landfall.Network/LoginInformation.cs @@ -0,0 +1,6 @@ +namespace Landfall.Network; + +public class LoginInformation +{ + public string PlayerName { get; set; } +} diff --git a/Landfall.Network/NetworkController.cs b/Landfall.Network/NetworkController.cs new file mode 100644 index 0000000..22791ab --- /dev/null +++ b/Landfall.Network/NetworkController.cs @@ -0,0 +1,65 @@ +using UnityEngine; + +namespace Landfall.Network; + +public class NetworkController : MonoBehaviour +{ + [SerializeField] + private MonoBehaviour[] m_ScriptsToDisable; + + [SerializeField] + private Camera[] m_CamerasToDisable; + + [SerializeField] + private Transform m_Hip; + + private bool m_HasControl; + + private NetworkManager m_NetworkManager; + + private string m_Name; + + public void Init(NetworkManager manager, bool hasControl, string playerName) + { + m_NetworkManager = manager; + m_HasControl = hasControl; + GetComponent<HasControl>().ChangeControl(m_HasControl); + m_Name = playerName; + } + + private void StripPlayer() + { + if (!m_HasControl) + { + MonoBehaviour[] scriptsToDisable = m_ScriptsToDisable; + foreach (MonoBehaviour monoBehaviour in scriptsToDisable) + { + monoBehaviour.enabled = false; + } + Camera[] camerasToDisable = m_CamerasToDisable; + foreach (Camera camera in camerasToDisable) + { + camera.enabled = false; + } + } + } + + private void Update() + { + if (m_HasControl) + { + SendUpdatesToServer(); + } + } + + private void SendUpdatesToServer() + { + Vector3 position = m_Hip.position; + m_NetworkManager.UpdateFromLocalClient(position); + } + + public void UpdatePosition(Vector3 newPos) + { + base.transform.position = newPos; + } +} diff --git a/Landfall.Network/NetworkManager.cs b/Landfall.Network/NetworkManager.cs new file mode 100644 index 0000000..89d790a --- /dev/null +++ b/Landfall.Network/NetworkManager.cs @@ -0,0 +1,213 @@ +using System; +using System.Collections.Generic; +using Lidgren.Network; +using UnityEngine; + +namespace Landfall.Network; + +public class NetworkManager : MonoBehaviour +{ + [SerializeField] + private GameObject m_PlayerPrefab; + + private GameObject m_SpawnedPlayer; + + private NetClient m_Client; + + private List<NetPlayer> m_Players = new List<NetPlayer>(); + + private NetPlayer m_LocalPlayer; + + private string m_LocalName; + + public bool Active { get; private set; } + + private void Awake() + { + } + + private void Start() + { + InitNetwork(); + } + + private void InitNetwork() + { + if (!StartClient()) + { + Debug.LogError("Could Not Connect to server!"); + return; + } + Debug.Log("Connected To Server!"); + SpawnPlayer(); + } + + public bool StartClient() + { + m_LocalName = "Philip " + UnityEngine.Random.Range(0, int.MaxValue); + LoginInformation loginInformation = new LoginInformation(); + loginInformation.PlayerName = m_LocalName; + LoginInformation ob = loginInformation; + NetPeerConfiguration netPeerConfiguration = new NetPeerConfiguration("RobotsNetwork"); + netPeerConfiguration.EnableMessageType(NetIncomingMessageType.Data); + m_Client = new NetClient(netPeerConfiguration); + m_Client.Start(); + NetOutgoingMessage netOutgoingMessage = m_Client.CreateMessage(); + netOutgoingMessage.Write((byte)1); + netOutgoingMessage.WriteAllProperties(ob); + m_Client.Connect("127.0.0.1", 1337, netOutgoingMessage); + return EstablishConnection(); + } + + private bool EstablishConnection() + { + DateTime now = DateTime.Now; + do + { + NetIncomingMessage netIncomingMessage; + if ((netIncomingMessage = m_Client.ReadMessage()) != null) + { + NetIncomingMessageType messageType = netIncomingMessage.MessageType; + if (messageType == NetIncomingMessageType.StatusChanged && netIncomingMessage.SenderConnection.Status == NetConnectionStatus.Connected) + { + Active = true; + NetOutgoingMessage netOutgoingMessage = m_Client.CreateMessage(); + netOutgoingMessage.Write((byte)4); + m_Client.SendMessage(netOutgoingMessage, NetDeliveryMethod.ReliableOrdered); + return true; + } + } + } + while (DateTime.Now.Subtract(now).Seconds <= 5); + return false; + } + + private void SpawnPlayer() + { + m_SpawnedPlayer = UnityEngine.Object.Instantiate(m_PlayerPrefab); + m_LocalPlayer = new NetPlayer + { + PlayerName = m_LocalName, + PlayerObject = m_SpawnedPlayer + }; + m_SpawnedPlayer.GetComponent<NetworkController>().Init(this, hasControl: true, m_LocalName); + m_SpawnedPlayer.SetActive(value: true); + } + + private void Update() + { + if (Active) + { + ReadMessages(); + } + } + + private void ReadMessages() + { + NetIncomingMessage netIncomingMessage; + while ((netIncomingMessage = m_Client.ReadMessage()) != null) + { + if (netIncomingMessage.MessageType == NetIncomingMessageType.Data) + { + PacketType packetType = (PacketType)netIncomingMessage.ReadByte(); + Debug.Log("Recieved Message: " + packetType); + switch (packetType) + { + case PacketType.Login: + { + bool flag = netIncomingMessage.ReadBoolean(); + RecieveAllPlayers(netIncomingMessage); + break; + } + case PacketType.NewPlayer: + RecieveNewPlayer(netIncomingMessage); + break; + case PacketType.AllPlayers: + RecieveAllPlayers(netIncomingMessage); + break; + case PacketType.Ping: + Debug.Log("Recieved Ping!"); + break; + case PacketType.PlayerUpdate: + RecievedPlayerUpdate(netIncomingMessage); + break; + } + } + } + } + + private void RecievedPlayerUpdate(NetIncomingMessage msg) + { + Vector3 newPos = msg.ReadVector3(); + string playerName = msg.ReadString(); + NetPlayer netPlayer = FindPlayerByName(playerName); + netPlayer.PlayerObject.GetComponent<NetworkController>().UpdatePosition(newPos); + } + + private NetPlayer FindPlayerByName(string playerName) + { + foreach (NetPlayer player in m_Players) + { + if (player.PlayerName == playerName) + { + return player; + } + } + throw new Exception("Could not find player woth name: " + playerName); + } + + private void RecieveNewPlayer(NetIncomingMessage msg) + { + Player player = new Player(); + msg.ReadAllProperties(player); + SpawnRemotePlayer(player); + } + + private void RecieveAllPlayers(NetIncomingMessage message) + { + byte b = message.ReadByte(); + for (byte b2 = 0; b2 < b; b2 = (byte)(b2 + 1)) + { + Player player = new Player(); + message.ReadAllProperties(player); + if (IsNewPlayer(player)) + { + SpawnRemotePlayer(player); + } + } + } + + private bool IsNewPlayer(Player player) + { + foreach (NetPlayer player2 in m_Players) + { + if (player2.PlayerName == player.Name) + { + return false; + } + } + return true; + } + + private void SpawnRemotePlayer(Player newPlayer) + { + GameObject gameObject = UnityEngine.Object.Instantiate(m_PlayerPrefab); + gameObject.name = newPlayer.Name; + gameObject.GetComponent<NetworkController>().Init(this, hasControl: false, newPlayer.Name); + gameObject.SetActive(value: true); + m_Players.Add(new NetPlayer + { + PlayerObject = gameObject, + PlayerName = newPlayer.Name + }); + } + + public void UpdateFromLocalClient(Vector3 position) + { + NetOutgoingMessage netOutgoingMessage = m_Client.CreateMessage(); + netOutgoingMessage.Write((byte)5); + netOutgoingMessage.Write(position); + netOutgoingMessage.Write(m_LocalName); + m_Client.SendMessage(netOutgoingMessage, NetDeliveryMethod.Unreliable); + } +} diff --git a/Landfall.Network/PacketType.cs b/Landfall.Network/PacketType.cs new file mode 100644 index 0000000..e137b60 --- /dev/null +++ b/Landfall.Network/PacketType.cs @@ -0,0 +1,10 @@ +namespace Landfall.Network; + +public enum PacketType : byte +{ + Login = 1, + NewPlayer, + AllPlayers, + Ping, + PlayerUpdate +} diff --git a/Landfall.Network/Player.cs b/Landfall.Network/Player.cs new file mode 100644 index 0000000..3f5a66f --- /dev/null +++ b/Landfall.Network/Player.cs @@ -0,0 +1,13 @@ +using Lidgren.Network; +using UnityEngine; + +namespace Landfall.Network; + +public class Player +{ + public string Name { get; set; } + + public NetConnection Connection { get; set; } + + public Vector3 Position { get; set; } +} diff --git a/LeftHandPos.cs b/LeftHandPos.cs new file mode 100644 index 0000000..955cf44 --- /dev/null +++ b/LeftHandPos.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class LeftHandPos : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/LegLeft.cs b/LegLeft.cs new file mode 100644 index 0000000..23446b9 --- /dev/null +++ b/LegLeft.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class LegLeft : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/LegRight.cs b/LegRight.cs new file mode 100644 index 0000000..a050339 --- /dev/null +++ b/LegRight.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class LegRight : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/LookAtVelocity.cs b/LookAtVelocity.cs new file mode 100644 index 0000000..6504d6f --- /dev/null +++ b/LookAtVelocity.cs @@ -0,0 +1,19 @@ +using UnityEngine; + +public class LookAtVelocity : MonoBehaviour +{ + private Rigidbody rig; + + private void Start() + { + rig = GetComponentInParent<Rigidbody>(); + } + + private void Update() + { + if (rig.velocity.magnitude > 2f) + { + base.transform.rotation = Quaternion.LookRotation(rig.velocity); + } + } +} diff --git a/MipTexMap.cs b/MipTexMap.cs new file mode 100644 index 0000000..57b6abc --- /dev/null +++ b/MipTexMap.cs @@ -0,0 +1,119 @@ +using UnityEngine; + +public class MipTexMap : MonoBehaviour +{ + private static Texture2D mipFilterTex64; + + private static Texture2D mipFilterTex128; + + private static Texture2D mipFilterTex256; + + private static Texture2D mipFilterTex512; + + private static Texture2D mipFilterTex1024; + + private static Texture2D mipFilterTex2048; + + private static void BuildMipFilterTex(int size) + { + size = Mathf.ClosestPowerOfTwo(size); + Texture2D texture2D = new Texture2D(size, size, TextureFormat.Alpha8, mipmap: true); + texture2D.anisoLevel = 3; + texture2D.filterMode = FilterMode.Trilinear; + texture2D.mipMapBias = 0f; + for (int i = 0; i < texture2D.mipmapCount; i++) + { + int num = size * size; + Color[] array = new Color[num]; + float num2 = 1f * (float)i / (float)(texture2D.mipmapCount - 1); + Color color = new Color(num2, num2, num2, num2); + for (int j = 0; j < num; j++) + { + array[j] = color; + } + texture2D.SetPixels(array, i); + } + texture2D.Apply(updateMipmaps: false, makeNoLongerReadable: true); + switch (size) + { + case 64: + mipFilterTex64 = texture2D; + break; + case 128: + mipFilterTex128 = texture2D; + break; + case 256: + mipFilterTex256 = texture2D; + break; + case 512: + mipFilterTex512 = texture2D; + break; + case 1024: + mipFilterTex1024 = texture2D; + break; + case 2048: + mipFilterTex2048 = texture2D; + break; + default: + mipFilterTex512 = texture2D; + break; + } + } + + public static Texture2D GetTex(int size) + { + size = Mathf.ClosestPowerOfTwo(size); + switch (size) + { + case 64: + if ((bool)mipFilterTex64) + { + return mipFilterTex64; + } + BuildMipFilterTex(size); + return mipFilterTex64; + case 128: + if ((bool)mipFilterTex128) + { + return mipFilterTex128; + } + BuildMipFilterTex(size); + return mipFilterTex128; + case 256: + if ((bool)mipFilterTex256) + { + return mipFilterTex256; + } + BuildMipFilterTex(size); + return mipFilterTex256; + case 512: + if ((bool)mipFilterTex512) + { + return mipFilterTex512; + } + BuildMipFilterTex(size); + return mipFilterTex512; + case 1024: + if ((bool)mipFilterTex1024) + { + return mipFilterTex1024; + } + BuildMipFilterTex(size); + return mipFilterTex1024; + case 2048: + if ((bool)mipFilterTex2048) + { + return mipFilterTex2048; + } + BuildMipFilterTex(size); + return mipFilterTex2048; + default: + if ((bool)mipFilterTex512) + { + return mipFilterTex512; + } + BuildMipFilterTex(size); + return mipFilterTex512; + } + } +} diff --git a/MouseLook.cs b/MouseLook.cs new file mode 100644 index 0000000..45c7cca --- /dev/null +++ b/MouseLook.cs @@ -0,0 +1,117 @@ +using UnityEngine; + +public class MouseLook : MonoBehaviour +{ + public enum RotationAxes + { + MouseXAndY, + MouseX, + MouseY + } + + public RotationAxes axes; + + public float sensitivityX = 3f; + + public float sensitivityY = 3f; + + public float minimumX = -360f; + + public float maximumX = 360f; + + public float minimumY = -80f; + + public float maximumY = 80f; + + public float forwardSpeedScale = 0.03f; + + public float strafeSpeedScale = 0.03f; + + private float rotationX; + + private float rotationY; + + private bool look; + + private Quaternion originalRotation; + + private void Update() + { + if (GUIUtility.hotControl != 0) + { + return; + } + if (Input.GetMouseButtonDown(0)) + { + look = true; + } + if (Input.GetMouseButtonUp(0)) + { + look = false; + } + if (look) + { + if (axes == RotationAxes.MouseXAndY) + { + rotationX += Input.GetAxis("Mouse X") * sensitivityX; + rotationY += Input.GetAxis("Mouse Y") * sensitivityY; + rotationX = ClampAngle(rotationX, minimumX, maximumX); + rotationY = ClampAngle(rotationY, minimumY, maximumY); + Quaternion quaternion = Quaternion.AngleAxis(rotationX, Vector3.up); + Quaternion quaternion2 = Quaternion.AngleAxis(rotationY, Vector3.left); + base.transform.localRotation = originalRotation * quaternion * quaternion2; + } + else if (axes == RotationAxes.MouseX) + { + rotationX += Input.GetAxis("Mouse X") * sensitivityX; + rotationX = ClampAngle(rotationX, minimumX, maximumX); + Quaternion quaternion3 = Quaternion.AngleAxis(rotationX, Vector3.up); + base.transform.localRotation = originalRotation * quaternion3; + } + else + { + rotationY += Input.GetAxis("Mouse Y") * sensitivityY; + rotationY = ClampAngle(rotationY, minimumY, maximumY); + Quaternion quaternion4 = Quaternion.AngleAxis(rotationY, Vector3.left); + base.transform.localRotation = originalRotation * quaternion4; + } + } + Vector3 direction = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical")); + direction = base.transform.TransformDirection(direction); + direction *= 10f; + float num = ((!Input.GetKey(KeyCode.LeftShift)) ? 50f : 150f); + float num2 = Input.GetAxis("Vertical") * forwardSpeedScale * num; + float num3 = Input.GetAxis("Horizontal") * strafeSpeedScale * num; + if (num2 != 0f) + { + base.transform.position += base.transform.forward * num2; + } + if (num3 != 0f) + { + base.transform.position += base.transform.right * num3; + } + } + + private void Start() + { + if ((bool)GetComponent<Rigidbody>()) + { + GetComponent<Rigidbody>().freezeRotation = true; + } + originalRotation = base.transform.localRotation; + look = false; + } + + public static float ClampAngle(float angle, float min, float max) + { + if (angle < -360f) + { + angle += 360f; + } + if (angle > 360f) + { + angle -= 360f; + } + return Mathf.Clamp(angle, min, max); + } +} diff --git a/MouseOrbitCS.cs b/MouseOrbitCS.cs new file mode 100644 index 0000000..40c2fb2 --- /dev/null +++ b/MouseOrbitCS.cs @@ -0,0 +1,64 @@ +using UnityEngine; + +public class MouseOrbitCS : MonoBehaviour +{ + public Transform target; + + public float distance = 10f; + + public float xSpeed = 250f; + + public float ySpeed = 120f; + + public float yMinLimit = -20f; + + public float yMaxLimit = 80f; + + private float x; + + private float y; + + private float normal_angle; + + private void Start() + { + Vector3 eulerAngles = base.transform.eulerAngles; + x = eulerAngles.y; + y = eulerAngles.x; + } + + private void LateUpdate() + { + if ((bool)target && !Input.GetKey(KeyCode.F)) + { + if (!Input.GetMouseButton(0)) + { + x += Input.GetAxis("Mouse X") * xSpeed * 0.02f; + y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f; + } + y = ClampAngle(y, yMinLimit + normal_angle, yMaxLimit + normal_angle); + Quaternion quaternion = Quaternion.Euler(y, x, 0f); + Vector3 position = quaternion * new Vector3(0f, 0f, 0f - distance) + target.position; + base.transform.rotation = quaternion; + base.transform.position = position; + } + } + + private static float ClampAngle(float angle, float min, float max) + { + if (angle < -360f) + { + angle += 360f; + } + if (angle > 360f) + { + angle -= 360f; + } + return Mathf.Clamp(angle, min, max); + } + + public void set_normal_angle(float a) + { + normal_angle = a; + } +} diff --git a/MoveRig.cs b/MoveRig.cs new file mode 100644 index 0000000..e4843f0 --- /dev/null +++ b/MoveRig.cs @@ -0,0 +1,20 @@ +using UnityEngine; + +public class MoveRig : MonoBehaviour +{ + private Rigidbody rig; + + public float force; + + public Transform target; + + private void Start() + { + rig = GetComponentInParent<Rigidbody>(); + } + + private void FixedUpdate() + { + rig.AddForceAtPosition(force * (target.position - base.transform.position), base.transform.position, ForceMode.Acceleration); + } +} diff --git a/MoveTransform.cs b/MoveTransform.cs new file mode 100644 index 0000000..1b135c3 --- /dev/null +++ b/MoveTransform.cs @@ -0,0 +1,21 @@ +using UnityEngine; + +public class MoveTransform : MonoBehaviour +{ + public Vector3 startForce; + + private Vector3 velocity = Vector3.zero; + + public float gravity; + + private void Start() + { + velocity = base.transform.TransformDirection(startForce); + } + + private void Update() + { + velocity += Time.deltaTime * Vector3.down * gravity; + base.transform.position += velocity * Time.deltaTime; + } +} diff --git a/MovementDataHandler.cs b/MovementDataHandler.cs new file mode 100644 index 0000000..18d43f5 --- /dev/null +++ b/MovementDataHandler.cs @@ -0,0 +1,92 @@ +using UnityEngine; + +public class MovementDataHandler : MonoBehaviour +{ + [HideInInspector] + public Vector3 groundedForward; + + [HideInInspector] + public Vector3 right; + + [HideInInspector] + public Vector3 left; + + [HideInInspector] + public Vector3 groundedBack; + + private Transform hip; + + private Transform torso; + + public Transform rotationTarget; + + [HideInInspector] + public float slopeStrenght; + + public float slopeVelocityStrenght; + + [HideInInspector] + public float sinceJump = 1f; + + [HideInInspector] + public Vector3 groundNormal; + + private InputHandler inputHandler; + + private Transform leftKnee; + + private Transform rightKnee; + + private void Start() + { + inputHandler = GetComponent<InputHandler>(); + hip = GetComponentInChildren<Hip>().transform; + torso = GetComponentInChildren<Torso>().transform; + if (!rotationTarget) + { + rotationTarget = GetComponentInChildren<RotationTarget>().transform; + } + KneeLeft componentInChildren = GetComponentInChildren<KneeLeft>(); + if ((bool)componentInChildren) + { + leftKnee = componentInChildren.transform; + } + KneeRight componentInChildren2 = GetComponentInChildren<KneeRight>(); + if ((bool)componentInChildren2) + { + rightKnee = componentInChildren2.transform; + } + } + + private void Update() + { + sinceJump += Time.deltaTime; + groundedForward = rotationTarget.forward; + groundedForward.y = slopeStrenght * 1f; + groundedForward = groundedForward.normalized; + groundedBack = -groundedForward; + right = rotationTarget.right; + left = -rotationTarget.right; + slopeStrenght = Mathf.Lerp(slopeStrenght, 0f, Time.deltaTime * 1f); + Debug.DrawLine(hip.position, hip.position + groundedForward * 10f); + } + + public void SetSlope(Vector3 normal) + { + groundNormal = normal; + slopeStrenght = Vector3.Cross(rotationTarget.right, normal).y; + Vector3 lhs = Vector3.Cross(Vector3.up, inputHandler.inputMovementDirection); + slopeVelocityStrenght = Vector3.Cross(lhs, normal).y; + } + + public float GetSmallestLegAngle() + { + float num = Vector3.Angle(leftKnee.forward, Vector3.down); + float num2 = Vector3.Angle(rightKnee.forward, Vector3.down); + if (num < num2) + { + return num; + } + return num2; + } +} diff --git a/MovementHandler.cs b/MovementHandler.cs new file mode 100644 index 0000000..22795f7 --- /dev/null +++ b/MovementHandler.cs @@ -0,0 +1,85 @@ +using System.Collections; +using UnityEngine; + +public class MovementHandler : MonoBehaviour +{ + private InputHandler inputHandler; + + public float friction = 0.9f; + + public Vector3 movementVector; + + public float[] animationForceAmounts; + + private AnimationHandler animationHandler; + + private RigidbodyHolder allRigs; + + public AnimationCurve jumpCurve; + + public float jumpForce; + + private StandingDataHandler standingData; + + private MovementDataHandler data; + + private PlayerDeath death; + + [HideInInspector] + public float multiplier = 1f; + + private WobbleShake wobbleShake; + + private void Start() + { + wobbleShake = GetComponentInChildren<WobbleShake>(); + death = GetComponent<PlayerDeath>(); + standingData = GetComponent<StandingDataHandler>(); + inputHandler = GetComponent<InputHandler>(); + animationHandler = GetComponent<AnimationHandler>(); + allRigs = GetComponent<RigidbodyHolder>(); + data = GetComponent<MovementDataHandler>(); + } + + private void FixedUpdate() + { + if (!death.dead) + { + data.sinceJump += Time.fixedDeltaTime; + movementVector += inputHandler.inputMovementDirection * animationForceAmounts[animationHandler.animationState]; + movementVector *= friction; + for (int i = 0; i < allRigs.GetAllRigs().Length; i++) + { + allRigs.GetAllRigs()[i].AddForce(movementVector * multiplier, ForceMode.Acceleration); + } + } + } + + public void Jump() + { + if (!(data.sinceJump < 0.5f) && !(standingData.sinceGrounded > 0.3f)) + { + data.sinceJump = 0f; + StartCoroutine(AddJumpForce()); + wobbleShake.AddShake(Vector3.up * 2f, 0.8f); + } + } + + private IEnumerator AddJumpForce() + { + float counter = 0f; + for (int i = 0; i < allRigs.GetAllRigs().Length; i++) + { + allRigs.GetAllRigs()[i].velocity = new Vector3(allRigs.GetAllRigs()[i].velocity.x, 0f, allRigs.GetAllRigs()[i].velocity.z); + } + while (counter < jumpCurve.keys[jumpCurve.length - 1].time && !death.dead) + { + counter += Time.deltaTime; + for (int j = 0; j < allRigs.GetAllRigs().Length; j++) + { + allRigs.GetAllRigs()[j].AddForce(Vector3.up * multiplier * jumpForce * jumpCurve.Evaluate(counter) * Time.deltaTime, ForceMode.Acceleration); + } + yield return null; + } + } +} diff --git a/MovementRig.cs b/MovementRig.cs new file mode 100644 index 0000000..e09ce49 --- /dev/null +++ b/MovementRig.cs @@ -0,0 +1,10 @@ +using System; +using UnityEngine; + +[Serializable] +public class MovementRig +{ + public Rigidbody rig; + + public float multiplier = 1f; +} @@ -0,0 +1,12 @@ +using UnityEngine; + +public class Neck : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/NetPlayer.cs b/NetPlayer.cs new file mode 100644 index 0000000..213568d --- /dev/null +++ b/NetPlayer.cs @@ -0,0 +1,8 @@ +using UnityEngine; + +public class NetPlayer +{ + public GameObject PlayerObject; + + public string PlayerName; +} @@ -0,0 +1,104 @@ +using UnityEngine; + +public class PID : MonoBehaviour +{ + public float maxForce; + + public float proportionalGain; + + public float differentialGain; + + private Vector3 lastError = Vector3.zero; + + private Vector3 currentForce = Vector3.zero; + + public float maxTorque; + + public float proportionalGainTorque; + + public float differentialGainTorque; + + private Vector3 lastErrorTorque = Vector3.zero; + + private Vector3 currentTorque = Vector3.zero; + + private Vector3 lastErrorTorqueUp = Vector3.zero; + + private Vector3 currentTorqueUp = Vector3.zero; + + public float currentMultiplier = 1f; + + private Rigidbody rig; + + private SetInertiaTension inertia; + + public Transform addForcePoint; + + private Transform forcePoint; + + private void Start() + { + rig = GetComponent<Rigidbody>(); + inertia = GetComponent<SetInertiaTension>(); + } + + private void Update() + { + if ((bool)inertia) + { + currentMultiplier = 1f - Mathf.Clamp(inertia.collisionValue, 0f, 0.7f); + } + } + + private void FixedUpdate() + { + } + + public void DoPID(Vector3 targetPosition, Vector3 targetRotation, Vector3 targetRotationUp, float multiplier = 1f) + { + AddForce(targetPosition, currentMultiplier * multiplier); + if (proportionalGainTorque != 0f) + { + AddTorque(targetRotation, currentMultiplier * multiplier); + AddTorqueUp(targetRotationUp, currentMultiplier * multiplier); + } + } + + public void AddForce(Vector3 targetPosition, float multiplier = 1f) + { + forcePoint = ((!(addForcePoint == null)) ? addForcePoint : base.transform); + Vector3 vector = targetPosition - forcePoint.position; + Vector3 vector2 = (vector - lastError) / Time.fixedDeltaTime; + lastError = vector; + currentForce = vector * proportionalGain + vector2 * differentialGain; + currentForce = Vector3.ClampMagnitude(currentForce, maxForce); + if ((bool)addForcePoint) + { + rig.AddForceAtPosition(currentForce * Time.fixedDeltaTime * 60f * multiplier, addForcePoint.position, ForceMode.Acceleration); + } + else + { + rig.AddForce(currentForce * Time.fixedDeltaTime * 60f * multiplier, ForceMode.Acceleration); + } + } + + public void AddTorque(Vector3 targetRotation, float multiplier = 1f) + { + Vector3 vector = Mathf.Clamp(Vector3.Angle(targetRotation, base.transform.forward), 0f, 3f) * Vector3.Cross(targetRotation, base.transform.forward); + Vector3 vector2 = (vector - lastErrorTorque) / Time.fixedDeltaTime; + lastErrorTorque = vector; + currentTorque = vector * proportionalGainTorque + vector2 * differentialGainTorque; + currentTorque = Vector3.ClampMagnitude(currentTorque, maxTorque); + rig.AddTorque(-currentTorque * Time.fixedDeltaTime * 60f * multiplier, ForceMode.Acceleration); + } + + public void AddTorqueUp(Vector3 targetRotation, float multiplier = 1f) + { + Vector3 vector = Mathf.Clamp(Vector3.Angle(targetRotation, base.transform.up), 0f, 3f) * Vector3.Cross(targetRotation, base.transform.up); + Vector3 vector2 = (vector - lastErrorTorqueUp) / Time.fixedDeltaTime; + lastErrorTorqueUp = vector; + currentTorqueUp = vector * proportionalGainTorque + vector2 * differentialGainTorque; + currentTorqueUp = Vector3.ClampMagnitude(currentTorqueUp, maxTorque); + rig.AddTorque(-currentTorqueUp * Time.fixedDeltaTime * 60f * multiplier, ForceMode.Acceleration); + } +} diff --git a/ParticleParent.cs b/ParticleParent.cs new file mode 100644 index 0000000..dc8de91 --- /dev/null +++ b/ParticleParent.cs @@ -0,0 +1,39 @@ +using UnityEngine; + +public class ParticleParent : MonoBehaviour +{ + public GameObject particleObject; + + private ParticleSystem[] parts; + + private Vector2[] particleSizes; + + private void Start() + { + particleObject = Object.Instantiate(particleObject, base.transform.position, base.transform.rotation); + particleObject.transform.parent = base.transform; + parts = particleObject.GetComponentsInChildren<ParticleSystem>(); + particleSizes = new Vector2[parts.Length]; + for (int i = 0; i < parts.Length; i++) + { + particleSizes[i].x = parts[i].main.startSize.constantMin; + particleSizes[i].y = parts[i].main.startSize.constantMax; + } + } + + private void Update() + { + } + + public void Play(float damage, float multi) + { + for (int i = 0; i < parts.Length; i++) + { + ParticleSystem.MainModule mainModule = default(ParticleSystem.MainModule); + mainModule = parts[i].main; + float num = (1.5f + damage * 0.01f) * multi; + mainModule.startSize = new ParticleSystem.MinMaxCurve(particleSizes[i].x * num, particleSizes[i].y * num); + parts[i].Play(); + } + } +} diff --git a/PhysicsAnimation.cs b/PhysicsAnimation.cs new file mode 100644 index 0000000..120a343 --- /dev/null +++ b/PhysicsAnimation.cs @@ -0,0 +1,36 @@ +using System; +using UnityEngine; + +[Serializable] +public class PhysicsAnimation +{ + public enum TorqueSpace + { + World, + Local, + Parent, + Hip + } + + public enum ForceSpace + { + World, + Local, + Parent, + Hip + } + + [Header("TORQUES")] + public Vector3 forwardTorque; + + public Vector3 backwardsTorque; + + public TorqueSpace torqueSpace; + + [Header("FORCES")] + public Vector3 forwardForce; + + public Vector3 backwardsForce; + + public ForceSpace forceSpace; +} diff --git a/PhysicsLerpBackToStart.cs b/PhysicsLerpBackToStart.cs new file mode 100644 index 0000000..5139a00 --- /dev/null +++ b/PhysicsLerpBackToStart.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class PhysicsLerpBackToStart : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/Pickup.cs b/Pickup.cs new file mode 100644 index 0000000..1c44994 --- /dev/null +++ b/Pickup.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class Pickup : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/PickupHandler.cs b/PickupHandler.cs new file mode 100644 index 0000000..8bf1615 --- /dev/null +++ b/PickupHandler.cs @@ -0,0 +1,63 @@ +using UnityEngine; + +public class PickupHandler : MonoBehaviour +{ + public Pickup setWeapon; + + public Pickup setWeapon2; + + private WeaponHandler weaponHandler; + + private Holding holding; + + private float counter; + + private void Start() + { + weaponHandler = GetComponent<WeaponHandler>(); + holding = GetComponent<Holding>(); + if ((bool)setWeapon) + { + PickUp(setWeapon); + } + if ((bool)setWeapon2) + { + PickUp2(setWeapon2); + } + } + + private void Update() + { + counter += Time.deltaTime; + } + + public void PickUp(Pickup objectToPickUp) + { + if (!(counter < 1f)) + { + counter = 0f; + holding.Drop(); + Weapon component = objectToPickUp.GetComponent<Weapon>(); + Gun component2 = component.GetComponent<Gun>(); + weaponHandler.SetGun(component2, mainHand: true); + bool hasOffHand = false; + if ((bool)setWeapon2) + { + hasOffHand = true; + } + HoldableObject component3 = component.GetComponent<HoldableObject>(); + component3.holder = base.transform; + holding.StartHolding(component3, hasOffHand); + } + } + + public void PickUp2(Pickup objectToPickUp) + { + Weapon component = objectToPickUp.GetComponent<Weapon>(); + Gun component2 = component.GetComponent<Gun>(); + weaponHandler.SetGun(component2, mainHand: false); + HoldableObject component3 = component.GetComponent<HoldableObject>(); + component3.holder = base.transform; + holding.StartHolding(component3, hasOffHand: true); + } +} diff --git a/Player.cs b/Player.cs new file mode 100644 index 0000000..55ff387 --- /dev/null +++ b/Player.cs @@ -0,0 +1,18 @@ +using UnityEngine; + +public class Player : MonoBehaviour +{ + public static Player localPlayer; + + public bool isLocalPlayer; + + public Transform torso; + + private void Start() + { + if (isLocalPlayer) + { + localPlayer = this; + } + } +} diff --git a/PlayerDeath.cs b/PlayerDeath.cs new file mode 100644 index 0000000..ec0813a --- /dev/null +++ b/PlayerDeath.cs @@ -0,0 +1,125 @@ +using UnityEngine; + +public class PlayerDeath : MonoBehaviour +{ + public bool dead; + + private bool isFrozen; + + public float muscleFunction = 1f; + + public bool terminalState; + + private DamageEffects damageEffects; + + private RagdollHandler ragdoll; + + private Transform hip; + + public float health = 100f; + + public ParticleSystem[] damageParticles; + + private HasControl hasControll; + + private Holding holding; + + private void Start() + { + damageEffects = GetComponent<DamageEffects>(); + ragdoll = GetComponent<RagdollHandler>(); + hip = GetComponentInChildren<Hip>().transform; + hasControll = GetComponent<HasControl>(); + holding = GetComponent<Holding>(); + } + + private void Update() + { + if (health < 100f) + { + health += Time.deltaTime * 10f; + health = Mathf.Clamp(health, -10f, 100f); + } + if (hip.transform.position.y < -10f) + { + Die(); + } + if (terminalState && muscleFunction > 0f) + { + muscleFunction -= Time.deltaTime * 1f; + } + if (muscleFunction < 0f && !isFrozen) + { + FreezeBody(); + } + } + + public void TakeDamage(Vector3 damage, Vector3 hitPoint, Rigidbody hitRig = null) + { + if (hasControll.hasControl) + { + damageEffects.TakeDamage(damage, hitPoint); + } + if (hitPoint != Vector3.zero) + { + for (int i = 0; i < damageParticles.Length; i++) + { + damageParticles[i].transform.rotation = Quaternion.LookRotation(damage); + damageParticles[i].transform.position = hitPoint; + damageParticles[i].Play(); + } + } + health -= damage.magnitude; + if (!(health <= 0f)) + { + return; + } + if ((bool)hitRig) + { + ConfigurableJoint component = hitRig.GetComponent<ConfigurableJoint>(); + if ((bool)component) + { + Object.Destroy(component); + } + } + Kill(); + } + + public void FreezeBody() + { + isFrozen = true; + Joint[] componentsInChildren = GetComponentsInChildren<Joint>(); + for (int i = 0; i < componentsInChildren.Length; i++) + { + ConfigurableJoint configurableJoint = (ConfigurableJoint)componentsInChildren[i]; + Rigidbody component = configurableJoint.GetComponent<Rigidbody>(); + JointDrive angularXDrive = configurableJoint.angularXDrive; + angularXDrive.positionSpring = 5f * component.mass; + angularXDrive.positionDamper = 1f * component.mass; + configurableJoint.angularXDrive = angularXDrive; + configurableJoint.angularYZDrive = angularXDrive; + configurableJoint.SetTargetRotationLocal(configurableJoint.transform.localRotation, configurableJoint.gameObject.GetComponent<StartRotation>().startRotationLocal); + } + } + + public void Die() + { + if (!dead) + { + holding.Drop(); + dead = true; + ragdoll.ragdollValue = 0f; + Collider[] componentsInChildren = GetComponentsInChildren<Collider>(); + foreach (Collider collider in componentsInChildren) + { + collider.material = null; + } + } + } + + public void Kill() + { + terminalState = true; + Die(); + } +} diff --git a/PlayerKnockback.cs b/PlayerKnockback.cs new file mode 100644 index 0000000..89fffb8 --- /dev/null +++ b/PlayerKnockback.cs @@ -0,0 +1,52 @@ +using UnityEngine; + +public class PlayerKnockback : MonoBehaviour +{ + private RigidbodyHolder allRigs; + + private StandingDataHandler standing; + + private WeaponHandler weapons; + + private void Start() + { + allRigs = GetComponent<RigidbodyHolder>(); + standing = GetComponent<StandingDataHandler>(); + weapons = GetComponent<WeaponHandler>(); + } + + private void Update() + { + if (Input.GetKeyDown(KeyCode.K)) + { + AddSeriousKnockback(); + } + } + + public void AddForce(Vector3 force, Rigidbody rig) + { + if (force.magnitude > 200f) + { + AddSeriousKnockback(); + force *= 0.1f; + } + for (int i = 0; i < allRigs.GetAllRigs().Length; i++) + { + float num = 1f; + if (rig == allRigs.GetAllRigs()[i]) + { + num *= 1f; + } + allRigs.GetAllRigs()[i].AddForce(force * num * 20f, ForceMode.Acceleration); + } + } + + private void AddSeriousKnockback() + { + GetComponent<PlayerDeath>().Kill(); + } + + private void AddNormalKnockback() + { + } +} diff --git a/ProjectileHit.cs b/ProjectileHit.cs new file mode 100644 index 0000000..305f9fc --- /dev/null +++ b/ProjectileHit.cs @@ -0,0 +1,75 @@ +using UnityEngine; + +public class ProjectileHit : MonoBehaviour +{ + public GameObject soundPlayer; + + public ProjectileHitSpawn[] objectsToSpawnOnHit; + + private bool done; + + public float damage = 25f; + + public float force; + + private void Start() + { + } + + private void Update() + { + } + + public void Hit(RaycastHit hit) + { + if (done) + { + return; + } + done = true; + Player component = hit.transform.root.GetComponent<Player>(); + ProjectileHitSpawn[] array = objectsToSpawnOnHit; + foreach (ProjectileHitSpawn projectileHitSpawn in array) + { + Vector3 point = hit.point; + Quaternion rotation = Quaternion.identity; + if ((bool)component) + { + if (projectileHitSpawn.playerSpawnRotation == ProjectileHitSpawn.SpawnRotation.forward) + { + rotation = Quaternion.LookRotation(base.transform.forward); + } + if (projectileHitSpawn.playerSpawnRotation == ProjectileHitSpawn.SpawnRotation.normal) + { + rotation = Quaternion.LookRotation(hit.normal); + } + } + else + { + if (projectileHitSpawn.groundSpawnRotation == ProjectileHitSpawn.SpawnRotation.forward) + { + rotation = Quaternion.LookRotation(base.transform.forward); + } + if (projectileHitSpawn.groundSpawnRotation == ProjectileHitSpawn.SpawnRotation.normal) + { + rotation = Quaternion.LookRotation(hit.normal); + } + } + GameObject gameObject = Object.Instantiate(projectileHitSpawn.spawnedObject, point, rotation); + } + Damagable component2 = hit.transform.GetComponent<Damagable>(); + if ((bool)component2) + { + component2.TakeDamage(damage * base.transform.forward, hit.point); + } + Rigidbody rigidbody = hit.rigidbody; + if ((bool)rigidbody && force != 0f) + { + float num = 1f; + num = Mathf.Clamp(rigidbody.mass / 10f, 0f, 1f); + rigidbody.AddForceAtPosition(base.transform.forward * force * num, hit.point, ForceMode.Impulse); + } + Object.Instantiate(soundPlayer, hit.point, Quaternion.identity).GetComponent<SFXPlayer>().Play(hit); + Object.Destroy(base.gameObject); + } +} diff --git a/ProjectileHitSpawn.cs b/ProjectileHitSpawn.cs new file mode 100644 index 0000000..8a1df24 --- /dev/null +++ b/ProjectileHitSpawn.cs @@ -0,0 +1,18 @@ +using System; +using UnityEngine; + +[Serializable] +public class ProjectileHitSpawn +{ + public enum SpawnRotation + { + normal, + forward + } + + public GameObject spawnedObject; + + public SpawnRotation groundSpawnRotation; + + public SpawnRotation playerSpawnRotation; +} diff --git a/Properties/AssemblyInfo.cs b/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..80d7579 --- /dev/null +++ b/Properties/AssemblyInfo.cs @@ -0,0 +1,7 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Security; +using System.Security.Permissions; + +[assembly: AssemblyVersion("0.0.0.0")] diff --git a/RTPColorChannels.cs b/RTPColorChannels.cs new file mode 100644 index 0000000..e60fb18 --- /dev/null +++ b/RTPColorChannels.cs @@ -0,0 +1,7 @@ +public enum RTPColorChannels +{ + R, + G, + B, + A +} diff --git a/RTPFogType.cs b/RTPFogType.cs new file mode 100644 index 0000000..e6381d0 --- /dev/null +++ b/RTPFogType.cs @@ -0,0 +1,7 @@ +public enum RTPFogType +{ + Exponential, + Exp2, + Linear, + None +} diff --git a/RTPLodLevel.cs b/RTPLodLevel.cs new file mode 100644 index 0000000..712f97b --- /dev/null +++ b/RTPLodLevel.cs @@ -0,0 +1,8 @@ +public enum RTPLodLevel +{ + POM_SoftShadows, + POM_HardShadows, + POM_NoShadows, + PM, + SIMPLE +} diff --git a/RTPObjExporter.cs b/RTPObjExporter.cs new file mode 100644 index 0000000..791de73 --- /dev/null +++ b/RTPObjExporter.cs @@ -0,0 +1,52 @@ +using System.IO; +using System.Text; +using UnityEngine; + +public class RTPObjExporter +{ + public static string MeshToString(MeshFilter mf) + { + Mesh sharedMesh = mf.sharedMesh; + Material[] sharedMaterials = mf.GetComponent<Renderer>().sharedMaterials; + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append("g ").Append(mf.name).Append("\n"); + Vector3[] vertices = sharedMesh.vertices; + for (int i = 0; i < vertices.Length; i++) + { + Vector3 vector = vertices[i]; + stringBuilder.Append($"v {0f - vector.x} {vector.y} {vector.z}\n"); + } + stringBuilder.Append("\n"); + Vector3[] normals = sharedMesh.normals; + for (int j = 0; j < normals.Length; j++) + { + Vector3 vector2 = normals[j]; + stringBuilder.Append($"vn {0f - vector2.x} {vector2.y} {vector2.z}\n"); + } + stringBuilder.Append("\n"); + Vector2[] uv = sharedMesh.uv; + for (int k = 0; k < uv.Length; k++) + { + Vector3 vector3 = uv[k]; + stringBuilder.Append($"vt {vector3.x} {vector3.y}\n"); + } + for (int l = 0; l < sharedMesh.subMeshCount; l++) + { + stringBuilder.Append("\n"); + stringBuilder.Append("usemtl ").Append(sharedMaterials[l].name).Append("\n"); + stringBuilder.Append("usemap ").Append(sharedMaterials[l].name).Append("\n"); + int[] triangles = sharedMesh.GetTriangles(l); + for (int m = 0; m < triangles.Length; m += 3) + { + stringBuilder.Append(string.Format("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}\n", triangles[m + 2] + 1, triangles[m + 1] + 1, triangles[m] + 1)); + } + } + return stringBuilder.ToString(); + } + + public static void MeshToFile(MeshFilter mf, string filename) + { + using StreamWriter streamWriter = new StreamWriter(filename); + streamWriter.Write(MeshToString(mf)); + } +} diff --git a/RTPTangentSolver.cs b/RTPTangentSolver.cs new file mode 100644 index 0000000..d06b9d2 --- /dev/null +++ b/RTPTangentSolver.cs @@ -0,0 +1,59 @@ +using UnityEngine; + +public class RTPTangentSolver +{ + public static void Solve(Mesh theMesh, bool planetFlag = false) + { + int vertexCount = theMesh.vertexCount; + Vector3[] vertices = theMesh.vertices; + Vector3[] normals = theMesh.normals; + Vector2[] uv = theMesh.uv; + int[] triangles = theMesh.triangles; + Vector4[] array = new Vector4[vertexCount]; + Vector3[] array2 = new Vector3[vertexCount]; + Vector3[] array3 = new Vector3[vertexCount]; + for (int i = 0; i < triangles.Length; i += 3) + { + int num = triangles[i]; + int num2 = triangles[i + 1]; + int num3 = triangles[i + 2]; + Vector3 vector = vertices[num]; + Vector3 vector2 = vertices[num2]; + Vector3 vector3 = vertices[num3]; + Vector2 vector4 = uv[num]; + Vector2 vector5 = uv[num2]; + Vector2 vector6 = uv[num3]; + float num4 = vector2.x - vector.x; + float num5 = vector3.x - vector.x; + float num6 = vector2.y - vector.y; + float num7 = vector3.y - vector.y; + float num8 = vector2.z - vector.z; + float num9 = vector3.z - vector.z; + float num10 = vector5.x - vector4.x; + float num11 = vector6.x - vector4.x; + float num12 = vector5.y - vector4.y; + float num13 = vector6.y - vector4.y; + float num14 = num10 * num13 - num11 * num12; + float num15 = ((num14 != 0f) ? (1f / num14) : 0f); + Vector3 vector7 = new Vector3((num13 * num4 - num12 * num5) * num15, (num13 * num6 - num12 * num7) * num15, (num13 * num8 - num12 * num9) * num15); + Vector3 vector8 = new Vector3((num10 * num5 - num11 * num4) * num15, (num10 * num7 - num11 * num6) * num15, (num10 * num9 - num11 * num8) * num15); + array2[num] += vector7; + array2[num2] += vector7; + array2[num3] += vector7; + array3[num] += vector8; + array3[num2] += vector8; + array3[num3] += vector8; + } + for (int j = 0; j < vertexCount; j++) + { + Vector3 normal = ((!planetFlag) ? normals[j] : Vector3.Normalize(vertices[j])); + Vector3 tangent = array2[j]; + Vector3.OrthoNormalize(ref normal, ref tangent); + array[j].x = tangent.x; + array[j].y = tangent.y; + array[j].z = tangent.z; + array[j].w = ((!(Vector3.Dot(Vector3.Cross(normal, tangent), array3[j]) < 0f)) ? 1f : (-1f)); + } + theMesh.tangents = array; + } +} diff --git a/RTP_DeferredParams.cs b/RTP_DeferredParams.cs new file mode 100644 index 0000000..2730d4a --- /dev/null +++ b/RTP_DeferredParams.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Rendering; + +[AddComponentMenu("Relief Terrain/Helpers/Deferred Params")] +[RequireComponent(typeof(Camera))] +[DisallowMultipleComponent] +[ExecuteInEditMode] +public class RTP_DeferredParams : MonoBehaviour +{ + private Camera mycam; + + private CommandBuffer combufPreLight; + + private CommandBuffer combufPostLight; + + public Material CopyPropsMat; + + private HashSet<Camera> sceneCamsWithBuffer = new HashSet<Camera>(); + + public void OnEnable() + { + if (NotifyDecals()) + { + return; + } + if (mycam == null) + { + mycam = GetComponent<Camera>(); + if (mycam == null) + { + return; + } + } + Initialize(); + Camera.onPreRender = (Camera.CameraCallback)Delegate.Combine(Camera.onPreRender, new Camera.CameraCallback(SetupCam)); + } + + public void OnDisable() + { + NotifyDecals(); + Cleanup(); + } + + public void OnDestroy() + { + NotifyDecals(); + Cleanup(); + } + + private bool NotifyDecals() + { + Type type = Type.GetType("UBERDecalSystem.DecalManager"); + if (type != null) + { + bool flag = false; + if (UnityEngine.Object.FindObjectOfType(type) != null && UnityEngine.Object.FindObjectOfType(type) is MonoBehaviour && (UnityEngine.Object.FindObjectOfType(type) as MonoBehaviour).enabled) + { + (UnityEngine.Object.FindObjectOfType(type) as MonoBehaviour).Invoke("OnDisable", 0f); + (UnityEngine.Object.FindObjectOfType(type) as MonoBehaviour).Invoke("OnEnable", 0f); + return true; + } + } + return false; + } + + private void Cleanup() + { + if (combufPreLight != null) + { + if ((bool)mycam) + { + mycam.RemoveCommandBuffer(CameraEvent.BeforeReflections, combufPreLight); + mycam.RemoveCommandBuffer(CameraEvent.AfterLighting, combufPostLight); + } + foreach (Camera item in sceneCamsWithBuffer) + { + if ((bool)item) + { + item.RemoveCommandBuffer(CameraEvent.BeforeReflections, combufPreLight); + item.RemoveCommandBuffer(CameraEvent.AfterLighting, combufPostLight); + } + } + } + sceneCamsWithBuffer.Clear(); + Camera.onPreRender = (Camera.CameraCallback)Delegate.Remove(Camera.onPreRender, new Camera.CameraCallback(SetupCam)); + } + + private void SetupCam(Camera cam) + { + bool flag = false; + if (cam == mycam || flag) + { + RefreshComBufs(cam, flag); + } + } + + public void RefreshComBufs(Camera cam, bool isSceneCam) + { + if (!cam || combufPreLight == null || combufPostLight == null) + { + return; + } + CommandBuffer[] commandBuffers = cam.GetCommandBuffers(CameraEvent.BeforeReflections); + bool flag = false; + CommandBuffer[] array = commandBuffers; + foreach (CommandBuffer commandBuffer in array) + { + if (commandBuffer.name == combufPreLight.name) + { + flag = true; + break; + } + } + if (!flag) + { + cam.AddCommandBuffer(CameraEvent.BeforeReflections, combufPreLight); + cam.AddCommandBuffer(CameraEvent.AfterLighting, combufPostLight); + if (isSceneCam) + { + sceneCamsWithBuffer.Add(cam); + } + } + } + + public void Initialize() + { + if (combufPreLight != null) + { + return; + } + int num = Shader.PropertyToID("_UBERPropsBuffer"); + if (CopyPropsMat == null) + { + if (CopyPropsMat != null) + { + UnityEngine.Object.DestroyImmediate(CopyPropsMat); + } + CopyPropsMat = new Material(Shader.Find("Hidden/UBER_CopyPropsTexture")); + CopyPropsMat.hideFlags = HideFlags.DontSave; + } + combufPreLight = new CommandBuffer(); + combufPreLight.name = "UBERPropsPrelight"; + combufPreLight.GetTemporaryRT(num, -1, -1, 0, FilterMode.Point, RenderTextureFormat.RHalf); + combufPreLight.Blit(BuiltinRenderTextureType.CameraTarget, num, CopyPropsMat); + combufPostLight = new CommandBuffer(); + combufPostLight.name = "UBERPropsPostlight"; + combufPostLight.ReleaseTemporaryRT(num); + } +} diff --git a/RTP_LODmanager.cs b/RTP_LODmanager.cs new file mode 100644 index 0000000..e14bd77 --- /dev/null +++ b/RTP_LODmanager.cs @@ -0,0 +1,378 @@ +using UnityEngine; + +public class RTP_LODmanager : MonoBehaviour +{ + public TerrainShaderLod RTP_LODlevel; + + public bool RTP_SHADOWS = true; + + public bool RTP_SOFT_SHADOWS = true; + + public bool show_first_features; + + public bool show_add_features; + + public bool RTP_NOFORWARDADD; + + public bool RTP_NO_DEFERRED; + + public bool RTP_FULLFORWARDSHADOWS; + + public bool RTP_NOLIGHTMAP; + + public bool RTP_NODIRLIGHTMAP; + + public bool RTP_NODYNLIGHTMAP; + + public bool NO_SPECULARITY; + + public bool RTP_ADDSHADOW; + + public bool RTP_CUT_HOLES; + + public bool FIX_REFRESHING_ISSUE = true; + + public bool RTP_USE_COLOR_ATLAS_FIRST; + + public bool RTP_USE_COLOR_ATLAS_ADD; + + public RTPFogType RTP_FOGTYPE; + + public bool ADV_COLOR_MAP_BLENDING_FIRST; + + public bool ADV_COLOR_MAP_BLENDING_ADD; + + public bool RTP_UV_BLEND_FIRST = true; + + public bool RTP_UV_BLEND_ADD = true; + + public bool RTP_DISTANCE_ONLY_UV_BLEND_FIRST = true; + + public bool RTP_DISTANCE_ONLY_UV_BLEND_ADD = true; + + public bool RTP_NORMALS_FOR_REPLACE_UV_BLEND_FIRST = true; + + public bool RTP_NORMALS_FOR_REPLACE_UV_BLEND_ADD = true; + + public bool RTP_SUPER_DETAIL_FIRST = true; + + public bool RTP_SUPER_DETAIL_ADD = true; + + public bool RTP_SUPER_DETAIL_MULTS_FIRST; + + public bool RTP_SUPER_DETAIL_MULTS_ADD; + + public bool RTP_SNOW_FIRST; + + public bool RTP_SNOW_ADD; + + public bool RTP_SNW_CHOOSEN_LAYER_COLOR_FIRST; + + public bool RTP_SNW_CHOOSEN_LAYER_COLOR_ADD; + + public int RTP_SNW_CHOOSEN_LAYER_COLOR_NUM_FIRST = 7; + + public int RTP_SNW_CHOOSEN_LAYER_COLOR_NUM_ADD = 7; + + public bool RTP_SNW_CHOOSEN_LAYER_NORMAL_FIRST; + + public bool RTP_SNW_CHOOSEN_LAYER_NORMAL_ADD; + + public int RTP_SNW_CHOOSEN_LAYER_NORMAL_NUM_FIRST = 7; + + public int RTP_SNW_CHOOSEN_LAYER_NORMAL_NUM_ADD = 7; + + public RTPLodLevel MAX_LOD_FIRST = RTPLodLevel.PM; + + public RTPLodLevel MAX_LOD_FIRST_PLUS4 = RTPLodLevel.SIMPLE; + + public RTPLodLevel MAX_LOD_ADD = RTPLodLevel.PM; + + public bool RTP_SHARPEN_HEIGHTBLEND_EDGES_PASS1_FIRST = true; + + public bool RTP_SHARPEN_HEIGHTBLEND_EDGES_PASS2_FIRST; + + public bool RTP_SHARPEN_HEIGHTBLEND_EDGES_PASS1_ADD = true; + + public bool RTP_SHARPEN_HEIGHTBLEND_EDGES_PASS2_ADD; + + public bool RTP_HEIGHTBLEND_AO_FIRST; + + public bool RTP_HEIGHTBLEND_AO_ADD; + + public bool RTP_EMISSION_FIRST; + + public bool RTP_EMISSION_ADD; + + public bool RTP_FUILD_EMISSION_WRAP_FIRST; + + public bool RTP_FUILD_EMISSION_WRAP_ADD; + + public bool RTP_HOTAIR_EMISSION_FIRST; + + public bool RTP_HOTAIR_EMISSION_ADD; + + public bool RTP_SHOW_OVERLAPPED; + + public bool RTP_TRIPLANAR_FIRST; + + public bool RTP_TRIPLANAR_ADD; + + public bool RTP_NORMALGLOBAL; + + public bool RTP_TESSELLATION; + + public bool RTP_TESSELLATION_SAMPLE_TEXTURE; + + public bool RTP_HEIGHTMAP_SAMPLE_BICUBIC = true; + + public bool RTP_DETAIL_HEIGHTMAP_SAMPLE; + + public bool RTP_TREESGLOBAL; + + public bool RTP_USE_BUMPMAPS_FIRST = true; + + public bool RTP_USE_BUMPMAPS_ADD = true; + + public bool RTP_USE_PERLIN_FIRST; + + public bool RTP_USE_PERLIN_ADD; + + public bool RTP_COLOR_MAP_BLEND_MULTIPLY_FIRST = true; + + public bool RTP_COLOR_MAP_BLEND_MULTIPLY_ADD = true; + + public bool RTP_SIMPLE_FAR_FIRST = true; + + public bool RTP_SIMPLE_FAR_ADD = true; + + public bool RTP_CROSSPASS_HEIGHTBLEND; + + public int[] UV_BLEND_ROUTE_NUM_FIRST = new int[8] { 0, 1, 2, 3, 4, 5, 6, 7 }; + + public int[] UV_BLEND_ROUTE_NUM_ADD = new int[8] { 0, 1, 2, 3, 4, 5, 6, 7 }; + + public bool RTP_HARD_CROSSPASS = true; + + public bool RTP_MAPPED_SHADOWS_FIRST; + + public bool RTP_MAPPED_SHADOWS_ADD; + + public bool RTP_VERTICAL_TEXTURE_FIRST; + + public bool RTP_VERTICAL_TEXTURE_ADD; + + public bool RTP_ADDITIONAL_FEATURES_IN_FALLBACKS = true; + + public bool RTP_4LAYERS_MODE; + + public int numLayers; + + public int numLayersProcessedByFarShader = 8; + + public bool ADDPASS_IN_BLENDBASE; + + public bool RTP_GLITTER_FIRST; + + public bool RTP_GLITTER_ADD; + + public bool RTP_WETNESS_FIRST; + + public bool RTP_WETNESS_ADD; + + public bool RTP_WET_RIPPLE_TEXTURE_FIRST; + + public bool RTP_WET_RIPPLE_TEXTURE_ADD; + + public bool RTP_CAUSTICS_FIRST; + + public bool RTP_CAUSTICS_ADD; + + public bool RTP_VERTALPHA_CAUSTICS; + + public bool SIMPLE_WATER_FIRST; + + public bool SIMPLE_WATER_ADD; + + public bool RTP_USE_EXTRUDE_REDUCTION_FIRST; + + public bool RTP_USE_EXTRUDE_REDUCTION_ADD; + + private Shader terrain_shader; + + private Shader terrain_shader_far; + + private Shader terrain_shader_add; + + private Shader terrain2geom_shader; + + private Shader terrain_geomBlend_shader; + + private Shader terrain2geom_geomBlend_shader; + + private Shader terrain_geomBlend_GeometryBlend_BumpedDetailSnow; + + private Shader geomblend_GeometryBlend_WaterShader_2VertexPaint_HB; + + private Shader geomBlend_GeometryBlend_WaterShader_FlowMap_HB; + + private Shader terrain_geomBlendActual_shader; + + public bool dont_sync; + + private void Awake() + { + RefreshLODlevel(); + } + + public void RefreshLODlevel() + { + ReliefTerrain[] array = (ReliefTerrain[])Object.FindObjectsOfType(typeof(ReliefTerrain)); + ReliefTerrain reliefTerrain = null; + for (int i = 0; i < array.Length; i++) + { + if ((bool)array[i].GetComponent(typeof(Terrain))) + { + reliefTerrain = array[i]; + break; + } + } + if (reliefTerrain != null && reliefTerrain.globalSettingsHolder != null) + { + if (terrain_shader == null) + { + terrain_shader = Shader.Find("Relief Pack/ReliefTerrain-FirstPass"); + } + if (terrain_shader_add == null) + { + terrain_shader_add = Shader.Find("Hidden/Relief Pack/ReliefTerrain-AddPass"); + } + } + else + { + if (terrain_shader == null) + { + terrain_shader = Shader.Find("Hidden/TerrainEngine/Splatmap/Lightmap-FirstPass"); + } + if (terrain_shader_add == null) + { + terrain_shader_add = Shader.Find("Hidden/TerrainEngine/Splatmap/Lightmap-AddPass"); + } + if (terrain_shader == null) + { + terrain_shader = Shader.Find("Nature/Terrain/Diffuse"); + } + if (terrain_shader_add == null) + { + terrain_shader_add = Shader.Find("Hidden/TerrainEngine/Splatmap/Diffuse-AddPass"); + } + } + if (terrain_shader_far == null) + { + terrain_shader_far = Shader.Find("Hidden/Relief Pack/ReliefTerrain-FarOnly"); + } + if (terrain2geom_shader == null) + { + terrain2geom_shader = Shader.Find("Relief Pack/Terrain2Geometry"); + } + if (terrain_geomBlend_shader == null) + { + terrain_geomBlend_shader = Shader.Find("Hidden/Relief Pack/ReliefTerrainGeometryBlendBase"); + } + if (terrain2geom_geomBlend_shader == null) + { + terrain2geom_geomBlend_shader = Shader.Find("Hidden/Relief Pack/ReliefTerrain2GeometryBlendBase"); + } + if (terrain_geomBlend_GeometryBlend_BumpedDetailSnow == null) + { + terrain_geomBlend_GeometryBlend_BumpedDetailSnow = Shader.Find("Relief Pack - GeometryBlend/Bumped Detail Snow"); + } + if (geomblend_GeometryBlend_WaterShader_2VertexPaint_HB == null) + { + geomblend_GeometryBlend_WaterShader_2VertexPaint_HB = Shader.Find("Relief Pack - GeometryBlend/Water/2 Layers/ HeightBlend"); + } + if (geomBlend_GeometryBlend_WaterShader_FlowMap_HB == null) + { + geomBlend_GeometryBlend_WaterShader_FlowMap_HB = Shader.Find("Relief Pack - GeometryBlend/Water/ FlowMap - HeightBlend"); + } + int maximumLOD = 700; + if (RTP_LODlevel == TerrainShaderLod.POM) + { + if (RTP_SHADOWS) + { + if (RTP_SOFT_SHADOWS) + { + Shader.EnableKeyword("RTP_POM_SHADING_HI"); + Shader.DisableKeyword("RTP_POM_SHADING_MED"); + Shader.DisableKeyword("RTP_POM_SHADING_LO"); + } + else + { + Shader.EnableKeyword("RTP_POM_SHADING_MED"); + Shader.DisableKeyword("RTP_POM_SHADING_HI"); + Shader.DisableKeyword("RTP_POM_SHADING_LO"); + } + } + else + { + Shader.EnableKeyword("RTP_POM_SHADING_LO"); + Shader.DisableKeyword("RTP_POM_SHADING_MED"); + Shader.DisableKeyword("RTP_POM_SHADING_HI"); + } + Shader.DisableKeyword("RTP_PM_SHADING"); + Shader.DisableKeyword("RTP_SIMPLE_SHADING"); + } + else if (RTP_LODlevel == TerrainShaderLod.PM) + { + Shader.DisableKeyword("RTP_POM_SHADING_HI"); + Shader.DisableKeyword("RTP_POM_SHADING_MED"); + Shader.DisableKeyword("RTP_POM_SHADING_LO"); + Shader.EnableKeyword("RTP_PM_SHADING"); + Shader.DisableKeyword("RTP_SIMPLE_SHADING"); + } + else + { + Shader.DisableKeyword("RTP_POM_SHADING_HI"); + Shader.DisableKeyword("RTP_POM_SHADING_MED"); + Shader.DisableKeyword("RTP_POM_SHADING_LO"); + Shader.DisableKeyword("RTP_PM_SHADING"); + Shader.EnableKeyword("RTP_SIMPLE_SHADING"); + } + if (terrain_shader != null) + { + terrain_shader.maximumLOD = maximumLOD; + } + if (terrain_shader_far != null) + { + terrain_shader_far.maximumLOD = maximumLOD; + } + if (terrain_shader_add != null) + { + terrain_shader_add.maximumLOD = maximumLOD; + } + if (terrain2geom_shader != null) + { + terrain2geom_shader.maximumLOD = maximumLOD; + } + if (terrain_geomBlend_shader != null) + { + terrain_geomBlend_shader.maximumLOD = maximumLOD; + } + if (terrain2geom_geomBlend_shader != null) + { + terrain2geom_geomBlend_shader.maximumLOD = maximumLOD; + } + if (terrain_geomBlend_GeometryBlend_BumpedDetailSnow != null) + { + terrain_geomBlend_GeometryBlend_BumpedDetailSnow.maximumLOD = maximumLOD; + } + if (geomblend_GeometryBlend_WaterShader_2VertexPaint_HB != null) + { + geomblend_GeometryBlend_WaterShader_2VertexPaint_HB.maximumLOD = maximumLOD; + } + if (geomBlend_GeometryBlend_WaterShader_FlowMap_HB != null) + { + geomBlend_GeometryBlend_WaterShader_FlowMap_HB.maximumLOD = maximumLOD; + } + } +} diff --git a/RTP_MouseOrbit_DynamicDistance.cs b/RTP_MouseOrbit_DynamicDistance.cs new file mode 100644 index 0000000..2965b07 --- /dev/null +++ b/RTP_MouseOrbit_DynamicDistance.cs @@ -0,0 +1,234 @@ +using UnityEngine; + +[AddComponentMenu("Relief Terrain/Helpers/Mouse Orbit - Dynamic Distance")] +public class RTP_MouseOrbit_DynamicDistance : MonoBehaviour +{ + public GameObject target; + + public Transform targetFocus; + + public float distance = 1f; + + [Range(0.1f, 8f)] + public float ZoomWheelSpeed = 4f; + + public float minDistance = 0.5f; + + public float maxDistance = 10f; + + public float xSpeed = 250f; + + public float ySpeed = 120f; + + public float xObjSpeed = 250f; + + public float yObjSpeed = 120f; + + public float yMinLimit = -20f; + + public float yMaxLimit = 80f; + + private float x; + + private float y; + + private float normal_angle; + + private float cur_distance; + + private float cur_xSpeed; + + private float cur_ySpeed; + + private float req_xSpeed; + + private float req_ySpeed; + + private float cur_ObjxSpeed; + + private float cur_ObjySpeed; + + private float req_ObjxSpeed; + + private float req_ObjySpeed; + + private bool DraggingObject; + + private bool lastLMBState; + + private Collider[] surfaceColliders; + + private float bounds_MaxSize = 20f; + + [HideInInspector] + public bool disableSteering; + + private void Start() + { + Vector3 eulerAngles = base.transform.eulerAngles; + x = eulerAngles.y; + y = eulerAngles.x; + Reset(); + } + + public void DisableSteering(bool state) + { + disableSteering = state; + } + + public void Reset() + { + lastLMBState = Input.GetMouseButton(0); + disableSteering = false; + cur_distance = distance; + cur_xSpeed = 0f; + cur_ySpeed = 0f; + req_xSpeed = 0f; + req_ySpeed = 0f; + surfaceColliders = null; + cur_ObjxSpeed = 0f; + cur_ObjySpeed = 0f; + req_ObjxSpeed = 0f; + req_ObjySpeed = 0f; + if (!target) + { + return; + } + Renderer[] componentsInChildren = target.GetComponentsInChildren<Renderer>(); + Bounds bounds = default(Bounds); + bool flag = false; + Renderer[] array = componentsInChildren; + foreach (Renderer renderer in array) + { + if (!flag) + { + flag = true; + bounds = renderer.bounds; + } + else + { + bounds.Encapsulate(renderer.bounds); + } + } + Vector3 size = bounds.size; + float num = ((!(size.x > size.y)) ? size.y : size.x); + num = ((!(size.z > num)) ? num : size.z); + bounds_MaxSize = num; + cur_distance += bounds_MaxSize * 1.2f; + surfaceColliders = target.GetComponentsInChildren<Collider>(); + } + + private void LateUpdate() + { + if (!target || !targetFocus) + { + return; + } + if (!lastLMBState && Input.GetMouseButton(0)) + { + DraggingObject = false; + if (surfaceColliders != null) + { + RaycastHit hitInfo = default(RaycastHit); + Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); + Collider[] array = surfaceColliders; + foreach (Collider collider in array) + { + if (collider.Raycast(ray, out hitInfo, float.PositiveInfinity)) + { + DraggingObject = true; + break; + } + } + } + } + else if (lastLMBState && !Input.GetMouseButton(0)) + { + DraggingObject = false; + } + lastLMBState = Input.GetMouseButton(0); + if (DraggingObject) + { + if (Input.GetMouseButton(0) && !disableSteering) + { + req_ObjxSpeed += (Input.GetAxis("Mouse X") * xObjSpeed * 0.02f - req_ObjxSpeed) * Time.deltaTime * 10f; + req_ObjySpeed += (Input.GetAxis("Mouse Y") * yObjSpeed * 0.02f - req_ObjySpeed) * Time.deltaTime * 10f; + } + else + { + req_ObjxSpeed += (0f - req_ObjxSpeed) * Time.deltaTime * 4f; + req_ObjySpeed += (0f - req_ObjySpeed) * Time.deltaTime * 4f; + } + req_xSpeed += (0f - req_xSpeed) * Time.deltaTime * 4f; + req_ySpeed += (0f - req_ySpeed) * Time.deltaTime * 4f; + } + else + { + if (Input.GetMouseButton(0) && !disableSteering) + { + req_xSpeed += (Input.GetAxis("Mouse X") * xSpeed * 0.02f - req_xSpeed) * Time.deltaTime * 10f; + req_ySpeed += (Input.GetAxis("Mouse Y") * ySpeed * 0.02f - req_ySpeed) * Time.deltaTime * 10f; + } + else + { + req_xSpeed += (0f - req_xSpeed) * Time.deltaTime * 4f; + req_ySpeed += (0f - req_ySpeed) * Time.deltaTime * 4f; + } + req_ObjxSpeed += (0f - req_ObjxSpeed) * Time.deltaTime * 4f; + req_ObjySpeed += (0f - req_ObjySpeed) * Time.deltaTime * 4f; + } + distance -= Input.GetAxis("Mouse ScrollWheel") * ZoomWheelSpeed; + distance = Mathf.Clamp(distance, minDistance, maxDistance); + cur_ObjxSpeed += (req_ObjxSpeed - cur_ObjxSpeed) * Time.deltaTime * 20f; + cur_ObjySpeed += (req_ObjySpeed - cur_ObjySpeed) * Time.deltaTime * 20f; + target.transform.RotateAround(targetFocus.position, Vector3.Cross(targetFocus.position - base.transform.position, base.transform.right), 0f - cur_ObjxSpeed); + target.transform.RotateAround(targetFocus.position, Vector3.Cross(targetFocus.position - base.transform.position, base.transform.up), 0f - cur_ObjySpeed); + cur_xSpeed += (req_xSpeed - cur_xSpeed) * Time.deltaTime * 20f; + cur_ySpeed += (req_ySpeed - cur_ySpeed) * Time.deltaTime * 20f; + x += cur_xSpeed; + y -= cur_ySpeed; + y = ClampAngle(y, yMinLimit + normal_angle, yMaxLimit + normal_angle); + if (surfaceColliders != null) + { + RaycastHit hitInfo2 = default(RaycastHit); + Vector3 vector = Vector3.Normalize(targetFocus.position - base.transform.position); + float num = 0.01f; + bool flag = false; + Collider[] array2 = surfaceColliders; + foreach (Collider collider2 in array2) + { + if (collider2.Raycast(new Ray(base.transform.position - vector * bounds_MaxSize, vector), out hitInfo2, float.PositiveInfinity)) + { + num = Mathf.Max(Vector3.Distance(hitInfo2.point, targetFocus.position) + distance, num); + flag = true; + } + } + if (flag) + { + cur_distance += (num - cur_distance) * Time.deltaTime * 4f; + } + } + Quaternion quaternion = Quaternion.Euler(y, x, 0f); + Vector3 position = quaternion * new Vector3(0f, 0f, 0f - cur_distance) + targetFocus.position; + base.transform.rotation = quaternion; + base.transform.position = position; + } + + private static float ClampAngle(float angle, float min, float max) + { + if (angle < -360f) + { + angle += 360f; + } + if (angle > 360f) + { + angle -= 360f; + } + return Mathf.Clamp(angle, min, max); + } + + public void set_normal_angle(float a) + { + normal_angle = a; + } +} diff --git a/RTP_TintDielectricColor.cs b/RTP_TintDielectricColor.cs new file mode 100644 index 0000000..9a6bdcd --- /dev/null +++ b/RTP_TintDielectricColor.cs @@ -0,0 +1,24 @@ +using UnityEngine; + +[AddComponentMenu("Relief Terrain/Helpers/Tint dielectric color")] +public class RTP_TintDielectricColor : MonoBehaviour +{ + [Tooltip("You can reduce/increase reflectivity by tinting default unity_ColorSpaceDielectricSpec.rgb color")] + [ColorUsage(false)] + public Color DielectricTint = new Color(0.2f, 0.2f, 0.2f, 1f); + + private void Awake() + { + SetDielectricColorTint(); + } + + private void OnValidate() + { + SetDielectricColorTint(); + } + + public void SetDielectricColorTint() + { + Shader.SetGlobalColor("RTP_ColorSpaceDielectricSpecTint", DielectricTint); + } +} diff --git a/RagdollHandler.cs b/RagdollHandler.cs new file mode 100644 index 0000000..ca52b8d --- /dev/null +++ b/RagdollHandler.cs @@ -0,0 +1,21 @@ +using UnityEngine; + +public class RagdollHandler : MonoBehaviour +{ + public float ragdollValue = 1f; + + private RigidbodyHolder rigs; + + private void Start() + { + rigs = GetComponent<RigidbodyHolder>(); + } + + private void Update() + { + for (int i = 0; i < rigs.GetAllRigs().Length; i++) + { + rigs.GetAllRigs()[i].GetComponent<DragHandler>().dragAmount = ragdollValue; + } + } +} diff --git a/RandomTable.cs b/RandomTable.cs new file mode 100644 index 0000000..cd86ec3 --- /dev/null +++ b/RandomTable.cs @@ -0,0 +1,109 @@ +public class RandomTable +{ + public static float[] Values = new float[1024] + { + 0.4639f, 0.34f, 0.223f, 0.4684f, 0.3222f, 0.9792f, 0.0317f, 0.9733f, 0.7783f, 0.4561f, + 0.2585f, 0.33f, 0.3873f, 0.3801f, 0.1798f, 0.9107f, 0.5116f, 0.0929f, 0.1807f, 0.6201f, + 0.1013f, 0.5563f, 0.6424f, 0.442f, 0.2151f, 0.4752f, 0.1573f, 0.5688f, 0.5012f, 0.6292f, + 0.6992f, 0.7077f, 0.5567f, 0.0055f, 0.7083f, 0.5831f, 0.2366f, 0.9923f, 0.981f, 0.1198f, + 0.5108f, 0.5604f, 0.9614f, 0.5578f, 0.5399f, 0.3328f, 0.4178f, 0.9207f, 0.7307f, 0.0766f, + 0.0085f, 0.6601f, 0.4289f, 0.5113f, 0.5878f, 0.9064f, 0.4379f, 0.6203f, 0.0621f, 0.1194f, + 0.2356f, 0.7958f, 0.0444f, 0.6173f, 0.8911f, 0.2631f, 0.2452f, 0.2765f, 0.7869f, 0.0597f, + 0.4243f, 0.4333f, 0.0521f, 0.6999f, 0.1394f, 0.4028f, 0.7419f, 0.5579f, 0.127f, 0.9463f, + 0.2055f, 0.0928f, 0.4229f, 0.7151f, 0.7119f, 0.926f, 0.3686f, 0.2865f, 0.2414f, 0.8316f, + 0.2322f, 0.4786f, 0.3669f, 0.432f, 0.2684f, 0.6191f, 0.3917f, 0.0566f, 0.0677f, 0.509f, + 0.9208f, 0.2983f, 0.701f, 0.0443f, 0.9367f, 0.4859f, 0.2712f, 0.1087f, 0.3258f, 0.6823f, + 0.955f, 0.6581f, 0.2958f, 0.5625f, 0.8671f, 0.8105f, 0.4879f, 0.8695f, 0.2247f, 0.9626f, + 0.6465f, 0.0037f, 0.2288f, 0.2636f, 0.3651f, 0.9583f, 0.6066f, 0.9018f, 0.7572f, 0.306f, + 0.6331f, 0.4076f, 0.4436f, 0.9799f, 0.9229f, 0.9464f, 0.594f, 0.6043f, 0.8642f, 0.1875f, + 0.8771f, 0.792f, 0.9548f, 0.9767f, 0.3505f, 0.8347f, 0.9451f, 0.1558f, 0.4118f, 0.5523f, + 0.8554f, 0.7413f, 0.7612f, 0.8962f, 0.782f, 0.2662f, 0.1288f, 0.6457f, 0.5915f, 0.2473f, + 0.2608f, 0.8119f, 0.6533f, 0.9767f, 0.2215f, 0.9574f, 0.294f, 0.159f, 0.8205f, 0.5696f, + 0.9343f, 0.4671f, 0.7631f, 0.8357f, 0.24f, 0.3898f, 0.9987f, 0.7837f, 0.758f, 0.6143f, + 0.2211f, 0.5024f, 0.978f, 0.2477f, 0.6195f, 0.6583f, 0.7696f, 0.7684f, 0.3371f, 0.3706f, + 0.0847f, 0.5105f, 0.5949f, 0.9946f, 0.1812f, 0.8681f, 0.312f, 0.4804f, 0.1773f, 0.3673f, + 0.7416f, 0.2029f, 0.2294f, 0.1081f, 0.0986f, 0.0104f, 0.7273f, 0.9422f, 0.0238f, 0.1106f, + 0.9582f, 0.2089f, 0.5846f, 0.4918f, 0.2382f, 0.5915f, 0.2974f, 0.6814f, 0.215f, 0.5877f, + 0.7044f, 0.9789f, 0.9116f, 0.6926f, 0.4629f, 0.2732f, 0.8028f, 0.6516f, 0.7367f, 0.9862f, + 0.4023f, 0.524f, 0.7404f, 0.799f, 0.9182f, 0.7053f, 0.4774f, 0.1022f, 0.8099f, 0.8606f, + 0.1182f, 0.0095f, 0.2801f, 0.9484f, 0.0254f, 0.4581f, 0.5126f, 0.082f, 0.5369f, 0.4725f, + 0.8357f, 0.0785f, 0.3579f, 0.7975f, 0.5705f, 0.1627f, 0.8159f, 0.8741f, 0.9153f, 0.392f, + 0.3663f, 0.7662f, 0.4627f, 0.0876f, 0.4023f, 0.2776f, 0.2941f, 0.3927f, 0.5048f, 0.2634f, + 0.5091f, 0.5189f, 0.7388f, 0.9658f, 0.0038f, 0.9768f, 0.2922f, 0.8371f, 0.5254f, 0.7437f, + 0.359f, 0.0606f, 0.5954f, 0.4831f, 0.9001f, 0.4232f, 0.9819f, 0.1549f, 0.0855f, 0.6815f, + 0.8144f, 0.1059f, 0.9722f, 0.207f, 0.9946f, 0.9892f, 0.6462f, 0.3302f, 0.432f, 0.1399f, + 0.9086f, 0.2715f, 0.5393f, 0.8451f, 0.14f, 0.0014f, 0.3401f, 0.5822f, 0.6935f, 0.2931f, + 0.7334f, 0.3755f, 0.676f, 0.1306f, 0.6065f, 0.441f, 0.1135f, 0.8444f, 0.3999f, 0.551f, + 0.4827f, 0.8948f, 0.1889f, 0.431f, 0.0436f, 0.3946f, 0.5443f, 0.7987f, 0.0404f, 0.0222f, + 0.6812f, 0.5983f, 0.0699f, 0.2556f, 0.1747f, 0.8808f, 0.412f, 0.3979f, 0.9328f, 0.9794f, + 0.2442f, 0.488f, 0.3137f, 0.8581f, 0.3909f, 0.4261f, 0.7548f, 0.3607f, 0.8628f, 0.5264f, + 0.09f, 0.6739f, 0.715f, 0.2374f, 0.2102f, 0.9528f, 0.4484f, 0.738f, 0.0773f, 0.2606f, + 0.5904f, 0.1275f, 0.6289f, 0.1362f, 0.8601f, 0.5967f, 0.524f, 0.8971f, 0.6488f, 0.1167f, + 0.6668f, 0.5369f, 0.8117f, 0.8549f, 0.8572f, 0.945f, 0.4341f, 0.6023f, 0.8237f, 0.1094f, + 0.6846f, 0.1955f, 0.2136f, 0.2835f, 0.387f, 0.182f, 0.8346f, 0.9489f, 0.3731f, 0.2497f, + 0.1625f, 0.5878f, 0.1926f, 0.7378f, 0.7774f, 0.6514f, 0.5625f, 0.9183f, 0.0948f, 0.2606f, + 0.6294f, 0.7513f, 0.3622f, 0.6496f, 0.3973f, 0.6706f, 0.2156f, 0.9254f, 0.9083f, 0.4868f, + 0.141f, 0.2361f, 0.9263f, 0.416f, 0.7814f, 0.5385f, 0.1195f, 0.0041f, 0.8475f, 0.8767f, + 0.9455f, 0.935f, 0.422f, 0.5028f, 0.9325f, 0.1166f, 0.7008f, 0.9955f, 0.3349f, 0.1746f, + 0.9828f, 0.1741f, 0.7342f, 0.7693f, 0.9175f, 0.3826f, 0.7958f, 0.0518f, 0.5281f, 0.6919f, + 0.3379f, 0.6756f, 0.9694f, 0.3549f, 0.0545f, 0.2542f, 0.9788f, 0.6112f, 0.89f, 0.7126f, + 0.2196f, 0.8264f, 0.3511f, 0.0873f, 0.8625f, 0.8054f, 0.4993f, 0.4821f, 0.0364f, 0.8156f, + 0.0165f, 0.8759f, 0.3083f, 0.65f, 0.4941f, 0.6159f, 0.3967f, 0.9216f, 0.1646f, 0.4727f, + 0.5598f, 0.6756f, 0.0598f, 0.2957f, 0.818f, 0.7693f, 0.1586f, 0.6481f, 0.2287f, 0.6274f, + 0.1385f, 0.6394f, 0.2003f, 0.3523f, 0.4707f, 0.8886f, 0.3117f, 0.5711f, 0.9793f, 0.4572f, + 0.1151f, 0.7256f, 0.6205f, 0.6293f, 0.8502f, 0.9499f, 0.2546f, 0.1423f, 0.6888f, 0.3072f, + 0.2848f, 0.8476f, 0.617f, 0.2074f, 0.5505f, 0.5418f, 0.1738f, 0.4748f, 0.6783f, 0.2891f, + 0.5281f, 0.3065f, 0.8693f, 0.0402f, 0.4173f, 0.4725f, 0.8576f, 0.9174f, 0.8423f, 0.9868f, + 0.6045f, 0.7311f, 0.6078f, 0.9046f, 0.3979f, 0.6278f, 0.5333f, 0.6567f, 0.6272f, 0.2235f, + 0.2684f, 0.2548f, 0.8343f, 0.131f, 0.838f, 0.6135f, 0.8216f, 0.8597f, 0.4052f, 0.9099f, + 0.0361f, 0.643f, 0.187f, 0.9457f, 0.319f, 0.709f, 0.8522f, 0.5595f, 0.8657f, 0.3688f, + 0.8404f, 0.9505f, 0.3151f, 0.3317f, 0.5092f, 0.4686f, 0.119f, 0.5418f, 0.9834f, 0.1155f, + 0.2998f, 0.8403f, 0.4452f, 0.9007f, 0.6336f, 0.3041f, 0.9961f, 0.844f, 0.4623f, 0.3144f, + 0.85f, 0.7736f, 0.9583f, 0.7653f, 0.5675f, 0.7226f, 0.0012f, 0.1896f, 0.3646f, 0.1923f, + 0.8368f, 0.7836f, 0.0267f, 0.0652f, 0.5887f, 0.9377f, 0.9936f, 0.5974f, 0.8519f, 0.6703f, + 0.3609f, 0.7556f, 0.5715f, 0.2319f, 0.425f, 0.1164f, 0.3218f, 0.6296f, 0.7012f, 0.7169f, + 0.1463f, 0.3605f, 0.4984f, 0.846f, 0.3079f, 0.3234f, 0.2888f, 0.4779f, 0.2364f, 0.8765f, + 0.6674f, 0.9771f, 0.1793f, 0.4794f, 0.6332f, 0.9576f, 0.3436f, 0.8718f, 0.4528f, 0.8954f, + 0.3276f, 0.8677f, 0.5968f, 0.907f, 0.4174f, 0.5307f, 0.5474f, 0.141f, 0.721f, 0.5876f, + 0.83f, 0.4608f, 0.5638f, 0.6737f, 0.0358f, 0.7558f, 0.3318f, 0.6534f, 0.9263f, 0.7245f, + 0.9785f, 0.4952f, 0.0981f, 0.9367f, 0.1399f, 0.8513f, 0.8898f, 0.3765f, 0.6614f, 0.1564f, + 0.6718f, 0.4878f, 0.0465f, 0.4419f, 0.014f, 0.4404f, 0.2359f, 0.1637f, 0.0753f, 0.2547f, + 0.214f, 0.5548f, 0.7128f, 0.7957f, 0.4716f, 0.105f, 0.3559f, 0.8344f, 0.498f, 0.0183f, + 0.3647f, 0.9188f, 0.9092f, 0.8585f, 0.9282f, 0.9463f, 0.7553f, 0.4087f, 0.1378f, 0.2478f, + 0.3006f, 0.47f, 0.2487f, 0.5216f, 0.0098f, 0.8915f, 0.9089f, 0.2275f, 0.7029f, 0.5967f, + 0.5815f, 0.0999f, 0.8048f, 0.9474f, 0.0806f, 0.3757f, 0.8904f, 0.6891f, 0.6009f, 0.3822f, + 0.814f, 0.2583f, 0.278f, 0.9073f, 0.625f, 0.0166f, 0.5028f, 0.743f, 0.2478f, 0.8462f, + 0.6478f, 0.3798f, 0.5173f, 0.9214f, 0.9048f, 0.8056f, 0.6719f, 0.4872f, 0.678f, 0.5756f, + 0.9107f, 0.9476f, 0.5247f, 0.2312f, 0.299f, 0.0681f, 0.5696f, 0.121f, 0.7016f, 0.3119f, + 0.4473f, 0.014f, 0.0133f, 0.2578f, 0.4818f, 0.8088f, 0.6282f, 0.7802f, 0.2027f, 0.0249f, + 0.7743f, 0.783f, 0.33f, 0.7888f, 0.3468f, 0.7787f, 0.2619f, 0.6966f, 0.2128f, 0.7138f, + 0.8718f, 0.6397f, 0.711f, 0.6512f, 0.0423f, 0.2369f, 0.7462f, 0.235f, 0.4427f, 0.1954f, + 0.1759f, 0.9879f, 0.0312f, 0.9754f, 0.277f, 0.7526f, 0.6397f, 0.5078f, 0.8735f, 0.7753f, + 0.39f, 0.4159f, 0.2878f, 0.1893f, 0.8379f, 0.1862f, 0.3556f, 0.8037f, 0.0291f, 0.802f, + 0.248f, 0.354f, 0.4205f, 0.1095f, 0.7312f, 0.7006f, 0.716f, 0.6515f, 0.25f, 0.8842f, + 0.3642f, 0.2449f, 0.4722f, 0.0806f, 0.3093f, 0.2506f, 0.519f, 0.0661f, 0.0378f, 0.8657f, + 0.7677f, 0.6173f, 0.537f, 0.7439f, 0.4012f, 0.5954f, 0.8698f, 0.1939f, 0.6703f, 0.0184f, + 0.7431f, 0.9795f, 0.3823f, 0.191f, 0.9922f, 0.9461f, 0.3064f, 0.7937f, 0.6873f, 0.5562f, + 0.9583f, 0.3909f, 0.3578f, 0.1102f, 0.9775f, 0.8314f, 0.4858f, 0.1486f, 0.8473f, 0.7331f, + 0.3973f, 0.3763f, 0.3987f, 0.4638f, 0.9769f, 0.8447f, 0.0756f, 0.4738f, 0.4709f, 0.5481f, + 0.3501f, 0.7274f, 0.1231f, 0.3477f, 0.8395f, 0.5627f, 0.0368f, 0.5647f, 0.9603f, 0.2205f, + 0.9069f, 0.6776f, 0.841f, 0.1115f, 0.0323f, 0.0277f, 0.4682f, 0.2291f, 0.5087f, 0.1996f, + 0.2981f, 0.6772f, 0.526f, 0.8282f, 0.4133f, 0.3051f, 0.2233f, 0.778f, 0.198f, 0.4149f, + 0.0074f, 0.4642f, 0.7852f, 0.5344f, 0.0605f, 0.5724f, 0.6933f, 0.8658f, 0.0349f, 0.5868f, + 0.1617f, 0.2037f, 0.6565f, 0.6043f, 0.6883f, 0.2572f, 0.2464f, 0.3382f, 0.8399f, 0.2684f, + 0.9132f, 0.7595f, 0.2892f, 0.3472f, 0.5089f, 0.3615f, 0.5546f, 0.0864f, 0.0243f, 0.6616f, + 0.9888f, 0.1106f, 0.1294f, 0.4059f, 0.7817f, 0.3039f, 0.5218f, 0.2362f, 0.2779f, 0.6992f, + 0.7338f, 0.772f, 0.6584f, 0.0563f, 0.153f, 0.5368f, 0.7922f, 0.1652f, 0.5922f, 0.2283f, + 0.147f, 0.116f, 0.3192f, 0.2934f, 0.8726f, 0.8422f, 0.3062f, 0.2287f, 0.7457f, 0.8213f, + 0.7782f, 0.6113f, 0.9691f, 0.2976f, 0.3673f, 0.815f, 0.9858f, 0.6932f, 0.4117f, 0.3666f, + 0.3454f, 0.609f, 0.7789f, 0.6408f, 0.3409f, 0.3284f, 0.8986f, 0.9523f, 0.2725f, 0.7589f, + 0.1112f, 0.6134f, 0.8643f, 0.6076f, 0.3573f, 0.2276f, 0.177f, 0.7738f, 0.3182f, 0.2983f, + 0.6793f, 0.4546f, 0.9767f, 0.2445f, 0.8801f, 0.0462f, 0.4513f, 0.7092f, 0.7841f, 0.4883f, + 0.2287f, 0.0412f, 0.0774f, 0.7188f, 0.4542f, 0.0391f, 0.6147f, 0.5386f, 0.8566f, 0.8889f, + 0.184f, 0.4879f, 0.8803f, 0.7268f, 0.1129f, 0.8357f, 0.9433f, 0.34f, 0.1679f, 0.2412f, + 0.1259f, 0.4601f, 0.7899f, 0.3138f, 0.6407f, 0.7959f, 0.198f, 0.4073f, 0.6738f, 0.4143f, + 0.1859f, 0.3534f, 0.7867f, 0.4221f, 0.1339f, 0.3632f, 0.3938f, 0.7487f, 0.3281f, 0.1156f, + 0.2538f, 0.5269f, 0.6727f, 0.5174f, 0.6864f, 0.5328f, 0.5511f, 0.6674f, 0.3826f, 0.4087f, + 0.6494f, 0.6139f, 0.6004f, 0.4854f + }; +} diff --git a/RandomizeRotation.cs b/RandomizeRotation.cs new file mode 100644 index 0000000..0186111 --- /dev/null +++ b/RandomizeRotation.cs @@ -0,0 +1,11 @@ +using UnityEngine; + +public class RandomizeRotation : MonoBehaviour +{ + public float spread; + + private void Start() + { + base.transform.Rotate(Random.insideUnitSphere.normalized, Random.Range(0f - spread, spread)); + } +} diff --git a/RaycastTrail.cs b/RaycastTrail.cs new file mode 100644 index 0000000..e619f0d --- /dev/null +++ b/RaycastTrail.cs @@ -0,0 +1,29 @@ +using UnityEngine; + +public class RaycastTrail : MonoBehaviour +{ + private ProjectileHit hit; + + private Vector3 lastPosition; + + private SpawnerHolder spawnerHolder; + + private void Start() + { + hit = GetComponent<ProjectileHit>(); + spawnerHolder = GetComponent<SpawnerHolder>(); + lastPosition = base.transform.position; + } + + private void LateUpdate() + { + Vector3 direction = base.transform.position - lastPosition; + Ray ray = new Ray(lastPosition, direction); + Physics.Raycast(ray, out var hitInfo, Vector3.Distance(base.transform.position, lastPosition)); + if ((bool)hitInfo.collider) + { + hit.Hit(hitInfo); + } + lastPosition = base.transform.position; + } +} diff --git a/Recoil.cs b/Recoil.cs new file mode 100644 index 0000000..ee047f1 --- /dev/null +++ b/Recoil.cs @@ -0,0 +1,64 @@ +using UnityEngine; + +public class Recoil : MonoBehaviour +{ + public float ADSMovementMultiplier = 0.5f; + + [Header("")] + public Vector3 gunForce; + + public Vector3 gunForceRandom; + + [Header("")] + public Vector3 gunTorque; + + public Vector3 gunTorqueRandom; + + [Header("")] + private Rigidbody rig; + + [Header("")] + public Vector2 recoil; + + public Vector2 randomRecoil; + + public AnimationCurve recoilCurve; + + private CameraRecoil cameraRecoil; + + private HoldableObject holdableObject; + + private ADS ads; + + private void Start() + { + rig = GetComponent<Rigidbody>(); + holdableObject = GetComponent<HoldableObject>(); + ads = GetComponentInChildren<ADS>(); + } + + private void Update() + { + if (!holdableObject.isHeld && (bool)cameraRecoil) + { + cameraRecoil = null; + } + } + + public void AddRecoil(bool ADS) + { + if (!cameraRecoil) + { + cameraRecoil = holdableObject.holder.GetComponentInChildren<CameraRecoil>(); + } + ads.PlayRecoilAnimation(); + cameraRecoil.AddRecoil(recoil + new Vector2(Random.Range(0f - randomRecoil.x, randomRecoil.x), Random.Range(0f - randomRecoil.y, randomRecoil.y)), recoilCurve); + float num = 1f; + if (ADS) + { + num = ADSMovementMultiplier; + } + rig.AddForce(base.transform.TransformDirection(gunForce + new Vector3(Random.Range(0f - gunForceRandom.x, gunForceRandom.x), Random.Range(0f - gunForceRandom.y, gunForceRandom.y), Random.Range(0f - gunForceRandom.z, gunForceRandom.z))) * num, ForceMode.VelocityChange); + rig.AddTorque(base.transform.TransformDirection(gunTorque + new Vector3(Random.Range(0f - gunTorqueRandom.x, gunTorqueRandom.x), Random.Range(0f - gunTorqueRandom.y, gunTorqueRandom.y), Random.Range(0f - gunTorqueRandom.z, gunTorqueRandom.z))) * num, ForceMode.VelocityChange); + } +} diff --git a/ReliefShaders_applyLightForDeferred.cs b/ReliefShaders_applyLightForDeferred.cs new file mode 100644 index 0000000..18aec65 --- /dev/null +++ b/ReliefShaders_applyLightForDeferred.cs @@ -0,0 +1,54 @@ +using UnityEngine; + +[ExecuteInEditMode] +public class ReliefShaders_applyLightForDeferred : MonoBehaviour +{ + public Light lightForSelfShadowing; + + private Renderer _renderer; + + private void Reset() + { + if ((bool)GetComponent<Light>()) + { + lightForSelfShadowing = GetComponent<Light>(); + } + } + + private void Update() + { + if (!lightForSelfShadowing) + { + return; + } + if (_renderer == null) + { + _renderer = GetComponent<Renderer>(); + } + if ((bool)GetComponent<Renderer>()) + { + if (lightForSelfShadowing.type == LightType.Directional) + { + for (int i = 0; i < _renderer.sharedMaterials.Length; i++) + { + _renderer.sharedMaterials[i].SetVector("_WorldSpaceLightPosCustom", -lightForSelfShadowing.transform.forward); + } + } + else + { + for (int j = 0; j < _renderer.materials.Length; j++) + { + _renderer.sharedMaterials[j].SetVector("_WorldSpaceLightPosCustom", new Vector4(lightForSelfShadowing.transform.position.x, lightForSelfShadowing.transform.position.y, lightForSelfShadowing.transform.position.z, 1f)); + } + } + } + else if (lightForSelfShadowing.type == LightType.Directional) + { + Shader.SetGlobalVector("_WorldSpaceLightPosCustom", -lightForSelfShadowing.transform.forward); + } + else + { + Shader.SetGlobalVector("_WorldSpaceLightPosCustom", new Vector4(lightForSelfShadowing.transform.position.x, lightForSelfShadowing.transform.position.y, lightForSelfShadowing.transform.position.z, 1f)); + } + } +} diff --git a/ReliefTerrain.cs b/ReliefTerrain.cs new file mode 100644 index 0000000..b596751 --- /dev/null +++ b/ReliefTerrain.cs @@ -0,0 +1,451 @@ +using System; +using System.Reflection; +using UnityEngine; + +[AddComponentMenu("Relief Terrain/Engine - Terrain or Mesh")] +[ExecuteInEditMode] +public class ReliefTerrain : MonoBehaviour +{ + public Texture2D controlA; + + public Texture2D controlB; + + public Texture2D controlC; + + public string save_path_controlA = string.Empty; + + public string save_path_controlB = string.Empty; + + public string save_path_controlC = string.Empty; + + public string save_path_colormap = string.Empty; + + public string save_path_BumpGlobalCombined = string.Empty; + + public string save_path_WetMask = string.Empty; + + public Texture2D NormalGlobal; + + public Texture2D TreesGlobal; + + public Texture2D ColorGlobal; + + public Texture2D AmbientEmissiveMap; + + public Texture2D BumpGlobalCombined; + + public Texture2D TERRAIN_WetMask; + + public Texture2D tmp_globalColorMap; + + public Texture2D tmp_CombinedMap; + + public Texture2D tmp_WaterMap; + + public bool globalColorModifed_flag; + + public bool globalCombinedModifed_flag; + + public bool globalWaterModifed_flag; + + public bool splat_layer_ordered_mode; + + public RTPColorChannels[] source_controls_channels; + + public int[] splat_layer_seq; + + public float[] splat_layer_boost; + + public bool[] splat_layer_calc; + + public bool[] splat_layer_masked; + + public RTPColorChannels[] source_controls_mask_channels; + + public Texture2D[] source_controls; + + public bool[] source_controls_invert; + + public Texture2D[] source_controls_mask; + + public bool[] source_controls_mask_invert; + + public Vector2 customTiling = new Vector2(3f, 3f); + + [SerializeField] + public ReliefTerrainPresetHolder[] presetHolders; + + [SerializeField] + public ReliefTerrainGlobalSettingsHolder globalSettingsHolder; + + public void GetGlobalSettingsHolder() + { + if (globalSettingsHolder != null) + { + return; + } + ReliefTerrain[] array = (ReliefTerrain[])UnityEngine.Object.FindObjectsOfType(typeof(ReliefTerrain)); + bool flag = GetComponent(typeof(Terrain)); + for (int i = 0; i < array.Length; i++) + { + if (array[i].transform.parent == base.transform.parent && array[i].globalSettingsHolder != null && ((flag && array[i].GetComponent(typeof(Terrain)) != null) || (!flag && array[i].GetComponent(typeof(Terrain)) == null))) + { + globalSettingsHolder = array[i].globalSettingsHolder; + if ((bool)globalSettingsHolder.Get_RTP_LODmanagerScript() && !globalSettingsHolder.Get_RTP_LODmanagerScript().RTP_WETNESS_FIRST && !globalSettingsHolder.Get_RTP_LODmanagerScript().RTP_WETNESS_ADD) + { + BumpGlobalCombined = array[i].BumpGlobalCombined; + globalCombinedModifed_flag = false; + } + break; + } + } + if (globalSettingsHolder == null) + { + globalSettingsHolder = new ReliefTerrainGlobalSettingsHolder(); + if (flag) + { + globalSettingsHolder.numTiles = 0; + Terrain terrain = (Terrain)GetComponent(typeof(Terrain)); + globalSettingsHolder.splats = new Texture2D[terrain.terrainData.splatPrototypes.Length]; + globalSettingsHolder.Bumps = new Texture2D[terrain.terrainData.splatPrototypes.Length]; + for (int j = 0; j < terrain.terrainData.splatPrototypes.Length; j++) + { + globalSettingsHolder.splats[j] = terrain.terrainData.splatPrototypes[j].texture; + globalSettingsHolder.Bumps[j] = terrain.terrainData.splatPrototypes[j].normalMap; + } + } + else + { + globalSettingsHolder.splats = new Texture2D[4]; + } + globalSettingsHolder.numLayers = globalSettingsHolder.splats.Length; + globalSettingsHolder.ReturnToDefaults(string.Empty); + } + else if (flag) + { + GetSplatsFromGlobalSettingsHolder(); + } + source_controls_mask = new Texture2D[12]; + source_controls = new Texture2D[12]; + source_controls_channels = new RTPColorChannels[12]; + source_controls_mask_channels = new RTPColorChannels[12]; + splat_layer_seq = new int[12] + { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11 + }; + splat_layer_boost = new float[12] + { + 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, + 1f, 1f + }; + splat_layer_calc = new bool[12]; + splat_layer_masked = new bool[12]; + source_controls_invert = new bool[12]; + source_controls_mask_invert = new bool[12]; + if (flag) + { + globalSettingsHolder.numTiles++; + } + } + + private void GetSplatsFromGlobalSettingsHolder() + { + SplatPrototype[] array = new SplatPrototype[globalSettingsHolder.numLayers]; + for (int i = 0; i < globalSettingsHolder.numLayers; i++) + { + array[i] = new SplatPrototype(); + array[i].tileSize = Vector2.one; + array[i].tileOffset = new Vector2(1f / customTiling.x, 1f / customTiling.y); + array[i].texture = globalSettingsHolder.splats[i]; + array[i].normalMap = globalSettingsHolder.Bumps[i]; + } + Terrain terrain = (Terrain)GetComponent(typeof(Terrain)); + terrain.terrainData.splatPrototypes = array; + } + + public void InitTerrainTileSizes() + { + Terrain terrain = (Terrain)GetComponent(typeof(Terrain)); + if ((bool)terrain) + { + globalSettingsHolder.terrainTileSize = terrain.terrainData.size; + return; + } + globalSettingsHolder.terrainTileSize = GetComponent<Renderer>().bounds.size; + globalSettingsHolder.terrainTileSize.y = globalSettingsHolder.tessHeight; + } + + private void Awake() + { + UpdateBasemapDistance(apply_material_if_applicable: false); + RefreshTextures(); + } + + public void InitArrays() + { + RefreshTextures(); + } + + private void UpdateBasemapDistance(bool apply_material_if_applicable) + { + Terrain terrain = (Terrain)GetComponent(typeof(Terrain)); + if (!terrain || globalSettingsHolder == null) + { + return; + } + terrain.basemapDistance = globalSettingsHolder.distance_start + globalSettingsHolder.distance_transition; + if (apply_material_if_applicable) + { + if (terrain.materialTemplate == null) + { + terrain.materialType = Terrain.MaterialType.Custom; + Shader shader = Shader.Find("Relief Pack/ReliefTerrain-FirstPass"); + if ((bool)shader) + { + Material material = new Material(shader); + material.name = base.gameObject.name + " material"; + terrain.materialTemplate = material; + } + } + else + { + Material materialTemplate = terrain.materialTemplate; + terrain.materialTemplate = null; + terrain.materialTemplate = materialTemplate; + } + } + if (globalSettingsHolder != null && globalSettingsHolder._RTP_LODmanagerScript != null && globalSettingsHolder._RTP_LODmanagerScript.numLayersProcessedByFarShader != globalSettingsHolder.numLayers) + { + terrain.basemapDistance = 500000f; + } + globalSettingsHolder.Refresh(terrain.materialTemplate); + } + + public void RefreshTextures(Material mat = null, bool check_weak_references = false) + { + GetGlobalSettingsHolder(); + InitTerrainTileSizes(); + if (globalSettingsHolder != null && BumpGlobalCombined != null) + { + globalSettingsHolder.BumpGlobalCombinedSize = BumpGlobalCombined.width; + } + UpdateBasemapDistance(apply_material_if_applicable: true); + Terrain terrain = (Terrain)GetComponent(typeof(Terrain)); + globalSettingsHolder.use_mat = mat; + if (!terrain && !mat) + { + if (GetComponent<Renderer>().sharedMaterial == null || GetComponent<Renderer>().sharedMaterial.name != "RTPMaterial") + { + GetComponent<Renderer>().sharedMaterial = new Material(Shader.Find("Relief Pack/Terrain2Geometry")); + GetComponent<Renderer>().sharedMaterial.name = "RTPMaterial"; + } + globalSettingsHolder.use_mat = GetComponent<Renderer>().sharedMaterial; + } + if ((bool)terrain && terrain.materialTemplate != null) + { + globalSettingsHolder.use_mat = terrain.materialTemplate; + terrain.materialTemplate.SetVector("RTP_CustomTiling", new Vector4(1f / customTiling.x, 1f / customTiling.y, 0f, 0f)); + } + globalSettingsHolder.use_mat = null; + RefreshControlMaps(mat); + if ((bool)mat) + { + mat.SetVector("RTP_CustomTiling", new Vector4(1f / customTiling.x, 1f / customTiling.y, 0f, 0f)); + } + } + + public void RefreshControlMaps(Material mat = null) + { + globalSettingsHolder.use_mat = mat; + Terrain terrain = (Terrain)GetComponent(typeof(Terrain)); + if (!terrain && !mat) + { + globalSettingsHolder.use_mat = GetComponent<Renderer>().sharedMaterial; + } + if ((bool)terrain && !mat && terrain.materialTemplate != null) + { + globalSettingsHolder.use_mat = terrain.materialTemplate; + } + globalSettingsHolder.SetShaderParam("_Control1", controlA); + if (globalSettingsHolder.numLayers > 4) + { + globalSettingsHolder.SetShaderParam("_Control3", controlB); + globalSettingsHolder.SetShaderParam("_Control2", controlB); + } + if (globalSettingsHolder.numLayers > 8) + { + globalSettingsHolder.SetShaderParam("_Control3", controlC); + } + globalSettingsHolder.SetShaderParam("_ColorMapGlobal", ColorGlobal); + globalSettingsHolder.SetShaderParam("_NormalMapGlobal", NormalGlobal); + globalSettingsHolder.SetShaderParam("_TreesMapGlobal", TreesGlobal); + globalSettingsHolder.SetShaderParam("_AmbientEmissiveMapGlobal", AmbientEmissiveMap); + globalSettingsHolder.SetShaderParam("_BumpMapGlobal", BumpGlobalCombined); + globalSettingsHolder.use_mat = null; + } + + public void GetControlMaps() + { + Terrain terrain = (Terrain)GetComponent(typeof(Terrain)); + if (!terrain) + { + Debug.Log("Can't fint terrain component !!!"); + return; + } + Type type = terrain.terrainData.GetType(); + PropertyInfo property = type.GetProperty("alphamapTextures", BindingFlags.Instance | BindingFlags.Public); + if (property != null) + { + Texture2D[] array = (Texture2D[])property.GetValue(terrain.terrainData, null); + if (array.Length > 0) + { + controlA = array[0]; + } + else + { + controlA = null; + } + if (array.Length > 1) + { + controlB = array[1]; + } + else + { + controlB = null; + } + if (array.Length > 2) + { + controlC = array[2]; + } + else + { + controlC = null; + } + } + else + { + Debug.LogError("Can't access alphamapTexture directly..."); + } + } + + public void SetCustomControlMaps() + { + Terrain terrain = (Terrain)GetComponent(typeof(Terrain)); + if (!terrain) + { + Debug.Log("Can't fint terrain component !!!"); + } + else + { + if (controlA == null) + { + return; + } + if (terrain.terrainData.alphamapResolution != controlA.width) + { + Debug.LogError("Terrain controlmap resolution differs fromrequested control texture..."); + } + else + { + if (!controlA) + { + return; + } + float[,,] alphamaps = terrain.terrainData.GetAlphamaps(0, 0, terrain.terrainData.alphamapResolution, terrain.terrainData.alphamapResolution); + Color[] pixels = controlA.GetPixels(); + for (int i = 0; i < terrain.terrainData.alphamapLayers; i++) + { + int num = 0; + switch (i) + { + case 4: + if (!controlB) + { + return; + } + pixels = controlB.GetPixels(); + break; + case 8: + if (!controlC) + { + return; + } + pixels = controlC.GetPixels(); + break; + } + int index = i & 3; + for (int j = 0; j < terrain.terrainData.alphamapResolution; j++) + { + for (int k = 0; k < terrain.terrainData.alphamapResolution; k++) + { + alphamaps[j, k, i] = pixels[num++][index]; + } + } + } + terrain.terrainData.SetAlphamaps(0, 0, alphamaps); + } + } + } + + public void RestorePreset(ReliefTerrainPresetHolder holder) + { + controlA = holder.controlA; + controlB = holder.controlB; + controlC = holder.controlC; + SetCustomControlMaps(); + ColorGlobal = holder.ColorGlobal; + NormalGlobal = holder.NormalGlobal; + TreesGlobal = holder.TreesGlobal; + AmbientEmissiveMap = holder.AmbientEmissiveMap; + BumpGlobalCombined = holder.BumpGlobalCombined; + TERRAIN_WetMask = holder.TERRAIN_WetMask; + globalColorModifed_flag = holder.globalColorModifed_flag; + globalCombinedModifed_flag = holder.globalCombinedModifed_flag; + globalWaterModifed_flag = holder.globalWaterModifed_flag; + RefreshTextures(); + globalSettingsHolder.RestorePreset(holder); + } + + public ReliefTerrainPresetHolder GetPresetByID(string PresetID) + { + if (presetHolders != null) + { + for (int i = 0; i < presetHolders.Length; i++) + { + if (presetHolders[i].PresetID == PresetID) + { + return presetHolders[i]; + } + } + } + return null; + } + + public ReliefTerrainPresetHolder GetPresetByName(string PresetName) + { + if (presetHolders != null) + { + for (int i = 0; i < presetHolders.Length; i++) + { + if (presetHolders[i].PresetName == PresetName) + { + return presetHolders[i]; + } + } + } + return null; + } + + public bool InterpolatePresets(string PresetID1, string PresetID2, float t) + { + ReliefTerrainPresetHolder presetByID = GetPresetByID(PresetID1); + ReliefTerrainPresetHolder presetByID2 = GetPresetByID(PresetID2); + if (presetByID == null || presetByID2 == null || presetByID.Spec == null || presetByID2.Spec == null || presetByID.Spec.Length != presetByID2.Spec.Length) + { + return false; + } + globalSettingsHolder.InterpolatePresets(presetByID, presetByID2, t); + return true; + } +} diff --git a/ReliefTerrainControlTexturesItems.cs b/ReliefTerrainControlTexturesItems.cs new file mode 100644 index 0000000..67429fe --- /dev/null +++ b/ReliefTerrainControlTexturesItems.cs @@ -0,0 +1,6 @@ +public enum ReliefTerrainControlTexturesItems +{ + Compose, + Acquire, + Controlmaps +} diff --git a/ReliefTerrainDerivedTexturesItems.cs b/ReliefTerrainDerivedTexturesItems.cs new file mode 100644 index 0000000..f9bd19e --- /dev/null +++ b/ReliefTerrainDerivedTexturesItems.cs @@ -0,0 +1,7 @@ +public enum ReliefTerrainDerivedTexturesItems +{ + Atlasing, + Heightmaps, + Bumpmaps, + Globalnormal +} diff --git a/ReliefTerrainGlobalSettingsHolder.cs b/ReliefTerrainGlobalSettingsHolder.cs new file mode 100644 index 0000000..3575c4b --- /dev/null +++ b/ReliefTerrainGlobalSettingsHolder.cs @@ -0,0 +1,2309 @@ +using System; +using UnityEngine; + +[Serializable] +public class ReliefTerrainGlobalSettingsHolder +{ + public int numTiles; + + public int numLayers; + + [NonSerialized] + public bool dont_check_weak_references; + + [NonSerialized] + public bool dont_check_for_interfering_terrain_replacement_shaders; + + [NonSerialized] + public Texture2D[] bakeJobArray; + + public Texture2D[] splats; + + public Texture2D[] splat_atlases = new Texture2D[3]; + + public string save_path_atlasA = string.Empty; + + public string save_path_atlasB = string.Empty; + + public string save_path_atlasC = string.Empty; + + public string save_path_terrain_steepness = string.Empty; + + public string save_path_terrain_height = string.Empty; + + public string save_path_terrain_direction = string.Empty; + + public string save_path_Bump01 = string.Empty; + + public string save_path_Bump23 = string.Empty; + + public string save_path_Bump45 = string.Empty; + + public string save_path_Bump67 = string.Empty; + + public string save_path_Bump89 = string.Empty; + + public string save_path_BumpAB = string.Empty; + + public string save_path_HeightMap = string.Empty; + + public string save_path_HeightMap2 = string.Empty; + + public string save_path_HeightMap3 = string.Empty; + + public string save_path_SSColorCombinedA = string.Empty; + + public string save_path_SSColorCombinedB = string.Empty; + + public string newPresetName = "a preset name..."; + + public Texture2D activateObject; + + private GameObject _RTP_LODmanager; + + public RTP_LODmanager _RTP_LODmanagerScript; + + public float RTP_MIP_BIAS; + + public float MasterLayerBrightness = 1f; + + public float MasterLayerSaturation = 1f; + + public float EmissionRefractFiltering = 4f; + + public float EmissionRefractAnimSpeed = 4f; + + public RTPColorChannels SuperDetailA_channel; + + public RTPColorChannels SuperDetailB_channel; + + public Texture2D Bump01; + + public Texture2D Bump23; + + public Texture2D Bump45; + + public Texture2D Bump67; + + public Texture2D Bump89; + + public Texture2D BumpAB; + + public Texture2D BumpGlobal; + + public int BumpGlobalCombinedSize = 1024; + + public Texture2D SSColorCombinedA; + + public Texture2D SSColorCombinedB; + + public Texture2D VerticalTexture; + + public float BumpMapGlobalScale; + + public Vector3 GlobalColorMapBlendValues; + + public float _GlobalColorMapNearMIP; + + public float GlobalColorMapSaturation; + + public float GlobalColorMapSaturationFar = 1f; + + public float GlobalColorMapDistortByPerlin = 0.005f; + + public float GlobalColorMapBrightness; + + public float GlobalColorMapBrightnessFar = 1f; + + public float _FarNormalDamp; + + public float blendMultiplier; + + public Vector3 terrainTileSize; + + public Texture2D HeightMap; + + public Vector4 ReliefTransform; + + public float DIST_STEPS; + + public float WAVELENGTH; + + public float ReliefBorderBlend; + + public float ExtrudeHeight; + + public float LightmapShading; + + public float RTP_AOsharpness; + + public float RTP_AOamp; + + public float _occlusionStrength = 1f; + + public float SHADOW_STEPS; + + public float WAVELENGTH_SHADOWS; + + public float SelfShadowStrength; + + public float ShadowSmoothing; + + public float ShadowSoftnessFade = 0.8f; + + public float distance_start; + + public float distance_transition; + + public float distance_start_bumpglobal; + + public float distance_transition_bumpglobal; + + public float rtp_perlin_start_val; + + public float _Phong; + + public float tessHeight = 300f; + + public float _TessSubdivisions = 1f; + + public float _TessSubdivisionsFar = 1f; + + public float _TessYOffset; + + public float trees_shadow_distance_start; + + public float trees_shadow_distance_transition; + + public float trees_shadow_value; + + public float trees_pixel_distance_start; + + public float trees_pixel_distance_transition; + + public float trees_pixel_blend_val; + + public float global_normalMap_multiplier; + + public float global_normalMap_farUsage; + + public float _AmbientEmissiveMultiplier = 1f; + + public float _AmbientEmissiveRelief = 0.5f; + + public Texture2D HeightMap2; + + public Texture2D HeightMap3; + + public int rtp_mipoffset_globalnorm; + + public float _SuperDetailTiling; + + public Texture2D SuperDetailA; + + public Texture2D SuperDetailB; + + public float TERRAIN_GlobalWetness; + + public Texture2D TERRAIN_RippleMap; + + public float TERRAIN_RippleScale; + + public float TERRAIN_FlowScale; + + public float TERRAIN_FlowSpeed; + + public float TERRAIN_FlowCycleScale; + + public float TERRAIN_FlowMipOffset; + + public float TERRAIN_WetDarkening; + + public float TERRAIN_WetDropletsStrength; + + public float TERRAIN_WetHeight_Treshold; + + public float TERRAIN_WetHeight_Transition; + + public float TERRAIN_RainIntensity; + + public float TERRAIN_DropletsSpeed; + + public float TERRAIN_mipoffset_flowSpeed; + + public float TERRAIN_CausticsAnimSpeed; + + public Color TERRAIN_CausticsColor; + + public GameObject TERRAIN_CausticsWaterLevelRefObject; + + public float TERRAIN_CausticsWaterLevel; + + public float TERRAIN_CausticsWaterLevelByAngle; + + public float TERRAIN_CausticsWaterDeepFadeLength; + + public float TERRAIN_CausticsWaterShallowFadeLength; + + public float TERRAIN_CausticsTilingScale; + + public Texture2D TERRAIN_CausticsTex; + + public Vector4 RTP_LightDefVector; + + public Texture2D[] Bumps; + + public float[] FarSpecCorrection; + + public float[] MIPmult; + + public float[] MixScale; + + public float[] MixBlend; + + public float[] MixSaturation; + + public float[] RTP_DiffFresnel; + + public float[] RTP_metallic; + + public float[] RTP_glossMin; + + public float[] RTP_glossMax; + + public float[] RTP_glitter; + + public float[] GlobalColorBottom; + + public float[] GlobalColorTop; + + public float[] GlobalColorColormapLoSat; + + public float[] GlobalColorColormapHiSat; + + public float[] GlobalColorLayerLoSat; + + public float[] GlobalColorLayerHiSat; + + public float[] GlobalColorLoBlend; + + public float[] GlobalColorHiBlend; + + public float[] MixBrightness; + + public float[] MixReplace; + + public float[] LayerBrightness; + + public float[] LayerBrightness2Spec; + + public float[] LayerAlbedo2SpecColor; + + public float[] LayerSaturation; + + public float[] LayerEmission; + + public Color[] LayerEmissionColor; + + public float[] LayerEmissionRefractStrength; + + public float[] LayerEmissionRefractHBedge; + + public float[] GlobalColorPerLayer; + + public float[] PER_LAYER_HEIGHT_MODIFIER; + + public float[] _SuperDetailStrengthMultA; + + public float[] _SuperDetailStrengthMultASelfMaskNear; + + public float[] _SuperDetailStrengthMultASelfMaskFar; + + public float[] _SuperDetailStrengthMultB; + + public float[] _SuperDetailStrengthMultBSelfMaskNear; + + public float[] _SuperDetailStrengthMultBSelfMaskFar; + + public float[] _SuperDetailStrengthNormal; + + public float[] _BumpMapGlobalStrength; + + public float[] AO_strength = new float[12] + { + 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, + 1f, 1f + }; + + public float[] VerticalTextureStrength; + + public float VerticalTextureGlobalBumpInfluence; + + public float VerticalTextureTiling; + + public Texture2D[] Heights; + + public float[] _snow_strength_per_layer; + + public ProceduralMaterial[] Substances; + + public float[] TERRAIN_LayerWetStrength; + + public float[] TERRAIN_WaterLevel; + + public float[] TERRAIN_WaterLevelSlopeDamp; + + public float[] TERRAIN_WaterEdge; + + public float[] TERRAIN_WaterGloss; + + public float[] TERRAIN_WaterGlossDamper; + + public float[] TERRAIN_Refraction; + + public float[] TERRAIN_WetRefraction; + + public float[] TERRAIN_Flow; + + public float[] TERRAIN_WetFlow; + + public float[] TERRAIN_WaterMetallic; + + public float[] TERRAIN_WetGloss; + + public Color[] TERRAIN_WaterColor; + + public float[] TERRAIN_WaterEmission; + + public float _snow_strength; + + public float _global_color_brightness_to_snow; + + public float _snow_slope_factor; + + public float _snow_edge_definition; + + public float _snow_height_treshold; + + public float _snow_height_transition; + + public Color _snow_color; + + public float _snow_gloss; + + public float _snow_reflectivness; + + public float _snow_deep_factor; + + public float _snow_diff_fresnel; + + public float _snow_metallic; + + public float _snow_Frost; + + public float _snow_MicroTiling = 1f; + + public float _snow_BumpMicro = 0.2f; + + public Color _SnowGlitterColor = new Color(1f, 1f, 1f, 0.1f); + + public float _snow_occlusionStrength = 0.5f; + + public int _snow_TranslucencyDeferredLightIndex; + + public Color _GlitterColor; + + public float[] _GlitterStrength; + + public float _GlitterTiling; + + public float _GlitterDensity; + + public float _GlitterFilter; + + public float _GlitterColorization; + + public Texture2D _SparkleMap; + + public bool _4LAYERS_SHADER_USED; + + public bool flat_dir_ref = true; + + public bool flip_dir_ref = true; + + public GameObject direction_object; + + public bool show_details; + + public bool show_details_main; + + public bool show_details_atlasing; + + public bool show_details_layers; + + public bool show_details_uv_blend; + + public bool show_controlmaps; + + public bool show_controlmaps_build; + + public bool show_controlmaps_helpers; + + public bool show_controlmaps_highcost; + + public bool show_controlmaps_splats; + + public bool show_vert_texture; + + public bool show_global_color; + + public bool show_snow; + + public bool show_global_bump; + + public bool show_global_bump_normals; + + public bool show_global_bump_superdetail; + + public ReliefTerrainMenuItems submenu; + + public ReliefTerrainSettingsItems submenu_settings; + + public ReliefTerrainDerivedTexturesItems submenu_derived_textures; + + public ReliefTerrainControlTexturesItems submenu_control_textures; + + public bool show_global_wet_settings; + + public bool show_global_reflection_settings; + + public int show_active_layer; + + public bool show_derivedmaps; + + public bool show_settings; + + public bool undo_flag; + + public bool paint_flag; + + public float paint_size = 0.5f; + + public float paint_smoothness; + + public float paint_opacity = 1f; + + public Color paintColor = new Color(0.5f, 0.3f, 0f, 0f); + + public bool preserveBrightness = true; + + public bool paint_alpha_flag; + + public bool paint_wetmask; + + public RaycastHit paintHitInfo; + + public bool paintHitInfo_flag; + + public bool cut_holes; + + private Texture2D dumb_tex; + + public Color[] paintColorSwatches; + + public Material use_mat; + + public ReliefTerrainGlobalSettingsHolder() + { + Bumps = new Texture2D[12]; + Heights = new Texture2D[12]; + FarSpecCorrection = new float[12]; + MIPmult = new float[12]; + MixScale = new float[12]; + MixBlend = new float[12]; + MixSaturation = new float[12]; + RTP_DiffFresnel = new float[12]; + RTP_metallic = new float[12]; + RTP_glossMin = new float[12]; + RTP_glossMax = new float[12]; + RTP_glitter = new float[12]; + MixBrightness = new float[12]; + MixReplace = new float[12]; + LayerBrightness = new float[12]; + LayerBrightness2Spec = new float[12]; + LayerAlbedo2SpecColor = new float[12]; + LayerSaturation = new float[12]; + LayerEmission = new float[12]; + LayerEmissionColor = new Color[12]; + LayerEmissionRefractStrength = new float[12]; + LayerEmissionRefractHBedge = new float[12]; + GlobalColorPerLayer = new float[12]; + GlobalColorBottom = new float[12]; + GlobalColorTop = new float[12]; + GlobalColorColormapLoSat = new float[12]; + GlobalColorColormapHiSat = new float[12]; + GlobalColorLayerLoSat = new float[12]; + GlobalColorLayerHiSat = new float[12]; + GlobalColorLoBlend = new float[12]; + GlobalColorHiBlend = new float[12]; + PER_LAYER_HEIGHT_MODIFIER = new float[12]; + _snow_strength_per_layer = new float[12]; + Substances = new ProceduralMaterial[12]; + _SuperDetailStrengthMultA = new float[12]; + _SuperDetailStrengthMultASelfMaskNear = new float[12]; + _SuperDetailStrengthMultASelfMaskFar = new float[12]; + _SuperDetailStrengthMultB = new float[12]; + _SuperDetailStrengthMultBSelfMaskNear = new float[12]; + _SuperDetailStrengthMultBSelfMaskFar = new float[12]; + _SuperDetailStrengthNormal = new float[12]; + _BumpMapGlobalStrength = new float[12]; + AO_strength = new float[12]; + VerticalTextureStrength = new float[12]; + TERRAIN_LayerWetStrength = new float[12]; + TERRAIN_WaterLevel = new float[12]; + TERRAIN_WaterLevelSlopeDamp = new float[12]; + TERRAIN_WaterEdge = new float[12]; + TERRAIN_WaterGloss = new float[12]; + TERRAIN_WaterGlossDamper = new float[12]; + TERRAIN_Refraction = new float[12]; + TERRAIN_WetRefraction = new float[12]; + TERRAIN_Flow = new float[12]; + TERRAIN_WetFlow = new float[12]; + TERRAIN_WaterMetallic = new float[12]; + TERRAIN_WetGloss = new float[12]; + TERRAIN_WaterColor = new Color[12]; + TERRAIN_WaterEmission = new float[12]; + _GlitterStrength = new float[12]; + } + + public void ReInit(Terrain terrainComp) + { + if (terrainComp.terrainData.splatPrototypes.Length > numLayers) + { + Texture2D[] array = new Texture2D[terrainComp.terrainData.splatPrototypes.Length]; + Texture2D[] array2 = new Texture2D[terrainComp.terrainData.splatPrototypes.Length]; + for (int i = 0; i < splats.Length; i++) + { + array[i] = splats[i]; + array2[i] = Bumps[i]; + } + splats = array; + Bumps = array2; + splats[terrainComp.terrainData.splatPrototypes.Length - 1] = terrainComp.terrainData.splatPrototypes[(terrainComp.terrainData.splatPrototypes.Length - 2 >= 0) ? (terrainComp.terrainData.splatPrototypes.Length - 2) : 0].texture; + Bumps[terrainComp.terrainData.splatPrototypes.Length - 1] = terrainComp.terrainData.splatPrototypes[(terrainComp.terrainData.splatPrototypes.Length - 2 >= 0) ? (terrainComp.terrainData.splatPrototypes.Length - 2) : 0].normalMap; + } + else if (terrainComp.terrainData.splatPrototypes.Length < numLayers) + { + Texture2D[] array3 = new Texture2D[terrainComp.terrainData.splatPrototypes.Length]; + Texture2D[] array4 = new Texture2D[terrainComp.terrainData.splatPrototypes.Length]; + for (int j = 0; j < array3.Length; j++) + { + array3[j] = splats[j]; + array4[j] = Bumps[j]; + } + splats = array3; + Bumps = array4; + } + numLayers = terrainComp.terrainData.splatPrototypes.Length; + } + + public void SetShaderParam(string name, Texture2D tex) + { + if ((bool)tex) + { + if ((bool)use_mat) + { + use_mat.SetTexture(name, tex); + } + else + { + Shader.SetGlobalTexture(name, tex); + } + } + } + + public void SetShaderParam(string name, Cubemap tex) + { + if ((bool)tex) + { + if ((bool)use_mat) + { + use_mat.SetTexture(name, tex); + } + else + { + Shader.SetGlobalTexture(name, tex); + } + } + } + + public void SetShaderParam(string name, Matrix4x4 mtx) + { + if ((bool)use_mat) + { + use_mat.SetMatrix(name, mtx); + } + else + { + Shader.SetGlobalMatrix(name, mtx); + } + } + + public void SetShaderParam(string name, Vector4 vec) + { + if ((bool)use_mat) + { + use_mat.SetVector(name, vec); + } + else + { + Shader.SetGlobalVector(name, vec); + } + } + + public void SetShaderParam(string name, float val) + { + if ((bool)use_mat) + { + use_mat.SetFloat(name, val); + } + else + { + Shader.SetGlobalFloat(name, val); + } + } + + public void SetShaderParam(string name, Color col) + { + if ((bool)use_mat) + { + use_mat.SetColor(name, col); + } + else + { + Shader.SetGlobalColor(name, col); + } + } + + public RTP_LODmanager Get_RTP_LODmanagerScript() + { + return _RTP_LODmanagerScript; + } + + private void CheckLightScriptForDefered() + { + Light[] array = UnityEngine.Object.FindObjectsOfType<Light>(); + Light light = null; + for (int i = 0; i < array.Length; i++) + { + if (array[i].type == LightType.Directional) + { + if (!(array[i].gameObject.GetComponent<ReliefShaders_applyLightForDeferred>() == null)) + { + return; + } + light = array[i]; + } + } + if ((bool)light) + { + ReliefShaders_applyLightForDeferred reliefShaders_applyLightForDeferred = light.gameObject.AddComponent(typeof(ReliefShaders_applyLightForDeferred)) as ReliefShaders_applyLightForDeferred; + reliefShaders_applyLightForDeferred.lightForSelfShadowing = light; + } + } + + public void RefreshAll() + { + CheckLightScriptForDefered(); + ReliefTerrain[] array = UnityEngine.Object.FindObjectsOfType(typeof(ReliefTerrain)) as ReliefTerrain[]; + for (int i = 0; i < array.Length; i++) + { + if (array[i].globalSettingsHolder != null) + { + Terrain terrain = array[i].GetComponent(typeof(Terrain)) as Terrain; + if ((bool)terrain) + { + array[i].globalSettingsHolder.Refresh(terrain.materialTemplate); + } + else + { + array[i].globalSettingsHolder.Refresh(array[i].GetComponent<Renderer>().sharedMaterial); + } + array[i].RefreshTextures(); + } + } + GeometryVsTerrainBlend[] array2 = UnityEngine.Object.FindObjectsOfType(typeof(GeometryVsTerrainBlend)) as GeometryVsTerrainBlend[]; + for (int j = 0; j < array2.Length; j++) + { + array2[j].SetupValues(); + } + } + + public void Refresh(Material mat = null, ReliefTerrain rt_caller = null) + { + if (splats == null) + { + return; + } + if (mat == null && rt_caller != null && rt_caller.globalSettingsHolder == this) + { + Terrain terrain = rt_caller.GetComponent(typeof(Terrain)) as Terrain; + if ((bool)terrain) + { + rt_caller.globalSettingsHolder.Refresh(terrain.materialTemplate); + } + else if (rt_caller.GetComponent<Renderer>() != null && rt_caller.GetComponent<Renderer>().sharedMaterial != null) + { + rt_caller.globalSettingsHolder.Refresh(rt_caller.GetComponent<Renderer>().sharedMaterial); + } + } + use_mat = mat; + if (mat != null) + { + mat.globalIlluminationFlags = MaterialGlobalIlluminationFlags.RealtimeEmissive; + } + for (int i = 0; i < numLayers; i++) + { + if (i < 4) + { + SetShaderParam("_SplatA" + i, splats[i]); + } + else if (i < 8) + { + if (_4LAYERS_SHADER_USED) + { + SetShaderParam("_SplatC" + (i - 4), splats[i]); + SetShaderParam("_SplatB" + (i - 4), splats[i]); + } + else + { + SetShaderParam("_SplatB" + (i - 4), splats[i]); + } + } + else if (i < 12) + { + SetShaderParam("_SplatC" + (i - 4), splats[i]); + } + } + CheckAndUpdate(ref RTP_DiffFresnel, 0f, numLayers); + CheckAndUpdate(ref RTP_metallic, 0f, numLayers); + CheckAndUpdate(ref RTP_glossMin, 0f, numLayers); + CheckAndUpdate(ref RTP_glossMax, 1f, numLayers); + CheckAndUpdate(ref RTP_glitter, 0f, numLayers); + CheckAndUpdate(ref TERRAIN_WaterGloss, 0.1f, numLayers); + CheckAndUpdate(ref TERRAIN_WaterGlossDamper, 0f, numLayers); + CheckAndUpdate(ref TERRAIN_WaterMetallic, 0.1f, numLayers); + CheckAndUpdate(ref TERRAIN_WetGloss, 0.05f, numLayers); + CheckAndUpdate(ref TERRAIN_WetFlow, 0.05f, numLayers); + CheckAndUpdate(ref MixBrightness, 2f, numLayers); + CheckAndUpdate(ref MixReplace, 0f, numLayers); + CheckAndUpdate(ref LayerBrightness, 1f, numLayers); + CheckAndUpdate(ref LayerBrightness2Spec, 0f, numLayers); + CheckAndUpdate(ref LayerAlbedo2SpecColor, 0f, numLayers); + CheckAndUpdate(ref LayerSaturation, 1f, numLayers); + CheckAndUpdate(ref LayerEmission, 0f, numLayers); + CheckAndUpdate(ref FarSpecCorrection, 0f, numLayers); + CheckAndUpdate(ref LayerEmissionColor, Color.black, numLayers); + CheckAndUpdate(ref LayerEmissionRefractStrength, 0f, numLayers); + CheckAndUpdate(ref LayerEmissionRefractHBedge, 0f, numLayers); + CheckAndUpdate(ref TERRAIN_WaterEmission, 0f, numLayers); + CheckAndUpdate(ref _GlitterStrength, 0f, numLayers); + SetShaderParam("terrainTileSize", terrainTileSize); + SetShaderParam("RTP_AOamp", RTP_AOamp); + SetShaderParam("RTP_AOsharpness", RTP_AOsharpness); + SetShaderParam("_occlusionStrength", _occlusionStrength); + SetShaderParam("EmissionRefractFiltering", EmissionRefractFiltering); + SetShaderParam("EmissionRefractAnimSpeed", EmissionRefractAnimSpeed); + SetShaderParam("_VerticalTexture", VerticalTexture); + SetShaderParam("_GlobalColorMapBlendValues", GlobalColorMapBlendValues); + SetShaderParam("_GlobalColorMapSaturation", GlobalColorMapSaturation); + SetShaderParam("_GlobalColorMapSaturationFar", GlobalColorMapSaturationFar); + SetShaderParam("_GlobalColorMapDistortByPerlin", GlobalColorMapDistortByPerlin); + SetShaderParam("_GlobalColorMapBrightness", GlobalColorMapBrightness); + SetShaderParam("_GlobalColorMapBrightnessFar", GlobalColorMapBrightnessFar); + SetShaderParam("_GlobalColorMapNearMIP", _GlobalColorMapNearMIP); + SetShaderParam("_RTP_MIP_BIAS", RTP_MIP_BIAS); + SetShaderParam("_BumpMapGlobalScale", BumpMapGlobalScale); + SetShaderParam("_FarNormalDamp", _FarNormalDamp); + SetShaderParam("_blend_multiplier", blendMultiplier); + SetShaderParam("_TERRAIN_ReliefTransform", ReliefTransform); + SetShaderParam("_TERRAIN_ReliefTransformTriplanarZ", ReliefTransform.x); + SetShaderParam("_TERRAIN_DIST_STEPS", DIST_STEPS); + SetShaderParam("_TERRAIN_WAVELENGTH", WAVELENGTH); + SetShaderParam("_TERRAIN_ExtrudeHeight", ExtrudeHeight); + SetShaderParam("_TERRAIN_LightmapShading", LightmapShading); + SetShaderParam("_TERRAIN_SHADOW_STEPS", SHADOW_STEPS); + SetShaderParam("_TERRAIN_WAVELENGTH_SHADOWS", WAVELENGTH_SHADOWS); + SetShaderParam("_TERRAIN_SelfShadowStrength", SelfShadowStrength); + SetShaderParam("_TERRAIN_ShadowSmoothing", (1f - ShadowSmoothing) * 6f); + SetShaderParam("_TERRAIN_ShadowSoftnessFade", ShadowSoftnessFade); + SetShaderParam("_TERRAIN_distance_start", distance_start); + SetShaderParam("_TERRAIN_distance_transition", distance_transition); + SetShaderParam("_TERRAIN_distance_start_bumpglobal", distance_start_bumpglobal); + SetShaderParam("_TERRAIN_distance_transition_bumpglobal", distance_transition_bumpglobal); + SetShaderParam("rtp_perlin_start_val", rtp_perlin_start_val); + Shader.SetGlobalVector("_TERRAIN_trees_shadow_values", new Vector4(trees_shadow_distance_start, trees_shadow_distance_transition, trees_shadow_value, global_normalMap_multiplier)); + Shader.SetGlobalVector("_TERRAIN_trees_pixel_values", new Vector4(trees_pixel_distance_start, trees_pixel_distance_transition, trees_pixel_blend_val, global_normalMap_farUsage)); + SetShaderParam("_Phong", _Phong); + SetShaderParam("_TessSubdivisions", _TessSubdivisions); + SetShaderParam("_TessSubdivisionsFar", _TessSubdivisionsFar); + SetShaderParam("_TessYOffset", _TessYOffset); + Shader.SetGlobalFloat("_AmbientEmissiveMultiplier", _AmbientEmissiveMultiplier); + Shader.SetGlobalFloat("_AmbientEmissiveRelief", _AmbientEmissiveRelief); + SetShaderParam("_SuperDetailTiling", _SuperDetailTiling); + Shader.SetGlobalFloat("rtp_snow_strength", _snow_strength); + Shader.SetGlobalFloat("rtp_global_color_brightness_to_snow", _global_color_brightness_to_snow); + Shader.SetGlobalFloat("rtp_snow_slope_factor", _snow_slope_factor); + Shader.SetGlobalFloat("rtp_snow_edge_definition", _snow_edge_definition); + Shader.SetGlobalFloat("rtp_snow_height_treshold", _snow_height_treshold); + Shader.SetGlobalFloat("rtp_snow_height_transition", _snow_height_transition); + Shader.SetGlobalColor("rtp_snow_color", _snow_color); + Shader.SetGlobalFloat("rtp_snow_gloss", _snow_gloss); + Shader.SetGlobalFloat("rtp_snow_reflectivness", _snow_reflectivness); + Shader.SetGlobalFloat("rtp_snow_deep_factor", _snow_deep_factor); + Shader.SetGlobalFloat("rtp_snow_diff_fresnel", _snow_diff_fresnel); + Shader.SetGlobalFloat("rtp_snow_metallic", _snow_metallic); + Shader.SetGlobalFloat("rtp_snow_Frost", _snow_Frost); + Shader.SetGlobalFloat("rtp_snow_MicroTiling", _snow_MicroTiling); + Shader.SetGlobalFloat("rtp_snow_BumpMicro", _snow_BumpMicro); + Shader.SetGlobalFloat("rtp_snow_occlusionStrength", _snow_occlusionStrength); + Shader.SetGlobalFloat("rtp_snow_TranslucencyDeferredLightIndex", _snow_TranslucencyDeferredLightIndex); + Shader.SetGlobalColor("_SnowGlitterColor", _SnowGlitterColor); + SetShaderParam("TERRAIN_CausticsAnimSpeed", TERRAIN_CausticsAnimSpeed); + SetShaderParam("TERRAIN_CausticsColor", TERRAIN_CausticsColor); + if ((bool)TERRAIN_CausticsWaterLevelRefObject) + { + TERRAIN_CausticsWaterLevel = TERRAIN_CausticsWaterLevelRefObject.transform.position.y; + } + Shader.SetGlobalFloat("TERRAIN_CausticsWaterLevel", TERRAIN_CausticsWaterLevel); + Shader.SetGlobalFloat("TERRAIN_CausticsWaterLevelByAngle", TERRAIN_CausticsWaterLevelByAngle); + Shader.SetGlobalFloat("TERRAIN_CausticsWaterDeepFadeLength", TERRAIN_CausticsWaterDeepFadeLength); + Shader.SetGlobalFloat("TERRAIN_CausticsWaterShallowFadeLength", TERRAIN_CausticsWaterShallowFadeLength); + SetShaderParam("TERRAIN_CausticsTilingScale", TERRAIN_CausticsTilingScale); + SetShaderParam("TERRAIN_CausticsTex", TERRAIN_CausticsTex); + SetShaderParam("_GlitterColor", _GlitterColor); + SetShaderParam("_GlitterTiling", _GlitterTiling); + SetShaderParam("_GlitterDensity", _GlitterDensity); + SetShaderParam("_GlitterFilter", _GlitterFilter); + SetShaderParam("_GlitterColorization", _GlitterColorization); + SetShaderParam("_SparkleMap", _SparkleMap); + if (numLayers > 0) + { + int num = 512; + for (int j = 0; j < numLayers; j++) + { + if ((bool)splats[j]) + { + num = splats[j].width; + break; + } + } + SetShaderParam("rtp_mipoffset_color", (0f - Mathf.Log(1024f / (float)num)) / Mathf.Log(2f)); + if (Bump01 != null) + { + num = Bump01.width; + } + SetShaderParam("rtp_mipoffset_bump", (0f - Mathf.Log(1024f / (float)num)) / Mathf.Log(2f)); + if ((bool)HeightMap) + { + num = HeightMap.width; + } + else if ((bool)HeightMap2) + { + num = HeightMap2.width; + } + else if ((bool)HeightMap3) + { + num = HeightMap3.width; + } + SetShaderParam("rtp_mipoffset_height", (0f - Mathf.Log(1024f / (float)num)) / Mathf.Log(2f)); + num = BumpGlobalCombinedSize; + SetShaderParam("rtp_mipoffset_globalnorm", (0f - Mathf.Log(1024f / ((float)num * BumpMapGlobalScale))) / Mathf.Log(2f) + (float)rtp_mipoffset_globalnorm); + SetShaderParam("rtp_mipoffset_superdetail", (0f - Mathf.Log(1024f / ((float)num * _SuperDetailTiling))) / Mathf.Log(2f)); + SetShaderParam("rtp_mipoffset_flow", (0f - Mathf.Log(1024f / ((float)num * TERRAIN_FlowScale))) / Mathf.Log(2f) + TERRAIN_FlowMipOffset); + if ((bool)TERRAIN_RippleMap) + { + num = TERRAIN_RippleMap.width; + } + SetShaderParam("rtp_mipoffset_ripple", (0f - Mathf.Log(1024f / ((float)num * TERRAIN_RippleScale))) / Mathf.Log(2f)); + if ((bool)TERRAIN_CausticsTex) + { + num = TERRAIN_CausticsTex.width; + } + SetShaderParam("rtp_mipoffset_caustics", (0f - Mathf.Log(1024f / ((float)num * TERRAIN_CausticsTilingScale))) / Mathf.Log(2f)); + } + Shader.SetGlobalFloat("TERRAIN_GlobalWetness", TERRAIN_GlobalWetness); + SetShaderParam("TERRAIN_RippleMap", TERRAIN_RippleMap); + SetShaderParam("TERRAIN_RippleScale", TERRAIN_RippleScale); + SetShaderParam("TERRAIN_FlowScale", TERRAIN_FlowScale); + SetShaderParam("TERRAIN_FlowMipOffset", TERRAIN_FlowMipOffset); + SetShaderParam("TERRAIN_FlowSpeed", TERRAIN_FlowSpeed); + SetShaderParam("TERRAIN_FlowCycleScale", TERRAIN_FlowCycleScale); + Shader.SetGlobalFloat("TERRAIN_RainIntensity", TERRAIN_RainIntensity); + SetShaderParam("TERRAIN_DropletsSpeed", TERRAIN_DropletsSpeed); + SetShaderParam("TERRAIN_WetDropletsStrength", TERRAIN_WetDropletsStrength); + SetShaderParam("TERRAIN_WetDarkening", TERRAIN_WetDarkening); + SetShaderParam("TERRAIN_mipoffset_flowSpeed", TERRAIN_mipoffset_flowSpeed); + SetShaderParam("TERRAIN_WetHeight_Treshold", TERRAIN_WetHeight_Treshold); + SetShaderParam("TERRAIN_WetHeight_Transition", TERRAIN_WetHeight_Transition); + Shader.SetGlobalVector("RTP_LightDefVector", RTP_LightDefVector); + SetShaderParam("_VerticalTextureGlobalBumpInfluence", VerticalTextureGlobalBumpInfluence); + SetShaderParam("_VerticalTextureTiling", VerticalTextureTiling); + SetShaderParam("_FarSpecCorrection0123", getVector(FarSpecCorrection, 0, 3)); + SetShaderParam("_MIPmult0123", getVector(MIPmult, 0, 3)); + SetShaderParam("_MixScale0123", getVector(MixScale, 0, 3)); + SetShaderParam("_MixBlend0123", getVector(MixBlend, 0, 3)); + SetShaderParam("_MixSaturation0123", getVector(MixSaturation, 0, 3)); + SetShaderParam("RTP_DiffFresnel0123", getVector(RTP_DiffFresnel, 0, 3)); + SetShaderParam("RTP_metallic0123", getVector(RTP_metallic, 0, 3)); + SetShaderParam("RTP_glossMin0123", getVector(RTP_glossMin, 0, 3)); + SetShaderParam("RTP_glossMax0123", getVector(RTP_glossMax, 0, 3)); + SetShaderParam("RTP_glitter0123", getVector(RTP_glitter, 0, 3)); + SetShaderParam("_MixBrightness0123", getVector(MixBrightness, 0, 3)); + SetShaderParam("_MixReplace0123", getVector(MixReplace, 0, 3)); + SetShaderParam("_LayerBrightness0123", MasterLayerBrightness * getVector(LayerBrightness, 0, 3)); + SetShaderParam("_LayerSaturation0123", MasterLayerSaturation * getVector(LayerSaturation, 0, 3)); + SetShaderParam("_LayerEmission0123", getVector(LayerEmission, 0, 3)); + SetShaderParam("_LayerEmissionColorR0123", getColorVector(LayerEmissionColor, 0, 3, 0)); + SetShaderParam("_LayerEmissionColorG0123", getColorVector(LayerEmissionColor, 0, 3, 1)); + SetShaderParam("_LayerEmissionColorB0123", getColorVector(LayerEmissionColor, 0, 3, 2)); + SetShaderParam("_LayerEmissionColorA0123", getColorVector(LayerEmissionColor, 0, 3, 3)); + SetShaderParam("_LayerBrightness2Spec0123", getVector(LayerBrightness2Spec, 0, 3)); + SetShaderParam("_LayerAlbedo2SpecColor0123", getVector(LayerAlbedo2SpecColor, 0, 3)); + SetShaderParam("_LayerEmissionRefractStrength0123", getVector(LayerEmissionRefractStrength, 0, 3)); + SetShaderParam("_LayerEmissionRefractHBedge0123", getVector(LayerEmissionRefractHBedge, 0, 3)); + SetShaderParam("_GlobalColorPerLayer0123", getVector(GlobalColorPerLayer, 0, 3)); + SetShaderParam("_GlobalColorBottom0123", getVector(GlobalColorBottom, 0, 3)); + SetShaderParam("_GlobalColorTop0123", getVector(GlobalColorTop, 0, 3)); + SetShaderParam("_GlobalColorColormapLoSat0123", getVector(GlobalColorColormapLoSat, 0, 3)); + SetShaderParam("_GlobalColorColormapHiSat0123", getVector(GlobalColorColormapHiSat, 0, 3)); + SetShaderParam("_GlobalColorLayerLoSat0123", getVector(GlobalColorLayerLoSat, 0, 3)); + SetShaderParam("_GlobalColorLayerHiSat0123", getVector(GlobalColorLayerHiSat, 0, 3)); + SetShaderParam("_GlobalColorLoBlend0123", getVector(GlobalColorLoBlend, 0, 3)); + SetShaderParam("_GlobalColorHiBlend0123", getVector(GlobalColorHiBlend, 0, 3)); + SetShaderParam("PER_LAYER_HEIGHT_MODIFIER0123", getVector(PER_LAYER_HEIGHT_MODIFIER, 0, 3)); + SetShaderParam("rtp_snow_strength_per_layer0123", getVector(_snow_strength_per_layer, 0, 3)); + SetShaderParam("_SuperDetailStrengthMultA0123", getVector(_SuperDetailStrengthMultA, 0, 3)); + SetShaderParam("_SuperDetailStrengthMultB0123", getVector(_SuperDetailStrengthMultB, 0, 3)); + SetShaderParam("_SuperDetailStrengthNormal0123", getVector(_SuperDetailStrengthNormal, 0, 3)); + SetShaderParam("_BumpMapGlobalStrength0123", getVector(_BumpMapGlobalStrength, 0, 3)); + SetShaderParam("_SuperDetailStrengthMultASelfMaskNear0123", getVector(_SuperDetailStrengthMultASelfMaskNear, 0, 3)); + SetShaderParam("_SuperDetailStrengthMultASelfMaskFar0123", getVector(_SuperDetailStrengthMultASelfMaskFar, 0, 3)); + SetShaderParam("_SuperDetailStrengthMultBSelfMaskNear0123", getVector(_SuperDetailStrengthMultBSelfMaskNear, 0, 3)); + SetShaderParam("_SuperDetailStrengthMultBSelfMaskFar0123", getVector(_SuperDetailStrengthMultBSelfMaskFar, 0, 3)); + SetShaderParam("TERRAIN_LayerWetStrength0123", getVector(TERRAIN_LayerWetStrength, 0, 3)); + SetShaderParam("TERRAIN_WaterLevel0123", getVector(TERRAIN_WaterLevel, 0, 3)); + SetShaderParam("TERRAIN_WaterLevelSlopeDamp0123", getVector(TERRAIN_WaterLevelSlopeDamp, 0, 3)); + SetShaderParam("TERRAIN_WaterEdge0123", getVector(TERRAIN_WaterEdge, 0, 3)); + SetShaderParam("TERRAIN_WaterGloss0123", getVector(TERRAIN_WaterGloss, 0, 3)); + SetShaderParam("TERRAIN_WaterGlossDamper0123", getVector(TERRAIN_WaterGlossDamper, 0, 3)); + SetShaderParam("TERRAIN_Refraction0123", getVector(TERRAIN_Refraction, 0, 3)); + SetShaderParam("TERRAIN_WetRefraction0123", getVector(TERRAIN_WetRefraction, 0, 3)); + SetShaderParam("TERRAIN_Flow0123", getVector(TERRAIN_Flow, 0, 3)); + SetShaderParam("TERRAIN_WetFlow0123", getVector(TERRAIN_WetFlow, 0, 3)); + SetShaderParam("TERRAIN_WaterMetallic0123", getVector(TERRAIN_WaterMetallic, 0, 3)); + SetShaderParam("TERRAIN_WetGloss0123", getVector(TERRAIN_WetGloss, 0, 3)); + SetShaderParam("TERRAIN_WaterColorR0123", getColorVector(TERRAIN_WaterColor, 0, 3, 0)); + SetShaderParam("TERRAIN_WaterColorG0123", getColorVector(TERRAIN_WaterColor, 0, 3, 1)); + SetShaderParam("TERRAIN_WaterColorB0123", getColorVector(TERRAIN_WaterColor, 0, 3, 2)); + SetShaderParam("TERRAIN_WaterColorA0123", getColorVector(TERRAIN_WaterColor, 0, 3, 3)); + SetShaderParam("TERRAIN_WaterEmission0123", getVector(TERRAIN_WaterEmission, 0, 3)); + SetShaderParam("_GlitterStrength0123", getVector(_GlitterStrength, 0, 3)); + SetShaderParam("RTP_AO_0123", getVector(AO_strength, 0, 3)); + SetShaderParam("_VerticalTexture0123", getVector(VerticalTextureStrength, 0, 3)); + if (numLayers > 4 && _4LAYERS_SHADER_USED) + { + SetShaderParam("_FarSpecCorrection89AB", getVector(FarSpecCorrection, 4, 7)); + SetShaderParam("_MIPmult89AB", getVector(MIPmult, 4, 7)); + SetShaderParam("_MixScale89AB", getVector(MixScale, 4, 7)); + SetShaderParam("_MixBlend89AB", getVector(MixBlend, 4, 7)); + SetShaderParam("_MixSaturation89AB", getVector(MixSaturation, 4, 7)); + SetShaderParam("RTP_DiffFresnel89AB", getVector(RTP_DiffFresnel, 4, 7)); + SetShaderParam("RTP_metallic89AB", getVector(RTP_metallic, 4, 7)); + SetShaderParam("RTP_glossMin89AB", getVector(RTP_glossMin, 4, 7)); + SetShaderParam("RTP_glossMax89AB", getVector(RTP_glossMax, 4, 7)); + SetShaderParam("RTP_glitter89AB", getVector(RTP_glitter, 4, 7)); + SetShaderParam("_MixBrightness89AB", getVector(MixBrightness, 4, 7)); + SetShaderParam("_MixReplace89AB", getVector(MixReplace, 4, 7)); + SetShaderParam("_LayerBrightness89AB", MasterLayerBrightness * getVector(LayerBrightness, 4, 7)); + SetShaderParam("_LayerSaturation89AB", MasterLayerSaturation * getVector(LayerSaturation, 4, 7)); + SetShaderParam("_LayerEmission89AB", getVector(LayerEmission, 4, 7)); + SetShaderParam("_LayerEmissionColorR89AB", getColorVector(LayerEmissionColor, 4, 7, 0)); + SetShaderParam("_LayerEmissionColorG89AB", getColorVector(LayerEmissionColor, 4, 7, 1)); + SetShaderParam("_LayerEmissionColorB89AB", getColorVector(LayerEmissionColor, 4, 7, 2)); + SetShaderParam("_LayerEmissionColorA89AB", getColorVector(LayerEmissionColor, 4, 7, 3)); + SetShaderParam("_LayerBrightness2Spec89AB", getVector(LayerBrightness2Spec, 4, 7)); + SetShaderParam("_LayerAlbedo2SpecColor89AB", getVector(LayerAlbedo2SpecColor, 4, 7)); + SetShaderParam("_LayerEmissionRefractStrength89AB", getVector(LayerEmissionRefractStrength, 4, 7)); + SetShaderParam("_LayerEmissionRefractHBedge89AB", getVector(LayerEmissionRefractHBedge, 4, 7)); + SetShaderParam("_GlobalColorPerLayer89AB", getVector(GlobalColorPerLayer, 4, 7)); + SetShaderParam("_GlobalColorBottom89AB", getVector(GlobalColorBottom, 4, 7)); + SetShaderParam("_GlobalColorTop89AB", getVector(GlobalColorTop, 4, 7)); + SetShaderParam("_GlobalColorColormapLoSat89AB", getVector(GlobalColorColormapLoSat, 4, 7)); + SetShaderParam("_GlobalColorColormapHiSat89AB", getVector(GlobalColorColormapHiSat, 4, 7)); + SetShaderParam("_GlobalColorLayerLoSat89AB", getVector(GlobalColorLayerLoSat, 4, 7)); + SetShaderParam("_GlobalColorLayerHiSat89AB", getVector(GlobalColorLayerHiSat, 4, 7)); + SetShaderParam("_GlobalColorLoBlend89AB", getVector(GlobalColorLoBlend, 4, 7)); + SetShaderParam("_GlobalColorHiBlend89AB", getVector(GlobalColorHiBlend, 4, 7)); + SetShaderParam("PER_LAYER_HEIGHT_MODIFIER89AB", getVector(PER_LAYER_HEIGHT_MODIFIER, 4, 7)); + SetShaderParam("rtp_snow_strength_per_layer89AB", getVector(_snow_strength_per_layer, 4, 7)); + SetShaderParam("_SuperDetailStrengthMultA89AB", getVector(_SuperDetailStrengthMultA, 4, 7)); + SetShaderParam("_SuperDetailStrengthMultB89AB", getVector(_SuperDetailStrengthMultB, 4, 7)); + SetShaderParam("_SuperDetailStrengthNormal89AB", getVector(_SuperDetailStrengthNormal, 4, 7)); + SetShaderParam("_BumpMapGlobalStrength89AB", getVector(_BumpMapGlobalStrength, 4, 7)); + SetShaderParam("_SuperDetailStrengthMultASelfMaskNear89AB", getVector(_SuperDetailStrengthMultASelfMaskNear, 4, 7)); + SetShaderParam("_SuperDetailStrengthMultASelfMaskFar89AB", getVector(_SuperDetailStrengthMultASelfMaskFar, 4, 7)); + SetShaderParam("_SuperDetailStrengthMultBSelfMaskNear89AB", getVector(_SuperDetailStrengthMultBSelfMaskNear, 4, 7)); + SetShaderParam("_SuperDetailStrengthMultBSelfMaskFar89AB", getVector(_SuperDetailStrengthMultBSelfMaskFar, 4, 7)); + SetShaderParam("TERRAIN_LayerWetStrength89AB", getVector(TERRAIN_LayerWetStrength, 4, 7)); + SetShaderParam("TERRAIN_WaterLevel89AB", getVector(TERRAIN_WaterLevel, 4, 7)); + SetShaderParam("TERRAIN_WaterLevelSlopeDamp89AB", getVector(TERRAIN_WaterLevelSlopeDamp, 4, 7)); + SetShaderParam("TERRAIN_WaterEdge89AB", getVector(TERRAIN_WaterEdge, 4, 7)); + SetShaderParam("TERRAIN_WaterGloss89AB", getVector(TERRAIN_WaterGloss, 4, 7)); + SetShaderParam("TERRAIN_WaterGlossDamper89AB", getVector(TERRAIN_WaterGlossDamper, 4, 7)); + SetShaderParam("TERRAIN_Refraction89AB", getVector(TERRAIN_Refraction, 4, 7)); + SetShaderParam("TERRAIN_WetRefraction89AB", getVector(TERRAIN_WetRefraction, 4, 7)); + SetShaderParam("TERRAIN_Flow89AB", getVector(TERRAIN_Flow, 4, 7)); + SetShaderParam("TERRAIN_WetFlow89AB", getVector(TERRAIN_WetFlow, 4, 7)); + SetShaderParam("TERRAIN_WaterMetallic89AB", getVector(TERRAIN_WaterMetallic, 4, 7)); + SetShaderParam("TERRAIN_WetGloss89AB", getVector(TERRAIN_WetGloss, 4, 7)); + SetShaderParam("TERRAIN_WaterColorR89AB", getColorVector(TERRAIN_WaterColor, 4, 7, 0)); + SetShaderParam("TERRAIN_WaterColorG89AB", getColorVector(TERRAIN_WaterColor, 4, 7, 1)); + SetShaderParam("TERRAIN_WaterColorB89AB", getColorVector(TERRAIN_WaterColor, 4, 7, 2)); + SetShaderParam("TERRAIN_WaterColorA89AB", getColorVector(TERRAIN_WaterColor, 4, 7, 3)); + SetShaderParam("TERRAIN_WaterEmission89AB", getVector(TERRAIN_WaterEmission, 4, 7)); + SetShaderParam("_GlitterStrength89AB", getVector(_GlitterStrength, 4, 7)); + SetShaderParam("RTP_AO_89AB", getVector(AO_strength, 4, 7)); + SetShaderParam("_VerticalTexture89AB", getVector(VerticalTextureStrength, 4, 7)); + } + else + { + SetShaderParam("_FarSpecCorrection4567", getVector(FarSpecCorrection, 4, 7)); + SetShaderParam("_MIPmult4567", getVector(MIPmult, 4, 7)); + SetShaderParam("_MixScale4567", getVector(MixScale, 4, 7)); + SetShaderParam("_MixBlend4567", getVector(MixBlend, 4, 7)); + SetShaderParam("_MixSaturation4567", getVector(MixSaturation, 4, 7)); + SetShaderParam("RTP_DiffFresnel4567", getVector(RTP_DiffFresnel, 4, 7)); + SetShaderParam("RTP_metallic4567", getVector(RTP_metallic, 4, 7)); + SetShaderParam("RTP_glossMin4567", getVector(RTP_glossMin, 4, 7)); + SetShaderParam("RTP_glossMax4567", getVector(RTP_glossMax, 4, 7)); + SetShaderParam("RTP_glitter4567", getVector(RTP_glitter, 4, 7)); + SetShaderParam("_MixBrightness4567", getVector(MixBrightness, 4, 7)); + SetShaderParam("_MixReplace4567", getVector(MixReplace, 4, 7)); + SetShaderParam("_LayerBrightness4567", MasterLayerBrightness * getVector(LayerBrightness, 4, 7)); + SetShaderParam("_LayerSaturation4567", MasterLayerSaturation * getVector(LayerSaturation, 4, 7)); + SetShaderParam("_LayerEmission4567", getVector(LayerEmission, 4, 7)); + SetShaderParam("_LayerEmissionColorR4567", getColorVector(LayerEmissionColor, 4, 7, 0)); + SetShaderParam("_LayerEmissionColorG4567", getColorVector(LayerEmissionColor, 4, 7, 1)); + SetShaderParam("_LayerEmissionColorB4567", getColorVector(LayerEmissionColor, 4, 7, 2)); + SetShaderParam("_LayerEmissionColorA4567", getColorVector(LayerEmissionColor, 4, 7, 3)); + SetShaderParam("_LayerBrightness2Spec4567", getVector(LayerBrightness2Spec, 4, 7)); + SetShaderParam("_LayerAlbedo2SpecColor4567", getVector(LayerAlbedo2SpecColor, 4, 7)); + SetShaderParam("_LayerEmissionRefractStrength4567", getVector(LayerEmissionRefractStrength, 4, 7)); + SetShaderParam("_LayerEmissionRefractHBedge4567", getVector(LayerEmissionRefractHBedge, 4, 7)); + SetShaderParam("_GlobalColorPerLayer4567", getVector(GlobalColorPerLayer, 4, 7)); + SetShaderParam("_GlobalColorBottom4567", getVector(GlobalColorBottom, 4, 7)); + SetShaderParam("_GlobalColorTop4567", getVector(GlobalColorTop, 4, 7)); + SetShaderParam("_GlobalColorColormapLoSat4567", getVector(GlobalColorColormapLoSat, 4, 7)); + SetShaderParam("_GlobalColorColormapHiSat4567", getVector(GlobalColorColormapHiSat, 4, 7)); + SetShaderParam("_GlobalColorLayerLoSat4567", getVector(GlobalColorLayerLoSat, 4, 7)); + SetShaderParam("_GlobalColorLayerHiSat4567", getVector(GlobalColorLayerHiSat, 4, 7)); + SetShaderParam("_GlobalColorLoBlend4567", getVector(GlobalColorLoBlend, 4, 7)); + SetShaderParam("_GlobalColorHiBlend4567", getVector(GlobalColorHiBlend, 4, 7)); + SetShaderParam("PER_LAYER_HEIGHT_MODIFIER4567", getVector(PER_LAYER_HEIGHT_MODIFIER, 4, 7)); + SetShaderParam("rtp_snow_strength_per_layer4567", getVector(_snow_strength_per_layer, 4, 7)); + SetShaderParam("_SuperDetailStrengthMultA4567", getVector(_SuperDetailStrengthMultA, 4, 7)); + SetShaderParam("_SuperDetailStrengthMultB4567", getVector(_SuperDetailStrengthMultB, 4, 7)); + SetShaderParam("_SuperDetailStrengthNormal4567", getVector(_SuperDetailStrengthNormal, 4, 7)); + SetShaderParam("_BumpMapGlobalStrength4567", getVector(_BumpMapGlobalStrength, 4, 7)); + SetShaderParam("_SuperDetailStrengthMultASelfMaskNear4567", getVector(_SuperDetailStrengthMultASelfMaskNear, 4, 7)); + SetShaderParam("_SuperDetailStrengthMultASelfMaskFar4567", getVector(_SuperDetailStrengthMultASelfMaskFar, 4, 7)); + SetShaderParam("_SuperDetailStrengthMultBSelfMaskNear4567", getVector(_SuperDetailStrengthMultBSelfMaskNear, 4, 7)); + SetShaderParam("_SuperDetailStrengthMultBSelfMaskFar4567", getVector(_SuperDetailStrengthMultBSelfMaskFar, 4, 7)); + SetShaderParam("TERRAIN_LayerWetStrength4567", getVector(TERRAIN_LayerWetStrength, 4, 7)); + SetShaderParam("TERRAIN_WaterLevel4567", getVector(TERRAIN_WaterLevel, 4, 7)); + SetShaderParam("TERRAIN_WaterLevelSlopeDamp4567", getVector(TERRAIN_WaterLevelSlopeDamp, 4, 7)); + SetShaderParam("TERRAIN_WaterEdge4567", getVector(TERRAIN_WaterEdge, 4, 7)); + SetShaderParam("TERRAIN_WaterGloss4567", getVector(TERRAIN_WaterGloss, 4, 7)); + SetShaderParam("TERRAIN_WaterGlossDamper4567", getVector(TERRAIN_WaterGlossDamper, 4, 7)); + SetShaderParam("TERRAIN_Refraction4567", getVector(TERRAIN_Refraction, 4, 7)); + SetShaderParam("TERRAIN_WetRefraction4567", getVector(TERRAIN_WetRefraction, 4, 7)); + SetShaderParam("TERRAIN_Flow4567", getVector(TERRAIN_Flow, 4, 7)); + SetShaderParam("TERRAIN_WetFlow4567", getVector(TERRAIN_WetFlow, 4, 7)); + SetShaderParam("TERRAIN_WaterMetallic4567", getVector(TERRAIN_WaterMetallic, 4, 7)); + SetShaderParam("TERRAIN_WetGloss4567", getVector(TERRAIN_WetGloss, 4, 7)); + SetShaderParam("TERRAIN_WaterColorR4567", getColorVector(TERRAIN_WaterColor, 4, 7, 0)); + SetShaderParam("TERRAIN_WaterColorG4567", getColorVector(TERRAIN_WaterColor, 4, 7, 1)); + SetShaderParam("TERRAIN_WaterColorB4567", getColorVector(TERRAIN_WaterColor, 4, 7, 2)); + SetShaderParam("TERRAIN_WaterColorA4567", getColorVector(TERRAIN_WaterColor, 4, 7, 3)); + SetShaderParam("TERRAIN_WaterEmission4567", getVector(TERRAIN_WaterEmission, 4, 7)); + SetShaderParam("_GlitterStrength4567", getVector(_GlitterStrength, 4, 7)); + SetShaderParam("RTP_AO_4567", getVector(AO_strength, 4, 7)); + SetShaderParam("_VerticalTexture4567", getVector(VerticalTextureStrength, 4, 7)); + SetShaderParam("_FarSpecCorrection89AB", getVector(FarSpecCorrection, 8, 11)); + SetShaderParam("_MIPmult89AB", getVector(MIPmult, 8, 11)); + SetShaderParam("_MixScale89AB", getVector(MixScale, 8, 11)); + SetShaderParam("_MixBlend89AB", getVector(MixBlend, 8, 11)); + SetShaderParam("_MixSaturation89AB", getVector(MixSaturation, 8, 11)); + SetShaderParam("RTP_DiffFresnel89AB", getVector(RTP_DiffFresnel, 8, 11)); + SetShaderParam("RTP_metallic89AB", getVector(RTP_metallic, 8, 11)); + SetShaderParam("RTP_glossMin89AB", getVector(RTP_glossMin, 8, 11)); + SetShaderParam("RTP_glossMax89AB", getVector(RTP_glossMax, 8, 11)); + SetShaderParam("RTP_glitter89AB", getVector(RTP_glitter, 8, 11)); + SetShaderParam("_MixBrightness89AB", getVector(MixBrightness, 8, 11)); + SetShaderParam("_MixReplace89AB", getVector(MixReplace, 8, 11)); + SetShaderParam("_LayerBrightness89AB", MasterLayerBrightness * getVector(LayerBrightness, 8, 11)); + SetShaderParam("_LayerSaturation89AB", MasterLayerSaturation * getVector(LayerSaturation, 8, 11)); + SetShaderParam("_LayerEmission89AB", getVector(LayerEmission, 8, 11)); + SetShaderParam("_LayerEmissionColorR89AB", getColorVector(LayerEmissionColor, 8, 11, 0)); + SetShaderParam("_LayerEmissionColorG89AB", getColorVector(LayerEmissionColor, 8, 11, 1)); + SetShaderParam("_LayerEmissionColorB89AB", getColorVector(LayerEmissionColor, 8, 11, 2)); + SetShaderParam("_LayerEmissionColorA89AB", getColorVector(LayerEmissionColor, 8, 11, 3)); + SetShaderParam("_LayerBrightness2Spec89AB", getVector(LayerBrightness2Spec, 8, 11)); + SetShaderParam("_LayerAlbedo2SpecColor89AB", getVector(LayerAlbedo2SpecColor, 8, 11)); + SetShaderParam("_LayerEmissionRefractStrength89AB", getVector(LayerEmissionRefractStrength, 8, 11)); + SetShaderParam("_LayerEmissionRefractHBedge89AB", getVector(LayerEmissionRefractHBedge, 8, 11)); + SetShaderParam("_GlobalColorPerLayer89AB", getVector(GlobalColorPerLayer, 8, 11)); + SetShaderParam("_GlobalColorBottom89AB", getVector(GlobalColorBottom, 8, 11)); + SetShaderParam("_GlobalColorTop89AB", getVector(GlobalColorTop, 8, 11)); + SetShaderParam("_GlobalColorColormapLoSat89AB", getVector(GlobalColorColormapLoSat, 8, 11)); + SetShaderParam("_GlobalColorColormapHiSat89AB", getVector(GlobalColorColormapHiSat, 8, 11)); + SetShaderParam("_GlobalColorLayerLoSat89AB", getVector(GlobalColorLayerLoSat, 8, 11)); + SetShaderParam("_GlobalColorLayerHiSat89AB", getVector(GlobalColorLayerHiSat, 8, 11)); + SetShaderParam("_GlobalColorLoBlend89AB", getVector(GlobalColorLoBlend, 8, 11)); + SetShaderParam("_GlobalColorHiBlend89AB", getVector(GlobalColorHiBlend, 8, 11)); + SetShaderParam("PER_LAYER_HEIGHT_MODIFIER89AB", getVector(PER_LAYER_HEIGHT_MODIFIER, 8, 11)); + SetShaderParam("rtp_snow_strength_per_layer89AB", getVector(_snow_strength_per_layer, 8, 11)); + SetShaderParam("_SuperDetailStrengthMultA89AB", getVector(_SuperDetailStrengthMultA, 8, 11)); + SetShaderParam("_SuperDetailStrengthMultB89AB", getVector(_SuperDetailStrengthMultB, 8, 11)); + SetShaderParam("_SuperDetailStrengthNormal89AB", getVector(_SuperDetailStrengthNormal, 8, 11)); + SetShaderParam("_BumpMapGlobalStrength89AB", getVector(_BumpMapGlobalStrength, 8, 11)); + SetShaderParam("_SuperDetailStrengthMultASelfMaskNear89AB", getVector(_SuperDetailStrengthMultASelfMaskNear, 8, 11)); + SetShaderParam("_SuperDetailStrengthMultASelfMaskFar89AB", getVector(_SuperDetailStrengthMultASelfMaskFar, 8, 11)); + SetShaderParam("_SuperDetailStrengthMultBSelfMaskNear89AB", getVector(_SuperDetailStrengthMultBSelfMaskNear, 8, 11)); + SetShaderParam("_SuperDetailStrengthMultBSelfMaskFar89AB", getVector(_SuperDetailStrengthMultBSelfMaskFar, 8, 11)); + SetShaderParam("TERRAIN_LayerWetStrength89AB", getVector(TERRAIN_LayerWetStrength, 8, 11)); + SetShaderParam("TERRAIN_WaterLevel89AB", getVector(TERRAIN_WaterLevel, 8, 11)); + SetShaderParam("TERRAIN_WaterLevelSlopeDamp89AB", getVector(TERRAIN_WaterLevelSlopeDamp, 8, 11)); + SetShaderParam("TERRAIN_WaterEdge89AB", getVector(TERRAIN_WaterEdge, 8, 11)); + SetShaderParam("TERRAIN_WaterGloss89AB", getVector(TERRAIN_WaterGloss, 8, 11)); + SetShaderParam("TERRAIN_WaterGlossDamper89AB", getVector(TERRAIN_WaterGlossDamper, 8, 11)); + SetShaderParam("TERRAIN_Refraction89AB", getVector(TERRAIN_Refraction, 8, 11)); + SetShaderParam("TERRAIN_WetRefraction89AB", getVector(TERRAIN_WetRefraction, 8, 11)); + SetShaderParam("TERRAIN_Flow89AB", getVector(TERRAIN_Flow, 8, 11)); + SetShaderParam("TERRAIN_WetFlow89AB", getVector(TERRAIN_WetFlow, 8, 11)); + SetShaderParam("TERRAIN_WaterMetallic89AB", getVector(TERRAIN_WaterMetallic, 8, 11)); + SetShaderParam("TERRAIN_WetGloss89AB", getVector(TERRAIN_WetGloss, 8, 11)); + SetShaderParam("TERRAIN_WaterColorR89AB", getColorVector(TERRAIN_WaterColor, 8, 11, 0)); + SetShaderParam("TERRAIN_WaterColorG89AB", getColorVector(TERRAIN_WaterColor, 8, 11, 1)); + SetShaderParam("TERRAIN_WaterColorB89AB", getColorVector(TERRAIN_WaterColor, 8, 11, 2)); + SetShaderParam("TERRAIN_WaterColorA89AB", getColorVector(TERRAIN_WaterColor, 8, 11, 3)); + SetShaderParam("TERRAIN_WaterEmission89AB", getVector(TERRAIN_WaterEmission, 8, 11)); + SetShaderParam("_GlitterStrength89AB", getVector(_GlitterStrength, 8, 11)); + SetShaderParam("RTP_AO_89AB", getVector(AO_strength, 8, 11)); + SetShaderParam("_VerticalTexture89AB", getVector(VerticalTextureStrength, 8, 11)); + } + if (splat_atlases.Length == 2) + { + Texture2D texture2D = splat_atlases[0]; + Texture2D texture2D2 = splat_atlases[1]; + splat_atlases = new Texture2D[3]; + splat_atlases[0] = texture2D; + splat_atlases[1] = texture2D2; + } + SetShaderParam("_SplatAtlasA", splat_atlases[0]); + SetShaderParam("_BumpMap01", Bump01); + SetShaderParam("_BumpMap23", Bump23); + SetShaderParam("_TERRAIN_HeightMap", HeightMap); + SetShaderParam("_SSColorCombinedA", SSColorCombinedA); + if (numLayers > 4) + { + SetShaderParam("_SplatAtlasB", splat_atlases[1]); + SetShaderParam("_SplatAtlasC", splat_atlases[1]); + SetShaderParam("_TERRAIN_HeightMap2", HeightMap2); + SetShaderParam("_SSColorCombinedB", SSColorCombinedB); + } + if (numLayers > 8) + { + SetShaderParam("_SplatAtlasC", splat_atlases[2]); + } + if (numLayers > 4 && _4LAYERS_SHADER_USED) + { + SetShaderParam("_BumpMap89", Bump45); + SetShaderParam("_BumpMapAB", Bump67); + SetShaderParam("_TERRAIN_HeightMap3", HeightMap2); + SetShaderParam("_BumpMap45", Bump45); + SetShaderParam("_BumpMap67", Bump67); + } + else + { + SetShaderParam("_BumpMap45", Bump45); + SetShaderParam("_BumpMap67", Bump67); + SetShaderParam("_BumpMap89", Bump89); + SetShaderParam("_BumpMapAB", BumpAB); + SetShaderParam("_TERRAIN_HeightMap3", HeightMap3); + } + use_mat = null; + } + + public Vector4 getVector(float[] vec, int idxA, int idxB) + { + if (vec == null) + { + return Vector4.zero; + } + Vector4 zero = Vector4.zero; + for (int i = idxA; i <= idxB; i++) + { + if (i < vec.Length) + { + zero[i - idxA] = vec[i]; + } + } + return zero; + } + + public Vector4 getColorVector(Color[] vec, int idxA, int idxB, int channel) + { + if (vec == null) + { + return Vector4.zero; + } + Vector4 zero = Vector4.zero; + for (int i = idxA; i <= idxB; i++) + { + if (i < vec.Length) + { + zero[i - idxA] = vec[i][channel]; + } + } + return zero; + } + + public Texture2D get_dumb_tex() + { + if (!dumb_tex) + { + dumb_tex = new Texture2D(32, 32, TextureFormat.RGB24, mipmap: false); + Color[] pixels = dumb_tex.GetPixels(); + for (int i = 0; i < pixels.Length; i++) + { + ref Color reference = ref pixels[i]; + reference = Color.white; + } + dumb_tex.SetPixels(pixels); + dumb_tex.Apply(); + } + return dumb_tex; + } + + public void SyncGlobalPropsAcrossTerrainGroups() + { + ReliefTerrain[] array = (ReliefTerrain[])UnityEngine.Object.FindObjectsOfType(typeof(ReliefTerrain)); + ReliefTerrainGlobalSettingsHolder[] array2 = new ReliefTerrainGlobalSettingsHolder[array.Length]; + int num = 0; + for (int i = 0; i < array.Length; i++) + { + bool flag = false; + for (int j = 0; j < num; j++) + { + if (array2[j] == array[i].globalSettingsHolder) + { + flag = true; + break; + } + } + if (!flag) + { + array2[num++] = array[i].globalSettingsHolder; + } + } + for (int k = 0; k < num; k++) + { + if (array2[k] != this) + { + array2[k].trees_shadow_distance_start = trees_shadow_distance_start; + array2[k].trees_shadow_distance_transition = trees_shadow_distance_transition; + array2[k].trees_shadow_value = trees_shadow_value; + array2[k].global_normalMap_multiplier = global_normalMap_multiplier; + array2[k].trees_pixel_distance_start = trees_pixel_distance_start; + array2[k].trees_pixel_distance_transition = trees_pixel_distance_transition; + array2[k].trees_pixel_blend_val = trees_pixel_blend_val; + array2[k].global_normalMap_farUsage = global_normalMap_farUsage; + array2[k]._AmbientEmissiveMultiplier = _AmbientEmissiveMultiplier; + array2[k]._AmbientEmissiveRelief = _AmbientEmissiveRelief; + array2[k]._snow_strength = _snow_strength; + array2[k]._global_color_brightness_to_snow = _global_color_brightness_to_snow; + array2[k]._snow_slope_factor = _snow_slope_factor; + array2[k]._snow_edge_definition = _snow_edge_definition; + array2[k]._snow_height_treshold = _snow_height_treshold; + array2[k]._snow_height_transition = _snow_height_transition; + array2[k]._snow_color = _snow_color; + array2[k]._snow_gloss = _snow_gloss; + array2[k]._snow_reflectivness = _snow_reflectivness; + array2[k]._snow_deep_factor = _snow_deep_factor; + array2[k]._snow_diff_fresnel = _snow_diff_fresnel; + array2[k]._snow_metallic = _snow_metallic; + array2[k]._snow_Frost = _snow_Frost; + array2[k]._snow_MicroTiling = _snow_MicroTiling; + array2[k]._snow_BumpMicro = _snow_BumpMicro; + array2[k]._snow_occlusionStrength = _snow_occlusionStrength; + array2[k]._snow_TranslucencyDeferredLightIndex = _snow_TranslucencyDeferredLightIndex; + array2[k]._SnowGlitterColor = _SnowGlitterColor; + array2[k]._GlitterColor = _GlitterColor; + array2[k]._GlitterTiling = _GlitterTiling; + array2[k]._GlitterDensity = _GlitterDensity; + array2[k]._GlitterFilter = _GlitterFilter; + array2[k]._GlitterColorization = _GlitterColorization; + array2[k]._SparkleMap = _SparkleMap; + array2[k].TERRAIN_CausticsWaterLevel = TERRAIN_CausticsWaterLevel; + array2[k].TERRAIN_CausticsWaterLevelByAngle = TERRAIN_CausticsWaterLevelByAngle; + array2[k].TERRAIN_CausticsWaterDeepFadeLength = TERRAIN_CausticsWaterDeepFadeLength; + array2[k].TERRAIN_CausticsWaterShallowFadeLength = TERRAIN_CausticsWaterShallowFadeLength; + array2[k].TERRAIN_GlobalWetness = TERRAIN_GlobalWetness; + array2[k].TERRAIN_RainIntensity = TERRAIN_RainIntensity; + array2[k].RTP_LightDefVector = RTP_LightDefVector; + } + } + } + + public void RestorePreset(ReliefTerrainPresetHolder holder) + { + numLayers = holder.numLayers; + splats = new Texture2D[holder.splats.Length]; + for (int i = 0; i < holder.splats.Length; i++) + { + splats[i] = holder.splats[i]; + } + splat_atlases = new Texture2D[3]; + for (int j = 0; j < splat_atlases.Length; j++) + { + splat_atlases[j] = holder.splat_atlases[j]; + } + RTP_MIP_BIAS = holder.RTP_MIP_BIAS; + MasterLayerBrightness = holder.MasterLayerBrightness; + MasterLayerSaturation = holder.MasterLayerSaturation; + SuperDetailA_channel = holder.SuperDetailA_channel; + SuperDetailB_channel = holder.SuperDetailB_channel; + Bump01 = holder.Bump01; + Bump23 = holder.Bump23; + Bump45 = holder.Bump45; + Bump67 = holder.Bump67; + Bump89 = holder.Bump89; + BumpAB = holder.BumpAB; + SSColorCombinedA = holder.SSColorCombinedA; + SSColorCombinedB = holder.SSColorCombinedB; + BumpGlobal = holder.BumpGlobal; + VerticalTexture = holder.VerticalTexture; + BumpMapGlobalScale = holder.BumpMapGlobalScale; + GlobalColorMapBlendValues = holder.GlobalColorMapBlendValues; + GlobalColorMapSaturation = holder.GlobalColorMapSaturation; + GlobalColorMapSaturationFar = holder.GlobalColorMapSaturationFar; + GlobalColorMapDistortByPerlin = holder.GlobalColorMapDistortByPerlin; + GlobalColorMapBrightness = holder.GlobalColorMapBrightness; + GlobalColorMapBrightnessFar = holder.GlobalColorMapBrightnessFar; + _GlobalColorMapNearMIP = holder._GlobalColorMapNearMIP; + _FarNormalDamp = holder._FarNormalDamp; + blendMultiplier = holder.blendMultiplier; + HeightMap = holder.HeightMap; + HeightMap2 = holder.HeightMap2; + HeightMap3 = holder.HeightMap3; + ReliefTransform = holder.ReliefTransform; + DIST_STEPS = holder.DIST_STEPS; + WAVELENGTH = holder.WAVELENGTH; + ReliefBorderBlend = holder.ReliefBorderBlend; + ExtrudeHeight = holder.ExtrudeHeight; + LightmapShading = holder.LightmapShading; + SHADOW_STEPS = holder.SHADOW_STEPS; + WAVELENGTH_SHADOWS = holder.WAVELENGTH_SHADOWS; + SelfShadowStrength = holder.SelfShadowStrength; + ShadowSmoothing = holder.ShadowSmoothing; + ShadowSoftnessFade = holder.ShadowSoftnessFade; + distance_start = holder.distance_start; + distance_transition = holder.distance_transition; + distance_start_bumpglobal = holder.distance_start_bumpglobal; + distance_transition_bumpglobal = holder.distance_transition_bumpglobal; + rtp_perlin_start_val = holder.rtp_perlin_start_val; + _Phong = holder._Phong; + tessHeight = holder.tessHeight; + _TessSubdivisions = holder._TessSubdivisions; + _TessSubdivisionsFar = holder._TessSubdivisionsFar; + _TessYOffset = holder._TessYOffset; + trees_shadow_distance_start = holder.trees_shadow_distance_start; + trees_shadow_distance_transition = holder.trees_shadow_distance_transition; + trees_shadow_value = holder.trees_shadow_value; + trees_pixel_distance_start = holder.trees_pixel_distance_start; + trees_pixel_distance_transition = holder.trees_pixel_distance_transition; + trees_pixel_blend_val = holder.trees_pixel_blend_val; + global_normalMap_multiplier = holder.global_normalMap_multiplier; + global_normalMap_farUsage = holder.global_normalMap_farUsage; + _AmbientEmissiveMultiplier = holder._AmbientEmissiveMultiplier; + _AmbientEmissiveRelief = holder._AmbientEmissiveRelief; + rtp_mipoffset_globalnorm = holder.rtp_mipoffset_globalnorm; + _SuperDetailTiling = holder._SuperDetailTiling; + SuperDetailA = holder.SuperDetailA; + SuperDetailB = holder.SuperDetailB; + TERRAIN_GlobalWetness = holder.TERRAIN_GlobalWetness; + TERRAIN_RippleMap = holder.TERRAIN_RippleMap; + TERRAIN_RippleScale = holder.TERRAIN_RippleScale; + TERRAIN_FlowScale = holder.TERRAIN_FlowScale; + TERRAIN_FlowSpeed = holder.TERRAIN_FlowSpeed; + TERRAIN_FlowCycleScale = holder.TERRAIN_FlowCycleScale; + TERRAIN_FlowMipOffset = holder.TERRAIN_FlowMipOffset; + TERRAIN_WetDarkening = holder.TERRAIN_WetDarkening; + TERRAIN_WetDropletsStrength = holder.TERRAIN_WetDropletsStrength; + TERRAIN_WetHeight_Treshold = holder.TERRAIN_WetHeight_Treshold; + TERRAIN_WetHeight_Transition = holder.TERRAIN_WetHeight_Transition; + TERRAIN_RainIntensity = holder.TERRAIN_RainIntensity; + TERRAIN_DropletsSpeed = holder.TERRAIN_DropletsSpeed; + TERRAIN_mipoffset_flowSpeed = holder.TERRAIN_mipoffset_flowSpeed; + TERRAIN_CausticsAnimSpeed = holder.TERRAIN_CausticsAnimSpeed; + TERRAIN_CausticsColor = holder.TERRAIN_CausticsColor; + TERRAIN_CausticsWaterLevel = holder.TERRAIN_CausticsWaterLevel; + TERRAIN_CausticsWaterLevelByAngle = holder.TERRAIN_CausticsWaterLevelByAngle; + TERRAIN_CausticsWaterDeepFadeLength = holder.TERRAIN_CausticsWaterDeepFadeLength; + TERRAIN_CausticsWaterShallowFadeLength = holder.TERRAIN_CausticsWaterShallowFadeLength; + TERRAIN_CausticsTilingScale = holder.TERRAIN_CausticsTilingScale; + TERRAIN_CausticsTex = holder.TERRAIN_CausticsTex; + RTP_AOsharpness = holder.RTP_AOsharpness; + RTP_AOamp = holder.RTP_AOamp; + _occlusionStrength = holder._occlusionStrength; + RTP_LightDefVector = holder.RTP_LightDefVector; + EmissionRefractFiltering = holder.EmissionRefractFiltering; + EmissionRefractAnimSpeed = holder.EmissionRefractAnimSpeed; + VerticalTextureGlobalBumpInfluence = holder.VerticalTextureGlobalBumpInfluence; + VerticalTextureTiling = holder.VerticalTextureTiling; + _snow_strength = holder._snow_strength; + _global_color_brightness_to_snow = holder._global_color_brightness_to_snow; + _snow_slope_factor = holder._snow_slope_factor; + _snow_edge_definition = holder._snow_edge_definition; + _snow_height_treshold = holder._snow_height_treshold; + _snow_height_transition = holder._snow_height_transition; + _snow_color = holder._snow_color; + _snow_gloss = holder._snow_gloss; + _snow_reflectivness = holder._snow_reflectivness; + _snow_deep_factor = holder._snow_deep_factor; + _snow_diff_fresnel = holder._snow_diff_fresnel; + _snow_metallic = holder._snow_metallic; + _snow_Frost = holder._snow_Frost; + _snow_MicroTiling = holder._snow_MicroTiling; + _snow_BumpMicro = holder._snow_BumpMicro; + _snow_occlusionStrength = holder._snow_occlusionStrength; + _snow_TranslucencyDeferredLightIndex = holder._snow_TranslucencyDeferredLightIndex; + _SnowGlitterColor = holder._SnowGlitterColor; + _GlitterColor = holder._GlitterColor; + _GlitterTiling = holder._GlitterTiling; + _GlitterDensity = holder._GlitterDensity; + _GlitterFilter = holder._GlitterFilter; + _GlitterColorization = holder._GlitterColorization; + _SparkleMap = holder._SparkleMap; + Bumps = new Texture2D[holder.Bumps.Length]; + FarSpecCorrection = new float[holder.Bumps.Length]; + MixScale = new float[holder.Bumps.Length]; + MixBlend = new float[holder.Bumps.Length]; + MixSaturation = new float[holder.Bumps.Length]; + RTP_DiffFresnel = new float[holder.Bumps.Length]; + RTP_metallic = new float[holder.Bumps.Length]; + RTP_glossMin = new float[holder.Bumps.Length]; + RTP_glossMax = new float[holder.Bumps.Length]; + RTP_glitter = new float[holder.Bumps.Length]; + MixBrightness = new float[holder.Bumps.Length]; + MixReplace = new float[holder.Bumps.Length]; + LayerBrightness = new float[holder.Bumps.Length]; + LayerBrightness2Spec = new float[holder.Bumps.Length]; + LayerAlbedo2SpecColor = new float[holder.Bumps.Length]; + LayerSaturation = new float[holder.Bumps.Length]; + LayerEmission = new float[holder.Bumps.Length]; + LayerEmissionColor = new Color[holder.Bumps.Length]; + LayerEmissionRefractStrength = new float[holder.Bumps.Length]; + LayerEmissionRefractHBedge = new float[holder.Bumps.Length]; + GlobalColorPerLayer = new float[holder.Bumps.Length]; + GlobalColorBottom = new float[holder.Bumps.Length]; + GlobalColorTop = new float[holder.Bumps.Length]; + GlobalColorColormapLoSat = new float[holder.Bumps.Length]; + GlobalColorColormapHiSat = new float[holder.Bumps.Length]; + GlobalColorLayerLoSat = new float[holder.Bumps.Length]; + GlobalColorLayerHiSat = new float[holder.Bumps.Length]; + GlobalColorLoBlend = new float[holder.Bumps.Length]; + GlobalColorHiBlend = new float[holder.Bumps.Length]; + PER_LAYER_HEIGHT_MODIFIER = new float[holder.Bumps.Length]; + _SuperDetailStrengthMultA = new float[holder.Bumps.Length]; + _SuperDetailStrengthMultASelfMaskNear = new float[holder.Bumps.Length]; + _SuperDetailStrengthMultASelfMaskFar = new float[holder.Bumps.Length]; + _SuperDetailStrengthMultB = new float[holder.Bumps.Length]; + _SuperDetailStrengthMultBSelfMaskNear = new float[holder.Bumps.Length]; + _SuperDetailStrengthMultBSelfMaskFar = new float[holder.Bumps.Length]; + _SuperDetailStrengthNormal = new float[holder.Bumps.Length]; + _BumpMapGlobalStrength = new float[holder.Bumps.Length]; + AO_strength = new float[holder.Bumps.Length]; + VerticalTextureStrength = new float[holder.Bumps.Length]; + Heights = new Texture2D[holder.Bumps.Length]; + _snow_strength_per_layer = new float[holder.Bumps.Length]; + Substances = new ProceduralMaterial[holder.Bumps.Length]; + TERRAIN_LayerWetStrength = new float[holder.Bumps.Length]; + TERRAIN_WaterLevel = new float[holder.Bumps.Length]; + TERRAIN_WaterLevelSlopeDamp = new float[holder.Bumps.Length]; + TERRAIN_WaterEdge = new float[holder.Bumps.Length]; + TERRAIN_WaterGloss = new float[holder.Bumps.Length]; + TERRAIN_WaterGlossDamper = new float[holder.Bumps.Length]; + TERRAIN_Refraction = new float[holder.Bumps.Length]; + TERRAIN_WetRefraction = new float[holder.Bumps.Length]; + TERRAIN_Flow = new float[holder.Bumps.Length]; + TERRAIN_WetFlow = new float[holder.Bumps.Length]; + TERRAIN_WaterMetallic = new float[holder.Bumps.Length]; + TERRAIN_WetGloss = new float[holder.Bumps.Length]; + TERRAIN_WaterColor = new Color[holder.Bumps.Length]; + TERRAIN_WaterEmission = new float[holder.Bumps.Length]; + _GlitterStrength = new float[holder.Bumps.Length]; + for (int k = 0; k < holder.Bumps.Length; k++) + { + Bumps[k] = holder.Bumps[k]; + FarSpecCorrection[k] = holder.FarSpecCorrection[k]; + MixScale[k] = holder.MixScale[k]; + MixBlend[k] = holder.MixBlend[k]; + MixSaturation[k] = holder.MixSaturation[k]; + CheckAndUpdate(ref holder.RTP_DiffFresnel, 0f, holder.Bumps.Length); + CheckAndUpdate(ref holder.RTP_metallic, 0f, holder.Bumps.Length); + CheckAndUpdate(ref holder.RTP_glossMin, 0f, holder.Bumps.Length); + CheckAndUpdate(ref holder.RTP_glossMax, 1f, holder.Bumps.Length); + CheckAndUpdate(ref holder.RTP_glitter, 0f, holder.Bumps.Length); + CheckAndUpdate(ref holder.TERRAIN_WaterGloss, 0.1f, holder.Bumps.Length); + CheckAndUpdate(ref holder.TERRAIN_WaterGlossDamper, 0f, holder.Bumps.Length); + CheckAndUpdate(ref holder.TERRAIN_WaterMetallic, 0.1f, holder.Bumps.Length); + CheckAndUpdate(ref holder.TERRAIN_WetGloss, 0.05f, holder.Bumps.Length); + CheckAndUpdate(ref holder.TERRAIN_WetFlow, 0.05f, holder.Bumps.Length); + CheckAndUpdate(ref holder.MixBrightness, 2f, holder.Bumps.Length); + CheckAndUpdate(ref holder.MixReplace, 0f, holder.Bumps.Length); + CheckAndUpdate(ref holder.LayerBrightness, 1f, holder.Bumps.Length); + CheckAndUpdate(ref holder.LayerBrightness2Spec, 0f, holder.Bumps.Length); + CheckAndUpdate(ref holder.LayerAlbedo2SpecColor, 0f, holder.Bumps.Length); + CheckAndUpdate(ref holder.LayerSaturation, 1f, holder.Bumps.Length); + CheckAndUpdate(ref holder.LayerEmission, 1f, holder.Bumps.Length); + CheckAndUpdate(ref holder.LayerEmissionColor, Color.black, holder.Bumps.Length); + CheckAndUpdate(ref holder.FarSpecCorrection, 0f, holder.Bumps.Length); + CheckAndUpdate(ref holder.LayerEmissionRefractStrength, 0f, holder.Bumps.Length); + CheckAndUpdate(ref holder.LayerEmissionRefractHBedge, 0f, holder.Bumps.Length); + CheckAndUpdate(ref holder.TERRAIN_WaterEmission, 0f, holder.Bumps.Length); + CheckAndUpdate(ref holder._GlitterStrength, 0f, holder.Bumps.Length); + RTP_DiffFresnel[k] = holder.RTP_DiffFresnel[k]; + RTP_metallic[k] = holder.RTP_metallic[k]; + RTP_glossMin[k] = holder.RTP_glossMin[k]; + RTP_glossMax[k] = holder.RTP_glossMax[k]; + RTP_glitter[k] = holder.RTP_glitter[k]; + MixBrightness[k] = holder.MixBrightness[k]; + MixReplace[k] = holder.MixReplace[k]; + LayerBrightness[k] = holder.LayerBrightness[k]; + LayerBrightness2Spec[k] = holder.LayerBrightness2Spec[k]; + LayerAlbedo2SpecColor[k] = holder.LayerAlbedo2SpecColor[k]; + LayerSaturation[k] = holder.LayerSaturation[k]; + LayerEmission[k] = holder.LayerEmission[k]; + ref Color reference = ref LayerEmissionColor[k]; + reference = holder.LayerEmissionColor[k]; + LayerEmissionRefractStrength[k] = holder.LayerEmissionRefractStrength[k]; + LayerEmissionRefractHBedge[k] = holder.LayerEmissionRefractHBedge[k]; + GlobalColorPerLayer[k] = holder.GlobalColorPerLayer[k]; + GlobalColorBottom[k] = holder.GlobalColorBottom[k]; + GlobalColorTop[k] = holder.GlobalColorTop[k]; + GlobalColorColormapLoSat[k] = holder.GlobalColorColormapLoSat[k]; + GlobalColorColormapHiSat[k] = holder.GlobalColorColormapHiSat[k]; + GlobalColorLayerLoSat[k] = holder.GlobalColorLayerLoSat[k]; + GlobalColorLayerHiSat[k] = holder.GlobalColorLayerHiSat[k]; + GlobalColorLoBlend[k] = holder.GlobalColorLoBlend[k]; + GlobalColorHiBlend[k] = holder.GlobalColorHiBlend[k]; + PER_LAYER_HEIGHT_MODIFIER[k] = holder.PER_LAYER_HEIGHT_MODIFIER[k]; + _SuperDetailStrengthMultA[k] = holder._SuperDetailStrengthMultA[k]; + _SuperDetailStrengthMultASelfMaskNear[k] = holder._SuperDetailStrengthMultASelfMaskNear[k]; + _SuperDetailStrengthMultASelfMaskFar[k] = holder._SuperDetailStrengthMultASelfMaskFar[k]; + _SuperDetailStrengthMultB[k] = holder._SuperDetailStrengthMultB[k]; + _SuperDetailStrengthMultBSelfMaskNear[k] = holder._SuperDetailStrengthMultBSelfMaskNear[k]; + _SuperDetailStrengthMultBSelfMaskFar[k] = holder._SuperDetailStrengthMultBSelfMaskFar[k]; + _SuperDetailStrengthNormal[k] = holder._SuperDetailStrengthNormal[k]; + _BumpMapGlobalStrength[k] = holder._BumpMapGlobalStrength[k]; + VerticalTextureStrength[k] = holder.VerticalTextureStrength[k]; + AO_strength[k] = holder.AO_strength[k]; + Heights[k] = holder.Heights[k]; + _snow_strength_per_layer[k] = holder._snow_strength_per_layer[k]; + Substances[k] = holder.Substances[k]; + TERRAIN_LayerWetStrength[k] = holder.TERRAIN_LayerWetStrength[k]; + TERRAIN_WaterLevel[k] = holder.TERRAIN_WaterLevel[k]; + TERRAIN_WaterLevelSlopeDamp[k] = holder.TERRAIN_WaterLevelSlopeDamp[k]; + TERRAIN_WaterEdge[k] = holder.TERRAIN_WaterEdge[k]; + TERRAIN_WaterGloss[k] = holder.TERRAIN_WaterGloss[k]; + TERRAIN_WaterGlossDamper[k] = holder.TERRAIN_WaterGlossDamper[k]; + TERRAIN_Refraction[k] = holder.TERRAIN_Refraction[k]; + TERRAIN_WetRefraction[k] = holder.TERRAIN_WetRefraction[k]; + TERRAIN_Flow[k] = holder.TERRAIN_Flow[k]; + TERRAIN_WetFlow[k] = holder.TERRAIN_WetFlow[k]; + TERRAIN_WaterMetallic[k] = holder.TERRAIN_WaterMetallic[k]; + TERRAIN_WetGloss[k] = holder.TERRAIN_WetGloss[k]; + ref Color reference2 = ref TERRAIN_WaterColor[k]; + reference2 = holder.TERRAIN_WaterColor[k]; + TERRAIN_WaterEmission[k] = holder.TERRAIN_WaterEmission[k]; + _GlitterStrength[k] = holder._GlitterStrength[k]; + } + } + + public void GlossBakeJob(Texture2D detailTex, Texture2D normalTex) + { + bakeJobArray = new Texture2D[2] { detailTex, normalTex }; + } + + public void SavePreset(ref ReliefTerrainPresetHolder holder) + { + holder.numLayers = numLayers; + holder.splats = new Texture2D[splats.Length]; + for (int i = 0; i < holder.splats.Length; i++) + { + holder.splats[i] = splats[i]; + } + holder.splat_atlases = new Texture2D[3]; + for (int j = 0; j < splat_atlases.Length; j++) + { + holder.splat_atlases[j] = splat_atlases[j]; + } + holder.RTP_MIP_BIAS = RTP_MIP_BIAS; + holder.MasterLayerBrightness = MasterLayerBrightness; + holder.MasterLayerSaturation = MasterLayerSaturation; + holder.SuperDetailA_channel = SuperDetailA_channel; + holder.SuperDetailB_channel = SuperDetailB_channel; + holder.Bump01 = Bump01; + holder.Bump23 = Bump23; + holder.Bump45 = Bump45; + holder.Bump67 = Bump67; + holder.Bump89 = Bump89; + holder.BumpAB = BumpAB; + holder.SSColorCombinedA = SSColorCombinedA; + holder.SSColorCombinedB = SSColorCombinedB; + holder.BumpGlobal = BumpGlobal; + holder.VerticalTexture = VerticalTexture; + holder.BumpMapGlobalScale = BumpMapGlobalScale; + holder.GlobalColorMapBlendValues = GlobalColorMapBlendValues; + holder.GlobalColorMapSaturation = GlobalColorMapSaturation; + holder.GlobalColorMapSaturationFar = GlobalColorMapSaturationFar; + holder.GlobalColorMapDistortByPerlin = GlobalColorMapDistortByPerlin; + holder.GlobalColorMapBrightness = GlobalColorMapBrightness; + holder.GlobalColorMapBrightnessFar = GlobalColorMapBrightnessFar; + holder._GlobalColorMapNearMIP = _GlobalColorMapNearMIP; + holder._FarNormalDamp = _FarNormalDamp; + holder.blendMultiplier = blendMultiplier; + holder.HeightMap = HeightMap; + holder.HeightMap2 = HeightMap2; + holder.HeightMap3 = HeightMap3; + holder.ReliefTransform = ReliefTransform; + holder.DIST_STEPS = DIST_STEPS; + holder.WAVELENGTH = WAVELENGTH; + holder.ReliefBorderBlend = ReliefBorderBlend; + holder.ExtrudeHeight = ExtrudeHeight; + holder.LightmapShading = LightmapShading; + holder.SHADOW_STEPS = SHADOW_STEPS; + holder.WAVELENGTH_SHADOWS = WAVELENGTH_SHADOWS; + holder.SelfShadowStrength = SelfShadowStrength; + holder.ShadowSmoothing = ShadowSmoothing; + holder.ShadowSoftnessFade = ShadowSoftnessFade; + holder.distance_start = distance_start; + holder.distance_transition = distance_transition; + holder.distance_start_bumpglobal = distance_start_bumpglobal; + holder.distance_transition_bumpglobal = distance_transition_bumpglobal; + holder.rtp_perlin_start_val = rtp_perlin_start_val; + holder._Phong = _Phong; + holder.tessHeight = tessHeight; + holder._TessSubdivisions = _TessSubdivisions; + holder._TessSubdivisionsFar = _TessSubdivisionsFar; + holder._TessYOffset = _TessYOffset; + holder.trees_shadow_distance_start = trees_shadow_distance_start; + holder.trees_shadow_distance_transition = trees_shadow_distance_transition; + holder.trees_shadow_value = trees_shadow_value; + holder.trees_pixel_distance_start = trees_pixel_distance_start; + holder.trees_pixel_distance_transition = trees_pixel_distance_transition; + holder.trees_pixel_blend_val = trees_pixel_blend_val; + holder.global_normalMap_multiplier = global_normalMap_multiplier; + holder.global_normalMap_farUsage = global_normalMap_farUsage; + holder._AmbientEmissiveMultiplier = _AmbientEmissiveMultiplier; + holder._AmbientEmissiveRelief = _AmbientEmissiveRelief; + holder.rtp_mipoffset_globalnorm = rtp_mipoffset_globalnorm; + holder._SuperDetailTiling = _SuperDetailTiling; + holder.SuperDetailA = SuperDetailA; + holder.SuperDetailB = SuperDetailB; + holder.TERRAIN_GlobalWetness = TERRAIN_GlobalWetness; + holder.TERRAIN_RippleMap = TERRAIN_RippleMap; + holder.TERRAIN_RippleScale = TERRAIN_RippleScale; + holder.TERRAIN_FlowScale = TERRAIN_FlowScale; + holder.TERRAIN_FlowSpeed = TERRAIN_FlowSpeed; + holder.TERRAIN_FlowCycleScale = TERRAIN_FlowCycleScale; + holder.TERRAIN_FlowMipOffset = TERRAIN_FlowMipOffset; + holder.TERRAIN_WetDarkening = TERRAIN_WetDarkening; + holder.TERRAIN_WetDropletsStrength = TERRAIN_WetDropletsStrength; + holder.TERRAIN_WetHeight_Treshold = TERRAIN_WetHeight_Treshold; + holder.TERRAIN_WetHeight_Transition = TERRAIN_WetHeight_Transition; + holder.TERRAIN_RainIntensity = TERRAIN_RainIntensity; + holder.TERRAIN_DropletsSpeed = TERRAIN_DropletsSpeed; + holder.TERRAIN_mipoffset_flowSpeed = TERRAIN_mipoffset_flowSpeed; + holder.TERRAIN_CausticsAnimSpeed = TERRAIN_CausticsAnimSpeed; + holder.TERRAIN_CausticsColor = TERRAIN_CausticsColor; + holder.TERRAIN_CausticsWaterLevel = TERRAIN_CausticsWaterLevel; + holder.TERRAIN_CausticsWaterLevelByAngle = TERRAIN_CausticsWaterLevelByAngle; + holder.TERRAIN_CausticsWaterDeepFadeLength = TERRAIN_CausticsWaterDeepFadeLength; + holder.TERRAIN_CausticsWaterShallowFadeLength = TERRAIN_CausticsWaterShallowFadeLength; + holder.TERRAIN_CausticsTilingScale = TERRAIN_CausticsTilingScale; + holder.TERRAIN_CausticsTex = TERRAIN_CausticsTex; + holder.RTP_AOsharpness = RTP_AOsharpness; + holder.RTP_AOamp = RTP_AOamp; + holder._occlusionStrength = _occlusionStrength; + holder.RTP_LightDefVector = RTP_LightDefVector; + holder.EmissionRefractFiltering = EmissionRefractFiltering; + holder.EmissionRefractAnimSpeed = EmissionRefractAnimSpeed; + holder.VerticalTextureGlobalBumpInfluence = VerticalTextureGlobalBumpInfluence; + holder.VerticalTextureTiling = VerticalTextureTiling; + holder._snow_strength = _snow_strength; + holder._global_color_brightness_to_snow = _global_color_brightness_to_snow; + holder._snow_slope_factor = _snow_slope_factor; + holder._snow_edge_definition = _snow_edge_definition; + holder._snow_height_treshold = _snow_height_treshold; + holder._snow_height_transition = _snow_height_transition; + holder._snow_color = _snow_color; + holder._snow_gloss = _snow_gloss; + holder._snow_reflectivness = _snow_reflectivness; + holder._snow_deep_factor = _snow_deep_factor; + holder._snow_diff_fresnel = _snow_diff_fresnel; + holder._snow_metallic = _snow_metallic; + holder._snow_Frost = _snow_Frost; + holder._snow_MicroTiling = _snow_MicroTiling; + holder._snow_BumpMicro = _snow_BumpMicro; + holder._snow_occlusionStrength = _snow_occlusionStrength; + holder._snow_TranslucencyDeferredLightIndex = _snow_TranslucencyDeferredLightIndex; + holder._SnowGlitterColor = _SnowGlitterColor; + holder._GlitterColor = _GlitterColor; + holder._GlitterTiling = _GlitterTiling; + holder._GlitterDensity = _GlitterDensity; + holder._GlitterFilter = _GlitterFilter; + holder._GlitterColorization = _GlitterColorization; + holder._SparkleMap = _SparkleMap; + holder.Bumps = new Texture2D[numLayers]; + holder.Spec = new float[numLayers]; + holder.FarSpecCorrection = new float[numLayers]; + holder.MixScale = new float[numLayers]; + holder.MixBlend = new float[numLayers]; + holder.MixSaturation = new float[numLayers]; + holder.RTP_DiffFresnel = new float[numLayers]; + holder.RTP_metallic = new float[numLayers]; + holder.RTP_glossMin = new float[numLayers]; + holder.RTP_glossMax = new float[numLayers]; + holder.RTP_glitter = new float[numLayers]; + holder.MixBrightness = new float[numLayers]; + holder.MixReplace = new float[numLayers]; + holder.LayerBrightness = new float[numLayers]; + holder.LayerBrightness2Spec = new float[numLayers]; + holder.LayerAlbedo2SpecColor = new float[numLayers]; + holder.LayerSaturation = new float[numLayers]; + holder.LayerEmission = new float[numLayers]; + holder.LayerEmissionColor = new Color[numLayers]; + holder.LayerEmissionRefractStrength = new float[numLayers]; + holder.LayerEmissionRefractHBedge = new float[numLayers]; + holder.GlobalColorPerLayer = new float[numLayers]; + holder.GlobalColorBottom = new float[numLayers]; + holder.GlobalColorTop = new float[numLayers]; + holder.GlobalColorColormapLoSat = new float[numLayers]; + holder.GlobalColorColormapHiSat = new float[numLayers]; + holder.GlobalColorLayerLoSat = new float[numLayers]; + holder.GlobalColorLayerHiSat = new float[numLayers]; + holder.GlobalColorLoBlend = new float[numLayers]; + holder.GlobalColorHiBlend = new float[numLayers]; + holder.PER_LAYER_HEIGHT_MODIFIER = new float[numLayers]; + holder._SuperDetailStrengthMultA = new float[numLayers]; + holder._SuperDetailStrengthMultASelfMaskNear = new float[numLayers]; + holder._SuperDetailStrengthMultASelfMaskFar = new float[numLayers]; + holder._SuperDetailStrengthMultB = new float[numLayers]; + holder._SuperDetailStrengthMultBSelfMaskNear = new float[numLayers]; + holder._SuperDetailStrengthMultBSelfMaskFar = new float[numLayers]; + holder._SuperDetailStrengthNormal = new float[numLayers]; + holder._BumpMapGlobalStrength = new float[numLayers]; + holder.VerticalTextureStrength = new float[numLayers]; + holder.AO_strength = new float[numLayers]; + holder.Heights = new Texture2D[numLayers]; + holder._snow_strength_per_layer = new float[numLayers]; + holder.Substances = new ProceduralMaterial[numLayers]; + holder.TERRAIN_LayerWetStrength = new float[numLayers]; + holder.TERRAIN_WaterLevel = new float[numLayers]; + holder.TERRAIN_WaterLevelSlopeDamp = new float[numLayers]; + holder.TERRAIN_WaterEdge = new float[numLayers]; + holder.TERRAIN_WaterGloss = new float[numLayers]; + holder.TERRAIN_WaterGlossDamper = new float[numLayers]; + holder.TERRAIN_Refraction = new float[numLayers]; + holder.TERRAIN_WetRefraction = new float[numLayers]; + holder.TERRAIN_Flow = new float[numLayers]; + holder.TERRAIN_WetFlow = new float[numLayers]; + holder.TERRAIN_WaterMetallic = new float[numLayers]; + holder.TERRAIN_WetGloss = new float[numLayers]; + holder.TERRAIN_WaterColor = new Color[numLayers]; + holder.TERRAIN_WaterEmission = new float[numLayers]; + holder._GlitterStrength = new float[numLayers]; + for (int k = 0; k < numLayers; k++) + { + holder.Bumps[k] = Bumps[k]; + holder.FarSpecCorrection[k] = FarSpecCorrection[k]; + holder.MixScale[k] = MixScale[k]; + holder.MixBlend[k] = MixBlend[k]; + holder.MixSaturation[k] = MixSaturation[k]; + CheckAndUpdate(ref RTP_DiffFresnel, 0f, numLayers); + CheckAndUpdate(ref RTP_metallic, 0f, numLayers); + CheckAndUpdate(ref RTP_glossMin, 0f, numLayers); + CheckAndUpdate(ref RTP_glossMax, 1f, numLayers); + CheckAndUpdate(ref RTP_glitter, 0f, numLayers); + CheckAndUpdate(ref TERRAIN_WaterGloss, 0.1f, numLayers); + CheckAndUpdate(ref TERRAIN_WaterGlossDamper, 0f, numLayers); + CheckAndUpdate(ref TERRAIN_WaterMetallic, 0.1f, numLayers); + CheckAndUpdate(ref TERRAIN_WetGloss, 0.05f, numLayers); + CheckAndUpdate(ref TERRAIN_WetFlow, 0.05f, numLayers); + CheckAndUpdate(ref MixBrightness, 2f, numLayers); + CheckAndUpdate(ref MixReplace, 0f, numLayers); + CheckAndUpdate(ref LayerBrightness, 1f, numLayers); + CheckAndUpdate(ref LayerBrightness2Spec, 0f, numLayers); + CheckAndUpdate(ref LayerAlbedo2SpecColor, 0f, numLayers); + CheckAndUpdate(ref LayerSaturation, 1f, numLayers); + CheckAndUpdate(ref LayerEmission, 0f, numLayers); + CheckAndUpdate(ref LayerEmissionColor, Color.black, numLayers); + CheckAndUpdate(ref LayerEmissionRefractStrength, 0f, numLayers); + CheckAndUpdate(ref LayerEmissionRefractHBedge, 0f, numLayers); + CheckAndUpdate(ref TERRAIN_WaterEmission, 0.5f, numLayers); + CheckAndUpdate(ref _GlitterStrength, 0f, numLayers); + holder.RTP_DiffFresnel[k] = RTP_DiffFresnel[k]; + holder.RTP_metallic[k] = RTP_metallic[k]; + holder.RTP_glossMin[k] = RTP_glossMin[k]; + holder.RTP_glossMax[k] = RTP_glossMax[k]; + holder.RTP_glitter[k] = RTP_glitter[k]; + holder.TERRAIN_WaterEmission[k] = TERRAIN_WaterEmission[k]; + holder.MixBrightness[k] = MixBrightness[k]; + holder.MixReplace[k] = MixReplace[k]; + holder.LayerBrightness[k] = LayerBrightness[k]; + holder.LayerBrightness2Spec[k] = LayerBrightness2Spec[k]; + holder.LayerAlbedo2SpecColor[k] = LayerAlbedo2SpecColor[k]; + holder.LayerSaturation[k] = LayerSaturation[k]; + holder.LayerEmission[k] = LayerEmission[k]; + ref Color reference = ref holder.LayerEmissionColor[k]; + reference = LayerEmissionColor[k]; + holder.LayerEmissionRefractStrength[k] = LayerEmissionRefractStrength[k]; + holder.LayerEmissionRefractHBedge[k] = LayerEmissionRefractHBedge[k]; + holder.GlobalColorPerLayer[k] = GlobalColorPerLayer[k]; + holder.GlobalColorBottom[k] = GlobalColorBottom[k]; + holder.GlobalColorTop[k] = GlobalColorTop[k]; + holder.GlobalColorColormapLoSat[k] = GlobalColorColormapLoSat[k]; + holder.GlobalColorColormapHiSat[k] = GlobalColorColormapHiSat[k]; + holder.GlobalColorLayerLoSat[k] = GlobalColorLayerLoSat[k]; + holder.GlobalColorLayerHiSat[k] = GlobalColorLayerHiSat[k]; + holder.GlobalColorLoBlend[k] = GlobalColorLoBlend[k]; + holder.GlobalColorHiBlend[k] = GlobalColorHiBlend[k]; + holder.PER_LAYER_HEIGHT_MODIFIER[k] = PER_LAYER_HEIGHT_MODIFIER[k]; + holder._SuperDetailStrengthMultA[k] = _SuperDetailStrengthMultA[k]; + holder._SuperDetailStrengthMultASelfMaskNear[k] = _SuperDetailStrengthMultASelfMaskNear[k]; + holder._SuperDetailStrengthMultASelfMaskFar[k] = _SuperDetailStrengthMultASelfMaskFar[k]; + holder._SuperDetailStrengthMultB[k] = _SuperDetailStrengthMultB[k]; + holder._SuperDetailStrengthMultBSelfMaskNear[k] = _SuperDetailStrengthMultBSelfMaskNear[k]; + holder._SuperDetailStrengthMultBSelfMaskFar[k] = _SuperDetailStrengthMultBSelfMaskFar[k]; + holder._SuperDetailStrengthNormal[k] = _SuperDetailStrengthNormal[k]; + holder._BumpMapGlobalStrength[k] = _BumpMapGlobalStrength[k]; + holder.VerticalTextureStrength[k] = VerticalTextureStrength[k]; + holder.AO_strength[k] = AO_strength[k]; + holder.Heights[k] = Heights[k]; + holder._snow_strength_per_layer[k] = _snow_strength_per_layer[k]; + holder.Substances[k] = Substances[k]; + holder.TERRAIN_LayerWetStrength[k] = TERRAIN_LayerWetStrength[k]; + holder.TERRAIN_WaterLevel[k] = TERRAIN_WaterLevel[k]; + holder.TERRAIN_WaterLevelSlopeDamp[k] = TERRAIN_WaterLevelSlopeDamp[k]; + holder.TERRAIN_WaterEdge[k] = TERRAIN_WaterEdge[k]; + holder.TERRAIN_WaterGloss[k] = TERRAIN_WaterGloss[k]; + holder.TERRAIN_WaterGlossDamper[k] = TERRAIN_WaterGlossDamper[k]; + holder.TERRAIN_Refraction[k] = TERRAIN_Refraction[k]; + holder.TERRAIN_WetRefraction[k] = TERRAIN_WetRefraction[k]; + holder.TERRAIN_Flow[k] = TERRAIN_Flow[k]; + holder.TERRAIN_WetFlow[k] = TERRAIN_WetFlow[k]; + holder.TERRAIN_WaterMetallic[k] = TERRAIN_WaterMetallic[k]; + holder.TERRAIN_WetGloss[k] = TERRAIN_WetGloss[k]; + ref Color reference2 = ref holder.TERRAIN_WaterColor[k]; + reference2 = TERRAIN_WaterColor[k]; + holder._GlitterStrength[k] = _GlitterStrength[k]; + } + } + + public void InterpolatePresets(ReliefTerrainPresetHolder holderA, ReliefTerrainPresetHolder holderB, float t) + { + RTP_MIP_BIAS = Mathf.Lerp(holderA.RTP_MIP_BIAS, holderB.RTP_MIP_BIAS, t); + MasterLayerBrightness = Mathf.Lerp(holderA.MasterLayerBrightness, holderB.MasterLayerBrightness, t); + MasterLayerSaturation = Mathf.Lerp(holderA.MasterLayerSaturation, holderB.MasterLayerSaturation, t); + BumpMapGlobalScale = Mathf.Lerp(holderA.BumpMapGlobalScale, holderB.BumpMapGlobalScale, t); + GlobalColorMapBlendValues = Vector3.Lerp(holderA.GlobalColorMapBlendValues, holderB.GlobalColorMapBlendValues, t); + GlobalColorMapSaturation = Mathf.Lerp(holderA.GlobalColorMapSaturation, holderB.GlobalColorMapSaturation, t); + GlobalColorMapSaturationFar = Mathf.Lerp(holderA.GlobalColorMapSaturationFar, holderB.GlobalColorMapSaturationFar, t); + GlobalColorMapDistortByPerlin = Mathf.Lerp(holderA.GlobalColorMapDistortByPerlin, holderB.GlobalColorMapDistortByPerlin, t); + GlobalColorMapBrightness = Mathf.Lerp(holderA.GlobalColorMapBrightness, holderB.GlobalColorMapBrightness, t); + GlobalColorMapBrightnessFar = Mathf.Lerp(holderA.GlobalColorMapBrightnessFar, holderB.GlobalColorMapBrightnessFar, t); + _GlobalColorMapNearMIP = Mathf.Lerp(holderA._GlobalColorMapNearMIP, holderB._GlobalColorMapNearMIP, t); + _FarNormalDamp = Mathf.Lerp(holderA._FarNormalDamp, holderB._FarNormalDamp, t); + blendMultiplier = Mathf.Lerp(holderA.blendMultiplier, holderB.blendMultiplier, t); + ReliefTransform = Vector4.Lerp(holderA.ReliefTransform, holderB.ReliefTransform, t); + DIST_STEPS = Mathf.Lerp(holderA.DIST_STEPS, holderB.DIST_STEPS, t); + WAVELENGTH = Mathf.Lerp(holderA.WAVELENGTH, holderB.WAVELENGTH, t); + ReliefBorderBlend = Mathf.Lerp(holderA.ReliefBorderBlend, holderB.ReliefBorderBlend, t); + ExtrudeHeight = Mathf.Lerp(holderA.ExtrudeHeight, holderB.ExtrudeHeight, t); + LightmapShading = Mathf.Lerp(holderA.LightmapShading, holderB.LightmapShading, t); + SHADOW_STEPS = Mathf.Lerp(holderA.SHADOW_STEPS, holderB.SHADOW_STEPS, t); + WAVELENGTH_SHADOWS = Mathf.Lerp(holderA.WAVELENGTH_SHADOWS, holderB.WAVELENGTH_SHADOWS, t); + SelfShadowStrength = Mathf.Lerp(holderA.SelfShadowStrength, holderB.SelfShadowStrength, t); + ShadowSmoothing = Mathf.Lerp(holderA.ShadowSmoothing, holderB.ShadowSmoothing, t); + ShadowSoftnessFade = Mathf.Lerp(holderA.ShadowSoftnessFade, holderB.ShadowSoftnessFade, t); + distance_start = Mathf.Lerp(holderA.distance_start, holderB.distance_start, t); + distance_transition = Mathf.Lerp(holderA.distance_transition, holderB.distance_transition, t); + distance_start_bumpglobal = Mathf.Lerp(holderA.distance_start_bumpglobal, holderB.distance_start_bumpglobal, t); + distance_transition_bumpglobal = Mathf.Lerp(holderA.distance_transition_bumpglobal, holderB.distance_transition_bumpglobal, t); + rtp_perlin_start_val = Mathf.Lerp(holderA.rtp_perlin_start_val, holderB.rtp_perlin_start_val, t); + trees_shadow_distance_start = Mathf.Lerp(holderA.trees_shadow_distance_start, holderB.trees_shadow_distance_start, t); + trees_shadow_distance_transition = Mathf.Lerp(holderA.trees_shadow_distance_transition, holderB.trees_shadow_distance_transition, t); + trees_shadow_value = Mathf.Lerp(holderA.trees_shadow_value, holderB.trees_shadow_value, t); + trees_pixel_distance_start = Mathf.Lerp(holderA.trees_pixel_distance_start, holderB.trees_pixel_distance_start, t); + trees_pixel_distance_transition = Mathf.Lerp(holderA.trees_pixel_distance_transition, holderB.trees_pixel_distance_transition, t); + trees_pixel_blend_val = Mathf.Lerp(holderA.trees_pixel_blend_val, holderB.trees_pixel_blend_val, t); + global_normalMap_multiplier = Mathf.Lerp(holderA.global_normalMap_multiplier, holderB.global_normalMap_multiplier, t); + global_normalMap_farUsage = Mathf.Lerp(holderA.global_normalMap_farUsage, holderB.global_normalMap_farUsage, t); + _AmbientEmissiveMultiplier = Mathf.Lerp(holderA._AmbientEmissiveMultiplier, holderB._AmbientEmissiveMultiplier, t); + _AmbientEmissiveRelief = Mathf.Lerp(holderA._AmbientEmissiveRelief, holderB._AmbientEmissiveRelief, t); + _SuperDetailTiling = Mathf.Lerp(holderA._SuperDetailTiling, holderB._SuperDetailTiling, t); + TERRAIN_GlobalWetness = Mathf.Lerp(holderA.TERRAIN_GlobalWetness, holderB.TERRAIN_GlobalWetness, t); + TERRAIN_RippleScale = Mathf.Lerp(holderA.TERRAIN_RippleScale, holderB.TERRAIN_RippleScale, t); + TERRAIN_FlowScale = Mathf.Lerp(holderA.TERRAIN_FlowScale, holderB.TERRAIN_FlowScale, t); + TERRAIN_FlowSpeed = Mathf.Lerp(holderA.TERRAIN_FlowSpeed, holderB.TERRAIN_FlowSpeed, t); + TERRAIN_FlowCycleScale = Mathf.Lerp(holderA.TERRAIN_FlowCycleScale, holderB.TERRAIN_FlowCycleScale, t); + TERRAIN_FlowMipOffset = Mathf.Lerp(holderA.TERRAIN_FlowMipOffset, holderB.TERRAIN_FlowMipOffset, t); + TERRAIN_WetDarkening = Mathf.Lerp(holderA.TERRAIN_WetDarkening, holderB.TERRAIN_WetDarkening, t); + TERRAIN_WetDropletsStrength = Mathf.Lerp(holderA.TERRAIN_WetDropletsStrength, holderB.TERRAIN_WetDropletsStrength, t); + TERRAIN_WetHeight_Treshold = Mathf.Lerp(holderA.TERRAIN_WetHeight_Treshold, holderB.TERRAIN_WetHeight_Treshold, t); + TERRAIN_WetHeight_Transition = Mathf.Lerp(holderA.TERRAIN_WetHeight_Transition, holderB.TERRAIN_WetHeight_Transition, t); + TERRAIN_RainIntensity = Mathf.Lerp(holderA.TERRAIN_RainIntensity, holderB.TERRAIN_RainIntensity, t); + TERRAIN_DropletsSpeed = Mathf.Lerp(holderA.TERRAIN_DropletsSpeed, holderB.TERRAIN_DropletsSpeed, t); + TERRAIN_mipoffset_flowSpeed = Mathf.Lerp(holderA.TERRAIN_mipoffset_flowSpeed, holderB.TERRAIN_mipoffset_flowSpeed, t); + TERRAIN_CausticsAnimSpeed = Mathf.Lerp(holderA.TERRAIN_CausticsAnimSpeed, holderB.TERRAIN_CausticsAnimSpeed, t); + TERRAIN_CausticsColor = Color.Lerp(holderA.TERRAIN_CausticsColor, holderB.TERRAIN_CausticsColor, t); + TERRAIN_CausticsWaterLevel = Mathf.Lerp(holderA.TERRAIN_CausticsWaterLevel, holderB.TERRAIN_CausticsWaterLevel, t); + TERRAIN_CausticsWaterLevelByAngle = Mathf.Lerp(holderA.TERRAIN_CausticsWaterLevelByAngle, holderB.TERRAIN_CausticsWaterLevelByAngle, t); + TERRAIN_CausticsWaterDeepFadeLength = Mathf.Lerp(holderA.TERRAIN_CausticsWaterDeepFadeLength, holderB.TERRAIN_CausticsWaterDeepFadeLength, t); + TERRAIN_CausticsWaterShallowFadeLength = Mathf.Lerp(holderA.TERRAIN_CausticsWaterShallowFadeLength, holderB.TERRAIN_CausticsWaterShallowFadeLength, t); + TERRAIN_CausticsTilingScale = Mathf.Lerp(holderA.TERRAIN_CausticsTilingScale, holderB.TERRAIN_CausticsTilingScale, t); + RTP_AOsharpness = Mathf.Lerp(holderA.RTP_AOsharpness, holderB.RTP_AOsharpness, t); + RTP_AOamp = Mathf.Lerp(holderA.RTP_AOamp, holderB.RTP_AOamp, t); + _occlusionStrength = Mathf.Lerp(holderA._occlusionStrength, holderB._occlusionStrength, t); + RTP_LightDefVector = Vector4.Lerp(holderA.RTP_LightDefVector, holderB.RTP_LightDefVector, t); + EmissionRefractFiltering = Mathf.Lerp(holderA.EmissionRefractFiltering, holderB.EmissionRefractFiltering, t); + EmissionRefractAnimSpeed = Mathf.Lerp(holderA.EmissionRefractAnimSpeed, holderB.EmissionRefractAnimSpeed, t); + VerticalTextureGlobalBumpInfluence = Mathf.Lerp(holderA.VerticalTextureGlobalBumpInfluence, holderB.VerticalTextureGlobalBumpInfluence, t); + VerticalTextureTiling = Mathf.Lerp(holderA.VerticalTextureTiling, holderB.VerticalTextureTiling, t); + _snow_strength = Mathf.Lerp(holderA._snow_strength, holderB._snow_strength, t); + _global_color_brightness_to_snow = Mathf.Lerp(holderA._global_color_brightness_to_snow, holderB._global_color_brightness_to_snow, t); + _snow_slope_factor = Mathf.Lerp(holderA._snow_slope_factor, holderB._snow_slope_factor, t); + _snow_edge_definition = Mathf.Lerp(holderA._snow_edge_definition, holderB._snow_edge_definition, t); + _snow_height_treshold = Mathf.Lerp(holderA._snow_height_treshold, holderB._snow_height_treshold, t); + _snow_height_transition = Mathf.Lerp(holderA._snow_height_transition, holderB._snow_height_transition, t); + _snow_color = Color.Lerp(holderA._snow_color, holderB._snow_color, t); + _snow_gloss = Mathf.Lerp(holderA._snow_gloss, holderB._snow_gloss, t); + _snow_reflectivness = Mathf.Lerp(holderA._snow_reflectivness, holderB._snow_reflectivness, t); + _snow_deep_factor = Mathf.Lerp(holderA._snow_deep_factor, holderB._snow_deep_factor, t); + _snow_diff_fresnel = Mathf.Lerp(holderA._snow_diff_fresnel, holderB._snow_diff_fresnel, t); + _snow_metallic = Mathf.Lerp(holderA._snow_metallic, holderB._snow_metallic, t); + _snow_Frost = Mathf.Lerp(holderA._snow_Frost, holderB._snow_Frost, t); + _snow_MicroTiling = Mathf.Lerp(holderA._snow_MicroTiling, holderB._snow_MicroTiling, t); + _snow_BumpMicro = Mathf.Lerp(holderA._snow_BumpMicro, holderB._snow_BumpMicro, t); + _snow_occlusionStrength = Mathf.Lerp(holderA._snow_occlusionStrength, holderB._snow_occlusionStrength, t); + _SnowGlitterColor = Color.Lerp(holderA._SnowGlitterColor, holderB._SnowGlitterColor, t); + _GlitterColor = Color.Lerp(holderA._GlitterColor, holderB._GlitterColor, t); + _GlitterTiling = Mathf.Lerp(holderA._GlitterTiling, holderB._GlitterTiling, t); + _GlitterDensity = Mathf.Lerp(holderA._GlitterDensity, holderB._GlitterDensity, t); + _GlitterFilter = Mathf.Lerp(holderA._GlitterFilter, holderB._GlitterFilter, t); + _GlitterColorization = Mathf.Lerp(holderA._GlitterColorization, holderB._GlitterColorization, t); + for (int i = 0; i < holderA.Spec.Length; i++) + { + if (i < FarSpecCorrection.Length) + { + FarSpecCorrection[i] = Mathf.Lerp(holderA.FarSpecCorrection[i], holderB.FarSpecCorrection[i], t); + MixScale[i] = Mathf.Lerp(holderA.MixScale[i], holderB.MixScale[i], t); + MixBlend[i] = Mathf.Lerp(holderA.MixBlend[i], holderB.MixBlend[i], t); + MixSaturation[i] = Mathf.Lerp(holderA.MixSaturation[i], holderB.MixSaturation[i], t); + RTP_DiffFresnel[i] = Mathf.Lerp(holderA.RTP_DiffFresnel[i], holderB.RTP_DiffFresnel[i], t); + RTP_metallic[i] = Mathf.Lerp(holderA.RTP_metallic[i], holderB.RTP_metallic[i], t); + RTP_glossMin[i] = Mathf.Lerp(holderA.RTP_glossMin[i], holderB.RTP_glossMin[i], t); + RTP_glossMax[i] = Mathf.Lerp(holderA.RTP_glossMax[i], holderB.RTP_glossMax[i], t); + RTP_glitter[i] = Mathf.Lerp(holderA.RTP_glitter[i], holderB.RTP_glitter[i], t); + MixBrightness[i] = Mathf.Lerp(holderA.MixBrightness[i], holderB.MixBrightness[i], t); + MixReplace[i] = Mathf.Lerp(holderA.MixReplace[i], holderB.MixReplace[i], t); + LayerBrightness[i] = Mathf.Lerp(holderA.LayerBrightness[i], holderB.LayerBrightness[i], t); + LayerBrightness2Spec[i] = Mathf.Lerp(holderA.LayerBrightness2Spec[i], holderB.LayerBrightness2Spec[i], t); + LayerAlbedo2SpecColor[i] = Mathf.Lerp(holderA.LayerAlbedo2SpecColor[i], holderB.LayerAlbedo2SpecColor[i], t); + LayerSaturation[i] = Mathf.Lerp(holderA.LayerSaturation[i], holderB.LayerSaturation[i], t); + LayerEmission[i] = Mathf.Lerp(holderA.LayerEmission[i], holderB.LayerEmission[i], t); + ref Color reference = ref LayerEmissionColor[i]; + reference = Color.Lerp(holderA.LayerEmissionColor[i], holderB.LayerEmissionColor[i], t); + LayerEmissionRefractStrength[i] = Mathf.Lerp(holderA.LayerEmissionRefractStrength[i], holderB.LayerEmissionRefractStrength[i], t); + LayerEmissionRefractHBedge[i] = Mathf.Lerp(holderA.LayerEmissionRefractHBedge[i], holderB.LayerEmissionRefractHBedge[i], t); + GlobalColorPerLayer[i] = Mathf.Lerp(holderA.GlobalColorPerLayer[i], holderB.GlobalColorPerLayer[i], t); + GlobalColorBottom[i] = Mathf.Lerp(holderA.GlobalColorBottom[i], holderB.GlobalColorBottom[i], t); + GlobalColorTop[i] = Mathf.Lerp(holderA.GlobalColorTop[i], holderB.GlobalColorTop[i], t); + GlobalColorColormapLoSat[i] = Mathf.Lerp(holderA.GlobalColorColormapLoSat[i], holderB.GlobalColorColormapLoSat[i], t); + GlobalColorColormapHiSat[i] = Mathf.Lerp(holderA.GlobalColorColormapHiSat[i], holderB.GlobalColorColormapHiSat[i], t); + GlobalColorLayerLoSat[i] = Mathf.Lerp(holderA.GlobalColorLayerLoSat[i], holderB.GlobalColorLayerLoSat[i], t); + GlobalColorLayerHiSat[i] = Mathf.Lerp(holderA.GlobalColorLayerHiSat[i], holderB.GlobalColorLayerHiSat[i], t); + GlobalColorLoBlend[i] = Mathf.Lerp(holderA.GlobalColorLoBlend[i], holderB.GlobalColorLoBlend[i], t); + GlobalColorHiBlend[i] = Mathf.Lerp(holderA.GlobalColorHiBlend[i], holderB.GlobalColorHiBlend[i], t); + PER_LAYER_HEIGHT_MODIFIER[i] = Mathf.Lerp(holderA.PER_LAYER_HEIGHT_MODIFIER[i], holderB.PER_LAYER_HEIGHT_MODIFIER[i], t); + _SuperDetailStrengthMultA[i] = Mathf.Lerp(holderA._SuperDetailStrengthMultA[i], holderB._SuperDetailStrengthMultA[i], t); + _SuperDetailStrengthMultASelfMaskNear[i] = Mathf.Lerp(holderA._SuperDetailStrengthMultASelfMaskNear[i], holderB._SuperDetailStrengthMultASelfMaskNear[i], t); + _SuperDetailStrengthMultASelfMaskFar[i] = Mathf.Lerp(holderA._SuperDetailStrengthMultASelfMaskFar[i], holderB._SuperDetailStrengthMultASelfMaskFar[i], t); + _SuperDetailStrengthMultB[i] = Mathf.Lerp(holderA._SuperDetailStrengthMultB[i], holderB._SuperDetailStrengthMultB[i], t); + _SuperDetailStrengthMultBSelfMaskNear[i] = Mathf.Lerp(holderA._SuperDetailStrengthMultBSelfMaskNear[i], holderB._SuperDetailStrengthMultBSelfMaskNear[i], t); + _SuperDetailStrengthMultBSelfMaskFar[i] = Mathf.Lerp(holderA._SuperDetailStrengthMultBSelfMaskFar[i], holderB._SuperDetailStrengthMultBSelfMaskFar[i], t); + _SuperDetailStrengthNormal[i] = Mathf.Lerp(holderA._SuperDetailStrengthNormal[i], holderB._SuperDetailStrengthNormal[i], t); + _BumpMapGlobalStrength[i] = Mathf.Lerp(holderA._BumpMapGlobalStrength[i], holderB._BumpMapGlobalStrength[i], t); + AO_strength[i] = Mathf.Lerp(holderA.AO_strength[i], holderB.AO_strength[i], t); + VerticalTextureStrength[i] = Mathf.Lerp(holderA.VerticalTextureStrength[i], holderB.VerticalTextureStrength[i], t); + _snow_strength_per_layer[i] = Mathf.Lerp(holderA._snow_strength_per_layer[i], holderB._snow_strength_per_layer[i], t); + TERRAIN_LayerWetStrength[i] = Mathf.Lerp(holderA.TERRAIN_LayerWetStrength[i], holderB.TERRAIN_LayerWetStrength[i], t); + TERRAIN_WaterLevel[i] = Mathf.Lerp(holderA.TERRAIN_WaterLevel[i], holderB.TERRAIN_WaterLevel[i], t); + TERRAIN_WaterLevelSlopeDamp[i] = Mathf.Lerp(holderA.TERRAIN_WaterLevelSlopeDamp[i], holderB.TERRAIN_WaterLevelSlopeDamp[i], t); + TERRAIN_WaterEdge[i] = Mathf.Lerp(holderA.TERRAIN_WaterEdge[i], holderB.TERRAIN_WaterEdge[i], t); + TERRAIN_WaterGloss[i] = Mathf.Lerp(holderA.TERRAIN_WaterGloss[i], holderB.TERRAIN_WaterGloss[i], t); + TERRAIN_WaterGlossDamper[i] = Mathf.Lerp(holderA.TERRAIN_WaterGlossDamper[i], holderB.TERRAIN_WaterGlossDamper[i], t); + TERRAIN_Refraction[i] = Mathf.Lerp(holderA.TERRAIN_Refraction[i], holderB.TERRAIN_Refraction[i], t); + TERRAIN_WetRefraction[i] = Mathf.Lerp(holderA.TERRAIN_WetRefraction[i], holderB.TERRAIN_WetRefraction[i], t); + TERRAIN_Flow[i] = Mathf.Lerp(holderA.TERRAIN_Flow[i], holderB.TERRAIN_Flow[i], t); + TERRAIN_WetFlow[i] = Mathf.Lerp(holderA.TERRAIN_WetFlow[i], holderB.TERRAIN_WetFlow[i], t); + TERRAIN_WaterMetallic[i] = Mathf.Lerp(holderA.TERRAIN_WaterMetallic[i], holderB.TERRAIN_WaterMetallic[i], t); + TERRAIN_WetGloss[i] = Mathf.Lerp(holderA.TERRAIN_WetGloss[i], holderB.TERRAIN_WetGloss[i], t); + ref Color reference2 = ref TERRAIN_WaterColor[i]; + reference2 = Color.Lerp(holderA.TERRAIN_WaterColor[i], holderB.TERRAIN_WaterColor[i], t); + TERRAIN_WaterEmission[i] = Mathf.Lerp(holderA.TERRAIN_WaterEmission[i], holderB.TERRAIN_WaterEmission[i], t); + _GlitterStrength[i] = Mathf.Lerp(holderA._GlitterStrength[i], holderB._GlitterStrength[i], t); + } + } + } + + public void ReturnToDefaults(string what = "", int layerIdx = -1) + { + if (what == string.Empty || what == "main") + { + ReliefTransform = new Vector4(3f, 3f, 0f, 0f); + distance_start = 5f; + distance_transition = 20f; + RTP_LightDefVector = new Vector4(0.05f, 0.5f, 0.5f, 25f); + ReliefBorderBlend = 6f; + LightmapShading = 0f; + RTP_MIP_BIAS = 0f; + RTP_AOsharpness = 1.5f; + RTP_AOamp = 0.1f; + _occlusionStrength = 1f; + MasterLayerBrightness = 1f; + MasterLayerSaturation = 1f; + EmissionRefractFiltering = 4f; + EmissionRefractAnimSpeed = 4f; + } + if (what == string.Empty || what == "perlin") + { + BumpMapGlobalScale = 0.1f; + _FarNormalDamp = 0.2f; + distance_start_bumpglobal = 30f; + distance_transition_bumpglobal = 30f; + rtp_perlin_start_val = 0f; + } + if (what == string.Empty || what == "global_color") + { + GlobalColorMapBlendValues = new Vector3(0.2f, 0.4f, 0.5f); + GlobalColorMapSaturation = 1f; + GlobalColorMapSaturationFar = 1f; + GlobalColorMapDistortByPerlin = 0.005f; + GlobalColorMapBrightness = 1f; + GlobalColorMapBrightnessFar = 1f; + _GlobalColorMapNearMIP = 0f; + trees_shadow_distance_start = 50f; + trees_shadow_distance_transition = 10f; + trees_shadow_value = 0.5f; + trees_pixel_distance_start = 500f; + trees_pixel_distance_transition = 10f; + trees_pixel_blend_val = 2f; + global_normalMap_multiplier = 1f; + global_normalMap_farUsage = 0f; + _Phong = 0f; + tessHeight = 300f; + _TessSubdivisions = 1f; + _TessSubdivisionsFar = 1f; + _TessYOffset = 0f; + _AmbientEmissiveMultiplier = 1f; + _AmbientEmissiveRelief = 0.5f; + } + if (what == string.Empty || what == "uvblend") + { + blendMultiplier = 1f; + } + if (what == string.Empty || what == "pom/pm") + { + ExtrudeHeight = 0.05f; + DIST_STEPS = 20f; + WAVELENGTH = 2f; + SHADOW_STEPS = 20f; + WAVELENGTH_SHADOWS = 2f; + SelfShadowStrength = 0.8f; + ShadowSmoothing = 1f; + ShadowSoftnessFade = 0.8f; + } + if (what == string.Empty || what == "snow") + { + _global_color_brightness_to_snow = 0.5f; + _snow_strength = 0f; + _snow_slope_factor = 2f; + _snow_edge_definition = 2f; + _snow_height_treshold = -200f; + _snow_height_transition = 1f; + _snow_color = Color.white; + _snow_gloss = 0.7f; + _snow_reflectivness = 0.7f; + _snow_deep_factor = 1.5f; + _snow_diff_fresnel = 0.5f; + _SnowGlitterColor = new Color(1f, 1f, 1f, 0.1f); + } + if (what == string.Empty || what == "superdetail") + { + _SuperDetailTiling = 8f; + } + if (what == string.Empty || what == "vertical") + { + VerticalTextureGlobalBumpInfluence = 0f; + VerticalTextureTiling = 50f; + } + if (what == string.Empty || what == "glitter") + { + _GlitterColor = new Color(1f, 1f, 1f, 0.1f); + _GlitterTiling = 1f; + _GlitterDensity = 0.1f; + _GlitterFilter = 0f; + _GlitterColorization = 0.5f; + } + if (what == string.Empty || what == "water") + { + TERRAIN_GlobalWetness = 1f; + TERRAIN_RippleScale = 4f; + TERRAIN_FlowScale = 1f; + TERRAIN_FlowSpeed = 0.5f; + TERRAIN_FlowCycleScale = 1f; + TERRAIN_RainIntensity = 1f; + TERRAIN_DropletsSpeed = 10f; + TERRAIN_mipoffset_flowSpeed = 1f; + TERRAIN_FlowMipOffset = 0f; + TERRAIN_WetDarkening = 0.5f; + TERRAIN_WetDropletsStrength = 0f; + TERRAIN_WetHeight_Treshold = -200f; + TERRAIN_WetHeight_Transition = 5f; + } + if (what == string.Empty || what == "caustics") + { + TERRAIN_CausticsAnimSpeed = 2f; + TERRAIN_CausticsColor = Color.white; + TERRAIN_CausticsWaterLevel = 30f; + TERRAIN_CausticsWaterLevelByAngle = 2f; + TERRAIN_CausticsWaterDeepFadeLength = 50f; + TERRAIN_CausticsWaterShallowFadeLength = 30f; + TERRAIN_CausticsTilingScale = 1f; + } + if (what == string.Empty || what == "layer") + { + int num = 0; + int num2 = ((numLayers >= 12) ? 12 : numLayers); + if (layerIdx >= 0) + { + num = layerIdx; + num2 = layerIdx + 1; + } + for (int i = num; i < num2; i++) + { + FarSpecCorrection[i] = 0f; + MIPmult[i] = 0f; + MixScale[i] = 0.2f; + MixBlend[i] = 0.5f; + MixSaturation[i] = 0.3f; + RTP_DiffFresnel[i] = 0f; + RTP_metallic[i] = 0f; + RTP_glossMin[i] = 0f; + RTP_glossMax[i] = 1f; + RTP_glitter[i] = 0f; + MixBrightness[i] = 2f; + MixReplace[i] = 0f; + LayerBrightness[i] = 1f; + LayerBrightness2Spec[i] = 0f; + LayerAlbedo2SpecColor[i] = 0f; + LayerSaturation[i] = 1f; + LayerEmission[i] = 0f; + ref Color reference = ref LayerEmissionColor[i]; + reference = Color.black; + LayerEmissionRefractStrength[i] = 0f; + LayerEmissionRefractHBedge[i] = 0f; + GlobalColorPerLayer[i] = 1f; + GlobalColorBottom[i] = 0f; + GlobalColorTop[i] = 1f; + GlobalColorColormapLoSat[i] = 1f; + GlobalColorColormapHiSat[i] = 1f; + GlobalColorLayerLoSat[i] = 1f; + GlobalColorLayerHiSat[i] = 1f; + GlobalColorLoBlend[i] = 1f; + GlobalColorHiBlend[i] = 1f; + PER_LAYER_HEIGHT_MODIFIER[i] = 0f; + _SuperDetailStrengthMultA[i] = 0f; + _SuperDetailStrengthMultASelfMaskNear[i] = 0f; + _SuperDetailStrengthMultASelfMaskFar[i] = 0f; + _SuperDetailStrengthMultB[i] = 0f; + _SuperDetailStrengthMultBSelfMaskNear[i] = 0f; + _SuperDetailStrengthMultBSelfMaskFar[i] = 0f; + _SuperDetailStrengthNormal[i] = 0f; + _BumpMapGlobalStrength[i] = 0.3f; + _snow_strength_per_layer[i] = 1f; + VerticalTextureStrength[i] = 0.5f; + AO_strength[i] = 1f; + TERRAIN_LayerWetStrength[i] = 1f; + TERRAIN_WaterLevel[i] = 0.5f; + TERRAIN_WaterLevelSlopeDamp[i] = 0.5f; + TERRAIN_WaterEdge[i] = 2f; + TERRAIN_WaterGloss[i] = 0.1f; + TERRAIN_WaterGlossDamper[i] = 0f; + TERRAIN_Refraction[i] = 0.01f; + TERRAIN_WetRefraction[i] = 0.2f; + TERRAIN_Flow[i] = 0.3f; + TERRAIN_WetFlow[i] = 0.05f; + TERRAIN_WaterMetallic[i] = 0.1f; + TERRAIN_WetGloss[i] = 0.05f; + ref Color reference2 = ref TERRAIN_WaterColor[i]; + reference2 = new Color(0.9f, 0.9f, 1f, 0.5f); + TERRAIN_WaterEmission[i] = 0f; + _GlitterStrength[i] = 0f; + } + } + } + + public bool CheckAndUpdate(ref float[] aLayerPropArray, float defVal, int len) + { + if (aLayerPropArray == null || aLayerPropArray.Length < len) + { + aLayerPropArray = new float[len]; + for (int i = 0; i < len; i++) + { + aLayerPropArray[i] = defVal; + } + return true; + } + return false; + } + + public bool CheckAndUpdate(ref Color[] aLayerPropArray, Color defVal, int len) + { + if (aLayerPropArray == null || aLayerPropArray.Length < len) + { + aLayerPropArray = new Color[len]; + for (int i = 0; i < len; i++) + { + aLayerPropArray[i] = defVal; + } + return true; + } + return false; + } +} diff --git a/ReliefTerrainMenuItems.cs b/ReliefTerrainMenuItems.cs new file mode 100644 index 0000000..9b32cb3 --- /dev/null +++ b/ReliefTerrainMenuItems.cs @@ -0,0 +1,7 @@ +public enum ReliefTerrainMenuItems +{ + Details, + Control, + CombinedTextures, + GeneralSettings +} diff --git a/ReliefTerrainPresetHolder.cs b/ReliefTerrainPresetHolder.cs new file mode 100644 index 0000000..da73e39 --- /dev/null +++ b/ReliefTerrainPresetHolder.cs @@ -0,0 +1,418 @@ +using System; +using UnityEngine; + +[Serializable] +public class ReliefTerrainPresetHolder : ScriptableObject +{ + public string PresetID; + + public string PresetName; + + public string type; + + public int numLayers; + + public Texture2D[] splats; + + public Texture2D[] splat_atlases; + + public Texture2D controlA; + + public Texture2D controlB; + + public Texture2D controlC; + + public float RTP_MIP_BIAS; + + public float MasterLayerBrightness = 1f; + + public float MasterLayerSaturation = 1f; + + public float EmissionRefractFiltering = 4f; + + public float EmissionRefractAnimSpeed = 4f; + + public RTPColorChannels SuperDetailA_channel; + + public RTPColorChannels SuperDetailB_channel; + + public Texture2D Bump01; + + public Texture2D Bump23; + + public Texture2D Bump45; + + public Texture2D Bump67; + + public Texture2D Bump89; + + public Texture2D BumpAB; + + public Texture2D ColorGlobal; + + public Texture2D NormalGlobal; + + public Texture2D TreesGlobal; + + public Texture2D AmbientEmissiveMap; + + public Texture2D SSColorCombinedA; + + public Texture2D SSColorCombinedB; + + public bool globalColorModifed_flag; + + public bool globalCombinedModifed_flag; + + public bool globalWaterModifed_flag; + + public Texture2D BumpGlobal; + + public Texture2D BumpGlobalCombined; + + public Texture2D VerticalTexture; + + public float BumpMapGlobalScale; + + public Vector3 GlobalColorMapBlendValues; + + public float GlobalColorMapSaturation; + + public float GlobalColorMapSaturationFar; + + public float GlobalColorMapDistortByPerlin = 0.005f; + + public float GlobalColorMapBrightness; + + public float GlobalColorMapBrightnessFar = 1f; + + public float _GlobalColorMapNearMIP; + + public float _FarNormalDamp; + + public float blendMultiplier; + + public Texture2D HeightMap; + + public Texture2D HeightMap2; + + public Texture2D HeightMap3; + + public Vector4 ReliefTransform; + + public float DIST_STEPS; + + public float WAVELENGTH; + + public float ReliefBorderBlend; + + public float ExtrudeHeight; + + public float LightmapShading; + + public float SHADOW_STEPS; + + public float WAVELENGTH_SHADOWS; + + public float SelfShadowStrength; + + public float ShadowSmoothing; + + public float ShadowSoftnessFade = 0.7f; + + public float distance_start; + + public float distance_transition; + + public float distance_start_bumpglobal; + + public float distance_transition_bumpglobal; + + public float rtp_perlin_start_val; + + public float _Phong; + + public float tessHeight = 300f; + + public float _TessSubdivisions = 1f; + + public float _TessSubdivisionsFar = 1f; + + public float _TessYOffset; + + public float trees_shadow_distance_start; + + public float trees_shadow_distance_transition; + + public float trees_shadow_value; + + public float trees_pixel_distance_start; + + public float trees_pixel_distance_transition; + + public float trees_pixel_blend_val; + + public float global_normalMap_multiplier; + + public float global_normalMap_farUsage; + + public float _AmbientEmissiveMultiplier; + + public float _AmbientEmissiveRelief; + + public int rtp_mipoffset_globalnorm; + + public float _SuperDetailTiling; + + public Texture2D SuperDetailA; + + public Texture2D SuperDetailB; + + public Texture2D TERRAIN_ReflectionMap; + + public RTPColorChannels TERRAIN_ReflectionMap_channel; + + public Color TERRAIN_ReflColorA; + + public Color TERRAIN_ReflColorB; + + public Color TERRAIN_ReflColorC; + + public float TERRAIN_ReflColorCenter; + + public float TERRAIN_ReflGlossAttenuation; + + public float TERRAIN_ReflectionRotSpeed; + + public float TERRAIN_GlobalWetness; + + public Texture2D TERRAIN_RippleMap; + + public Texture2D TERRAIN_WetMask; + + public float TERRAIN_RippleScale; + + public float TERRAIN_FlowScale; + + public float TERRAIN_FlowSpeed; + + public float TERRAIN_FlowCycleScale; + + public float TERRAIN_FlowMipOffset; + + public float TERRAIN_WetDarkening; + + public float TERRAIN_WetDropletsStrength; + + public float TERRAIN_WetHeight_Treshold; + + public float TERRAIN_WetHeight_Transition; + + public float TERRAIN_RainIntensity; + + public float TERRAIN_DropletsSpeed; + + public float TERRAIN_mipoffset_flowSpeed; + + public float TERRAIN_CausticsAnimSpeed; + + public Color TERRAIN_CausticsColor; + + public float TERRAIN_CausticsWaterLevel; + + public float TERRAIN_CausticsWaterLevelByAngle; + + public float TERRAIN_CausticsWaterDeepFadeLength; + + public float TERRAIN_CausticsWaterShallowFadeLength; + + public float TERRAIN_CausticsTilingScale; + + public Texture2D TERRAIN_CausticsTex; + + public Vector4 RTP_LightDefVector; + + public float RTP_AOamp; + + public float RTP_AOsharpness; + + public float _occlusionStrength; + + public Texture2D[] Bumps; + + public float[] Spec; + + public float[] FarSpecCorrection; + + public float[] MixScale; + + public float[] MixBlend; + + public float[] MixSaturation; + + public float[] RTP_DiffFresnel; + + public float[] RTP_metallic; + + public float[] RTP_glossMin; + + public float[] RTP_glossMax; + + public float[] RTP_glitter; + + public float[] MixBrightness; + + public float[] MixReplace; + + public float[] LayerBrightness; + + public float[] LayerBrightness2Spec; + + public float[] LayerAlbedo2SpecColor; + + public float[] LayerSaturation; + + public float[] LayerEmission; + + public Color[] LayerEmissionColor; + + public float[] LayerEmissionRefractStrength; + + public float[] LayerEmissionRefractHBedge; + + public float[] GlobalColorPerLayer; + + public float[] GlobalColorBottom; + + public float[] GlobalColorTop; + + public float[] GlobalColorColormapLoSat; + + public float[] GlobalColorColormapHiSat; + + public float[] GlobalColorLayerLoSat; + + public float[] GlobalColorLayerHiSat; + + public float[] GlobalColorLoBlend; + + public float[] GlobalColorHiBlend; + + public float[] PER_LAYER_HEIGHT_MODIFIER; + + public float[] _SuperDetailStrengthMultA; + + public float[] _SuperDetailStrengthMultASelfMaskNear; + + public float[] _SuperDetailStrengthMultASelfMaskFar; + + public float[] _SuperDetailStrengthMultB; + + public float[] _SuperDetailStrengthMultBSelfMaskNear; + + public float[] _SuperDetailStrengthMultBSelfMaskFar; + + public float[] _SuperDetailStrengthNormal; + + public float[] _BumpMapGlobalStrength; + + public float[] VerticalTextureStrength; + + public float[] AO_strength; + + public float VerticalTextureGlobalBumpInfluence; + + public float VerticalTextureTiling; + + public Texture2D[] Heights; + + public float[] _snow_strength_per_layer; + + public ProceduralMaterial[] Substances; + + public float[] TERRAIN_LayerWetStrength; + + public float[] TERRAIN_WaterLevel; + + public float[] TERRAIN_WaterLevelSlopeDamp; + + public float[] TERRAIN_WaterEdge; + + public float[] TERRAIN_WaterGloss; + + public float[] TERRAIN_WaterGlossDamper; + + public float[] TERRAIN_Refraction; + + public float[] TERRAIN_WetRefraction; + + public float[] TERRAIN_Flow; + + public float[] TERRAIN_WetFlow; + + public float[] TERRAIN_WaterMetallic; + + public float[] TERRAIN_WetGloss; + + public Color[] TERRAIN_WaterColor; + + public float[] TERRAIN_WaterEmission; + + public float _snow_strength; + + public float _global_color_brightness_to_snow; + + public float _snow_slope_factor; + + public float _snow_edge_definition; + + public float _snow_height_treshold; + + public float _snow_height_transition; + + public Color _snow_color; + + public float _snow_gloss; + + public float _snow_reflectivness; + + public float _snow_deep_factor; + + public float _snow_fresnel; + + public float _snow_diff_fresnel; + + public float _snow_metallic; + + public float _snow_Frost; + + public float _snow_MicroTiling; + + public float _snow_BumpMicro; + + public float _snow_occlusionStrength; + + public int _snow_TranslucencyDeferredLightIndex; + + public Color _SnowGlitterColor; + + public Color _GlitterColor; + + public float[] _GlitterStrength; + + public float _GlitterTiling; + + public float _GlitterDensity; + + public float _GlitterFilter; + + public float _GlitterColorization; + + public Texture2D _SparkleMap; + + public void Init(string name) + { + PresetID = string.Empty + UnityEngine.Random.value + Time.realtimeSinceStartup; + PresetName = name; + } +} diff --git a/ReliefTerrainSettingsItems.cs b/ReliefTerrainSettingsItems.cs new file mode 100644 index 0000000..ac1af7e --- /dev/null +++ b/ReliefTerrainSettingsItems.cs @@ -0,0 +1,13 @@ +public enum ReliefTerrainSettingsItems +{ + MainSettings, + UVblend, + GlobalColor, + GlobalNormal, + Superdetail, + POMSettings, + VerticalTex, + Snow, + Water, + Glitter +} diff --git a/ReliefTerrainVertexBlendTriplanar.cs b/ReliefTerrainVertexBlendTriplanar.cs new file mode 100644 index 0000000..6de2fc8 --- /dev/null +++ b/ReliefTerrainVertexBlendTriplanar.cs @@ -0,0 +1,138 @@ +using UnityEngine; + +[AddComponentMenu("Relief Terrain/Helpers/MIP solver for standalone shader")] +[ExecuteInEditMode] +public class ReliefTerrainVertexBlendTriplanar : MonoBehaviour +{ + public Texture2D tmp_globalColorMap; + + public string save_path_colormap = string.Empty; + + public GeometryVsTerrainBlend painterInstance; + + public Material material; + + public void SetupMIPOffsets() + { + if (GetComponent<Renderer>() == null && this.material == null) + { + return; + } + Material material = ((!(GetComponent<Renderer>() != null)) ? this.material : GetComponent<Renderer>().sharedMaterial); + if (material == null) + { + return; + } + if (material.HasProperty("_SplatAtlasA")) + { + SetupTex("_SplatAtlasA", "rtp_mipoffset_color", 1f, -1f); + } + if (material.HasProperty("_SplatA0")) + { + SetupTex("_SplatA0", "rtp_mipoffset_color"); + } + SetupTex("_BumpMap01", "rtp_mipoffset_bump"); + SetupTex("_TERRAIN_HeightMap", "rtp_mipoffset_height"); + if (material.HasProperty("_BumpMapGlobal")) + { + SetupTex("_BumpMapGlobal", "rtp_mipoffset_globalnorm", material.GetFloat("_BumpMapGlobalScale"), material.GetFloat("rtp_mipoffset_globalnorm_offset")); + if (material.HasProperty("_SuperDetailTiling")) + { + SetupTex("_BumpMapGlobal", "rtp_mipoffset_superdetail", material.GetFloat("_SuperDetailTiling")); + } + if (material.HasProperty("TERRAIN_FlowScale")) + { + SetupTex("_BumpMapGlobal", "rtp_mipoffset_flow", material.GetFloat("TERRAIN_FlowScale"), material.GetFloat("TERRAIN_FlowMipOffset")); + } + } + if (material.HasProperty("TERRAIN_RippleMap")) + { + SetupTex("TERRAIN_RippleMap", "rtp_mipoffset_ripple", material.GetFloat("TERRAIN_RippleScale")); + } + if (material.HasProperty("TERRAIN_CausticsTex")) + { + SetupTex("TERRAIN_CausticsTex", "rtp_mipoffset_caustics", material.GetFloat("TERRAIN_CausticsTilingScale")); + } + } + + private void SetupTex(string tex_name, string param_name, float _mult = 1f, float _add = 0f) + { + if (!(GetComponent<Renderer>() == null) || !(this.material == null)) + { + Material material = ((!(GetComponent<Renderer>() != null)) ? this.material : GetComponent<Renderer>().sharedMaterial); + if (!(material == null) && material.GetTexture(tex_name) != null) + { + int width = material.GetTexture(tex_name).width; + material.SetFloat(param_name, (0f - Mathf.Log(1024f / ((float)width * _mult))) / Mathf.Log(2f) + _add); + } + } + } + + public void SetTopPlanarUVBounds() + { + MeshFilter meshFilter = GetComponent(typeof(MeshFilter)) as MeshFilter; + if (meshFilter == null) + { + return; + } + Mesh sharedMesh = meshFilter.sharedMesh; + Vector3[] vertices = sharedMesh.vertices; + if (vertices.Length == 0) + { + return; + } + Vector3 vector = base.transform.TransformPoint(vertices[0]); + Vector4 value = default(Vector4); + value.x = vector.x; + value.y = vector.z; + value.z = vector.x; + value.w = vector.z; + for (int i = 1; i < vertices.Length; i++) + { + vector = base.transform.TransformPoint(vertices[i]); + if (vector.x < value.x) + { + value.x = vector.x; + } + if (vector.z < value.y) + { + value.y = vector.z; + } + if (vector.x > value.z) + { + value.z = vector.x; + } + if (vector.z > value.w) + { + value.w = vector.z; + } + } + value.z -= value.x; + value.w -= value.y; + if (!(GetComponent<Renderer>() == null) || !(this.material == null)) + { + Material material = ((!(GetComponent<Renderer>() != null)) ? this.material : GetComponent<Renderer>().sharedMaterial); + if (!(material == null)) + { + material.SetVector("_TERRAIN_PosSize", value); + } + } + } + + private void Awake() + { + SetupMIPOffsets(); + if (Application.isPlaying) + { + base.enabled = false; + } + } + + private void Update() + { + if (!Application.isPlaying) + { + SetupMIPOffsets(); + } + } +} diff --git a/RemoveAfterSeconds.cs b/RemoveAfterSeconds.cs new file mode 100644 index 0000000..ce32902 --- /dev/null +++ b/RemoveAfterSeconds.cs @@ -0,0 +1,19 @@ +using UnityEngine; + +public class RemoveAfterSeconds : MonoBehaviour +{ + public float seconds = 2f; + + private void Start() + { + } + + private void Update() + { + seconds -= Time.deltaTime; + if (seconds < 0f) + { + Object.Destroy(base.gameObject); + } + } +} diff --git a/RemoveMouse.cs b/RemoveMouse.cs new file mode 100644 index 0000000..85d89db --- /dev/null +++ b/RemoveMouse.cs @@ -0,0 +1,17 @@ +using UnityEngine; + +public class RemoveMouse : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + if (Input.GetKey(KeyCode.Mouse1)) + { + Cursor.lockState = CursorLockMode.Locked; + Cursor.visible = false; + } + } +} diff --git a/ResolveHoleCollision.cs b/ResolveHoleCollision.cs new file mode 100644 index 0000000..7220bf4 --- /dev/null +++ b/ResolveHoleCollision.cs @@ -0,0 +1,97 @@ +using UnityEngine; + +[AddComponentMenu("Relief Terrain/Helpers/Resolve Hole Collision")] +[RequireComponent(typeof(Collider))] +public class ResolveHoleCollision : MonoBehaviour +{ + public Collider[] entranceTriggers; + + public TerrainCollider[] terrainColliders; + + public float checkOffset = 1f; + + public bool StartBelowGroundSurface; + + private TerrainCollider terrainColliderForUpdate; + + private Collider _collider; + + private Rigidbody _rigidbody; + + private void Awake() + { + _collider = GetComponent<Collider>(); + _rigidbody = GetComponent<Rigidbody>(); + for (int i = 0; i < entranceTriggers.Length; i++) + { + if (entranceTriggers[i] != null) + { + entranceTriggers[i].isTrigger = true; + } + } + if (!(_rigidbody != null) || !StartBelowGroundSurface) + { + return; + } + for (int j = 0; j < terrainColliders.Length; j++) + { + if (terrainColliders[j] != null && _collider != null) + { + Physics.IgnoreCollision(_collider, terrainColliders[j], ignore: true); + } + } + } + + private void OnTriggerEnter(Collider other) + { + if (_collider == null) + { + return; + } + for (int i = 0; i < entranceTriggers.Length; i++) + { + if (entranceTriggers[i] == other) + { + for (int j = 0; j < terrainColliders.Length; j++) + { + Physics.IgnoreCollision(_collider, terrainColliders[j], ignore: true); + } + } + } + } + + private void FixedUpdate() + { + if (!terrainColliderForUpdate) + { + return; + } + RaycastHit hitInfo = default(RaycastHit); + if (terrainColliderForUpdate.Raycast(new Ray(base.transform.position + Vector3.up * checkOffset, Vector3.down), out hitInfo, float.PositiveInfinity)) + { + for (int i = 0; i < terrainColliders.Length; i++) + { + Physics.IgnoreCollision(_collider, terrainColliders[i], ignore: false); + } + } + terrainColliderForUpdate = null; + } + + private void OnTriggerExit(Collider other) + { + if (_collider == null) + { + return; + } + for (int i = 0; i < entranceTriggers.Length; i++) + { + if (entranceTriggers[i] == other) + { + for (int j = 0; j < terrainColliders.Length; j++) + { + Physics.IgnoreCollision(_collider, terrainColliders[j], ignore: false); + } + } + } + } +} diff --git a/ResolveHoleCollisionMultiple.cs b/ResolveHoleCollisionMultiple.cs new file mode 100644 index 0000000..6d1990e --- /dev/null +++ b/ResolveHoleCollisionMultiple.cs @@ -0,0 +1,110 @@ +using UnityEngine; + +[AddComponentMenu("Relief Terrain/Helpers/Resolve Hole Collision for multiple child colliders")] +public class ResolveHoleCollisionMultiple : MonoBehaviour +{ + public Collider[] childColliders; + + public Collider[] entranceTriggers; + + public TerrainCollider[] terrainColliders; + + public float checkOffset = 1f; + + public bool StartBelowGroundSurface; + + private TerrainCollider terrainColliderForUpdate; + + private Rigidbody _rigidbody; + + private void Awake() + { + _rigidbody = GetComponent<Rigidbody>(); + for (int i = 0; i < entranceTriggers.Length; i++) + { + if (entranceTriggers[i] != null) + { + entranceTriggers[i].isTrigger = true; + } + } + if (!(_rigidbody != null) || !StartBelowGroundSurface) + { + return; + } + for (int j = 0; j < terrainColliders.Length; j++) + { + for (int k = 0; k < childColliders.Length; k++) + { + if (terrainColliders[j] != null && childColliders[k] != null) + { + Physics.IgnoreCollision(childColliders[k], terrainColliders[j], ignore: true); + } + } + } + } + + private void OnTriggerEnter(Collider other) + { + for (int i = 0; i < entranceTriggers.Length; i++) + { + if (!(entranceTriggers[i] == other)) + { + continue; + } + for (int j = 0; j < terrainColliders.Length; j++) + { + for (int k = 0; k < childColliders.Length; k++) + { + if (childColliders[k] != null && terrainColliders[j] != null) + { + Physics.IgnoreCollision(childColliders[k], terrainColliders[j], ignore: true); + } + } + } + } + } + + private void FixedUpdate() + { + if (!terrainColliderForUpdate) + { + return; + } + RaycastHit hitInfo = default(RaycastHit); + if (terrainColliderForUpdate.Raycast(new Ray(base.transform.position + Vector3.up * checkOffset, Vector3.down), out hitInfo, float.PositiveInfinity)) + { + for (int i = 0; i < terrainColliders.Length; i++) + { + for (int j = 0; j < childColliders.Length; j++) + { + if (childColliders[j] != null && terrainColliders[i] != null) + { + Physics.IgnoreCollision(childColliders[j], terrainColliders[i], ignore: false); + } + } + } + } + terrainColliderForUpdate = null; + } + + private void OnTriggerExit(Collider other) + { + for (int i = 0; i < entranceTriggers.Length; i++) + { + if (!(entranceTriggers[i] == other)) + { + continue; + } + for (int j = 0; j < terrainColliders.Length; j++) + { + for (int k = 0; k < childColliders.Length; k++) + { + if (childColliders[k] != null && terrainColliders[j] != null) + { + Physics.IgnoreCollision(childColliders[k], terrainColliders[j], ignore: false); + } + } + } + } + } +} diff --git a/RestartOnR.cs b/RestartOnR.cs new file mode 100644 index 0000000..346eff3 --- /dev/null +++ b/RestartOnR.cs @@ -0,0 +1,16 @@ +using UnityEngine; + +public class RestartOnR : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + if (Input.GetKeyDown(KeyCode.T)) + { + Application.LoadLevel(Application.loadedLevel); + } + } +} diff --git a/RightHandPos.cs b/RightHandPos.cs new file mode 100644 index 0000000..cdc08a7 --- /dev/null +++ b/RightHandPos.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class RightHandPos : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/RigidbodyHolder.cs b/RigidbodyHolder.cs new file mode 100644 index 0000000..796f77a --- /dev/null +++ b/RigidbodyHolder.cs @@ -0,0 +1,44 @@ +using System.Collections.Generic; +using UnityEngine; + +public class RigidbodyHolder : MonoBehaviour +{ + private Rigidbody[] allRigs; + + private WeaponHandler weapons; + + private void Start() + { + allRigs = GetComponentsInChildren<Rigidbody>(); + weapons = GetComponent<WeaponHandler>(); + } + + private void Update() + { + } + + public Rigidbody[] GetAllRigs() + { + if (!weapons.leftGun && !weapons.rightGun) + { + return allRigs; + } + List<Rigidbody> list = new List<Rigidbody>(); + for (int i = 0; i < allRigs.Length; i++) + { + list.Add(allRigs[i]); + } + if ((bool)weapons) + { + if ((bool)weapons.leftGun) + { + list.Add(weapons.leftGun.rig); + } + if ((bool)weapons.rightGun) + { + list.Add(weapons.rightGun.rig); + } + } + return list.ToArray(); + } +} diff --git a/RigidbodyMovment.cs b/RigidbodyMovment.cs new file mode 100644 index 0000000..885de66 --- /dev/null +++ b/RigidbodyMovment.cs @@ -0,0 +1,10 @@ +using System; +using UnityEngine; + +[Serializable] +public class RigidbodyMovment +{ + public Rigidbody rig; + + public float force; +} diff --git a/RotateByKeyboardInput.cs b/RotateByKeyboardInput.cs new file mode 100644 index 0000000..913473c --- /dev/null +++ b/RotateByKeyboardInput.cs @@ -0,0 +1,103 @@ +using UnityEngine; + +public class RotateByKeyboardInput : MonoBehaviour +{ + public enum XSpace + { + self, + world + } + + public enum YSpace + { + self, + world + } + + public bool useX; + + public XSpace xSpace; + + public Vector3 xVector; + + public bool useY; + + public YSpace ySpace; + + public Vector3 yVector; + + [Header("Control")] + public bool needControl; + + public bool needAlive; + + private HasControl hasControl; + + private PlayerDeath death; + + private float m = 1f; + + private void Start() + { + if (needControl) + { + hasControl = base.transform.root.GetComponent<HasControl>(); + } + if (needAlive) + { + death = base.transform.root.GetComponent<PlayerDeath>(); + } + } + + private void LateUpdate() + { + Vector3 zero = Vector3.zero; + if (Input.GetKey(KeyCode.W)) + { + zero += Vector3.forward; + } + if (Input.GetKey(KeyCode.S)) + { + zero -= Vector3.forward; + } + if (Input.GetKey(KeyCode.D)) + { + zero += Vector3.right; + } + if (Input.GetKey(KeyCode.A)) + { + zero += Vector3.left; + } + zero = zero.normalized; + if (needControl && !hasControl.hasControl) + { + return; + } + if (needAlive) + { + m = Mathf.Clamp(death.muscleFunction * 2f, 0f, 1f); + if (death.dead) + { + return; + } + } + if (useX) + { + Vector3 vector = xVector; + if (xSpace == XSpace.self) + { + vector = base.transform.TransformDirection(vector); + } + base.transform.Rotate(vector * zero.x * m * 0.8f, Space.World); + } + if (useY) + { + Vector3 vector2 = yVector; + if (ySpace == YSpace.self) + { + vector2 = base.transform.TransformDirection(vector2); + } + base.transform.Rotate(vector2 * zero.y * m * 0.8f, Space.World); + } + } +} diff --git a/RotateByMouseInput.cs b/RotateByMouseInput.cs new file mode 100644 index 0000000..ced8420 --- /dev/null +++ b/RotateByMouseInput.cs @@ -0,0 +1,121 @@ +using UnityEngine; + +public class RotateByMouseInput : MonoBehaviour +{ + public enum XSpace + { + self, + world + } + + public enum YSpace + { + self, + world + } + + public bool useX; + + public XSpace xSpace; + + public Vector3 xVector; + + public bool useY; + + public YSpace ySpace; + + public Vector3 yVector; + + [Header("Control")] + public bool needControl; + + public bool needAlive; + + public bool freezeUnusedAngles; + + private HasControl hasControl; + + private PlayerDeath death; + + private float m = 1f; + + private void Start() + { + if (needControl) + { + hasControl = base.transform.root.GetComponent<HasControl>(); + } + if (needAlive) + { + death = base.transform.root.GetComponent<PlayerDeath>(); + } + } + + private void LateUpdate() + { + if (needControl && !hasControl.hasControl) + { + return; + } + if (needAlive) + { + m = Mathf.Clamp(death.muscleFunction * 2f, 0f, 1f); + if (death.dead) + { + return; + } + } + if (useX) + { + Vector3 vector = xVector; + if (xSpace == XSpace.self) + { + vector = base.transform.TransformDirection(vector); + } + base.transform.Rotate(vector * Input.GetAxis("Mouse X") * m * 0.8f, Space.World); + } + if (useY) + { + Vector3 vector2 = yVector; + if (ySpace == YSpace.self) + { + vector2 = base.transform.TransformDirection(vector2); + } + base.transform.Rotate(vector2 * Input.GetAxis("Mouse Y") * m * 0.8f, Space.World); + } + if (!freezeUnusedAngles) + { + return; + } + if (useY) + { + if (yVector.x == 0f) + { + base.transform.localRotation = Quaternion.Euler(0f, base.transform.localEulerAngles.y, base.transform.localEulerAngles.z); + } + if (yVector.y == 0f) + { + base.transform.localRotation = Quaternion.Euler(base.transform.localEulerAngles.x, 0f, base.transform.localEulerAngles.z); + } + if (yVector.z == 0f) + { + base.transform.localRotation = Quaternion.Euler(base.transform.localEulerAngles.x, base.transform.localEulerAngles.y, 0f); + } + } + if (useX) + { + if (xVector.x == 0f) + { + base.transform.localRotation = Quaternion.Euler(0f, base.transform.localEulerAngles.y, base.transform.localEulerAngles.z); + } + if (xVector.y == 0f) + { + base.transform.localRotation = Quaternion.Euler(base.transform.localEulerAngles.x, 0f, base.transform.localEulerAngles.z); + } + if (xVector.z == 0f) + { + base.transform.localRotation = Quaternion.Euler(base.transform.localEulerAngles.x, base.transform.localEulerAngles.y, 0f); + } + } + } +} diff --git a/RotationHandler.cs b/RotationHandler.cs new file mode 100644 index 0000000..ee33545 --- /dev/null +++ b/RotationHandler.cs @@ -0,0 +1,73 @@ +using UnityEngine; + +public class RotationHandler : MonoBehaviour +{ + private Transform rotationTarget; + + private Rigidbody hip; + + private Rigidbody torso; + + private Rigidbody head; + + public float rotationTorque; + + public float clamp; + + private InputHandler input; + + private PlayerDeath death; + + [HideInInspector] + public float hipCorrectionAmount; + + public bool useHip = true; + + public bool useTorso = true; + + public bool useHead = true; + + private void Start() + { + death = GetComponent<PlayerDeath>(); + rotationTarget = GetComponentInChildren<RotationTarget>().transform; + hip = GetComponentInChildren<Hip>().GetComponent<Rigidbody>(); + torso = GetComponentInChildren<Torso>().GetComponent<Rigidbody>(); + head = GetComponentInChildren<Head>().GetComponent<Rigidbody>(); + input = GetComponent<InputHandler>(); + } + + private void FixedUpdate() + { + if (!death.dead) + { + float num = head.transform.InverseTransformPoint(rotationTarget.position).x; + float num2 = torso.transform.InverseTransformPoint(rotationTarget.position).x; + hipCorrectionAmount = hip.transform.InverseTransformPoint(hip.transform.position + input.lastInputDirection * 10f).x; + float muscleFunction = death.muscleFunction; + float num3 = 0.3f; + if (input.inputMovementDirection.magnitude > 0.1f) + { + num3 = 1f; + } + if (clamp != 0f) + { + hipCorrectionAmount = Mathf.Clamp(hipCorrectionAmount, 0f - clamp, clamp); + num = Mathf.Clamp(num, 0f - clamp, clamp); + num2 = Mathf.Clamp(num2, 0f - clamp, clamp); + } + if (useHip) + { + hip.AddTorque(Vector3.up * muscleFunction * rotationTorque * num3 * hipCorrectionAmount, ForceMode.Acceleration); + } + if (useTorso) + { + torso.AddTorque(Vector3.up * muscleFunction * rotationTorque * num2, ForceMode.Acceleration); + } + if (useHead) + { + head.AddTorque(Vector3.up * muscleFunction * rotationTorque * num, ForceMode.Acceleration); + } + } + } +} diff --git a/RotationTarget.cs b/RotationTarget.cs new file mode 100644 index 0000000..02c8bec --- /dev/null +++ b/RotationTarget.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class RotationTarget : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/RuntimeDecalCombiner.cs b/RuntimeDecalCombiner.cs new file mode 100644 index 0000000..31c1822 --- /dev/null +++ b/RuntimeDecalCombiner.cs @@ -0,0 +1,68 @@ +using System.Collections.Generic; +using ch.sycoforge.Decal; +using ch.sycoforge.Decal.Projectors.Geometry; +using UnityEngine; + +public class RuntimeDecalCombiner +{ + public static List<GameObject> Combine(IList<EasyDecal> decals) + { + Dictionary<DecalTextureAtlas, List<EasyDecal>> dictionary = new Dictionary<DecalTextureAtlas, List<EasyDecal>>(); + foreach (EasyDecal decal in decals) + { + if (decal.Source == SourceMode.Atlas && decal.Projector != null) + { + if (!dictionary.ContainsKey(decal.Atlas)) + { + dictionary.Add(decal.Atlas, new List<EasyDecal>()); + } + dictionary[decal.Atlas].Add(decal); + } + } + return Combine(dictionary); + } + + private static List<GameObject> Combine(Dictionary<DecalTextureAtlas, List<EasyDecal>> mappings) + { + List<GameObject> list = new List<GameObject>(); + if (mappings.Count > 0) + { + foreach (DecalTextureAtlas key in mappings.Keys) + { + IList<EasyDecal> list2 = mappings[key]; + foreach (EasyDecal item in list2) + { + GameObject gameObject = Combine(list2, key); + if (gameObject != null) + { + list.Add(gameObject); + } + } + } + return list; + } + return list; + } + + private static GameObject Combine(IList<EasyDecal> decals, DecalTextureAtlas atlas) + { + if (decals.Count > 0) + { + DynamicMesh dynamicMesh = new DynamicMesh(DecalBase.DecalRoot, RecreationMode.Always); + GameObject gameObject = new GameObject($"Combined Decals Root [{atlas.name}]"); + MeshFilter meshFilter = gameObject.AddComponent<MeshFilter>(); + MeshRenderer meshRenderer = gameObject.AddComponent<MeshRenderer>(); + foreach (EasyDecal decal in decals) + { + if (decal.Source == SourceMode.Atlas && decal.Projector != null) + { + dynamicMesh.Add(decal.Projector.Mesh, decal.LocalToWorldMatrix, gameObject.transform.worldToLocalMatrix); + decal.gameObject.SetActive(value: false); + } + } + meshRenderer.material = atlas.Material; + meshFilter.sharedMesh = dynamicMesh.ConvertToMesh(null); + } + return null; + } +} diff --git a/SFXPlayer.cs b/SFXPlayer.cs new file mode 100644 index 0000000..ec85233 --- /dev/null +++ b/SFXPlayer.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; +using UnityEngine; + +public class SFXPlayer : MonoBehaviour +{ + public List<AudioClip> metal; + + public List<AudioClip> other; + + internal void Play(RaycastHit hit) + { + AudioSource component = GetComponent<AudioSource>(); + component.mute = true; + //List<AudioClip> list = new List<AudioClip>(); + //list = ((!hit.rigidbody) ? other : metal); + //if (!hit.rigidbody) + //{ + // component.volume *= 0.5f; + //} + //component.clip = list[Random.Range(0, list.Count)]; + //component.Play(); + } +} diff --git a/ScreenShakeByCollision.cs b/ScreenShakeByCollision.cs new file mode 100644 index 0000000..14cd1ca --- /dev/null +++ b/ScreenShakeByCollision.cs @@ -0,0 +1,34 @@ +using UnityEngine; + +public class ScreenShakeByCollision : MonoBehaviour +{ + private WobbleShake shake; + + private void Start() + { + shake = base.transform.root.GetComponentInChildren<WobbleShake>(); + } + + private void Update() + { + } + + private void OnCollisionEnter(Collision collision) + { + Collide(collision); + shake.AddShakeWorld(collision.relativeVelocity * -0.08f, 0.9f); + } + + private void OnCollisionStay(Collision collision) + { + Collide(collision); + shake.AddShakeWorld(collision.relativeVelocity * -0.01f, 0.9f); + } + + private void Collide(Collision collision) + { + if (!(collision.transform.root == base.transform.root)) + { + } + } +} diff --git a/SelectorHelperClass.cs b/SelectorHelperClass.cs new file mode 100644 index 0000000..84bc50f --- /dev/null +++ b/SelectorHelperClass.cs @@ -0,0 +1,5 @@ +using UnityEngine; + +public class SelectorHelperClass : MonoBehaviour +{ +} diff --git a/SetAnimationByInput.cs b/SetAnimationByInput.cs new file mode 100644 index 0000000..cc50e5a --- /dev/null +++ b/SetAnimationByInput.cs @@ -0,0 +1,40 @@ +using UnityEngine; + +public class SetAnimationByInput : MonoBehaviour +{ + private InputHandler input; + + private AnimationHandler anim; + + private StandingDataHandler standingData; + + private void Start() + { + anim = GetComponent<AnimationHandler>(); + input = GetComponent<InputHandler>(); + standingData = GetComponent<StandingDataHandler>(); + } + + private void Update() + { + if ((double)standingData.sinceGrounded > 0.2) + { + anim.animationState = 3; + } + else if (input.inputMovementDirection.magnitude > 0.1f) + { + if (input.isSpringting) + { + anim.animationState = 1; + } + else + { + anim.animationState = 2; + } + } + else + { + anim.animationState = 0; + } + } +} diff --git a/SetAnimationByVelocity.cs b/SetAnimationByVelocity.cs new file mode 100644 index 0000000..c737363 --- /dev/null +++ b/SetAnimationByVelocity.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class SetAnimationByVelocity : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/SetInertiaTension.cs b/SetInertiaTension.cs new file mode 100644 index 0000000..82a713c --- /dev/null +++ b/SetInertiaTension.cs @@ -0,0 +1,43 @@ +using UnityEngine; + +public class SetInertiaTension : MonoBehaviour +{ + private Vector3 defaultInertia; + + private Vector3 stableInertia = Vector3.one; + + public float collisionValue; + + private Rigidbody rig; + + private HoldableObject holdable; + + private void Start() + { + rig = GetComponent<Rigidbody>(); + holdable = GetComponent<HoldableObject>(); + defaultInertia = rig.inertiaTensor; + } + + private void Update() + { + collisionValue = Mathf.Lerp(collisionValue, 0f, Time.deltaTime * 7f); + rig.inertiaTensor = Vector3.Lerp(stableInertia, defaultInertia, Mathf.Clamp(collisionValue, 0f, 1f)); + } + + private void OnCollisionEnter(Collision collision) + { + if (!(collision.transform.root == base.transform.root) && !(collision.transform.root == holdable.holder)) + { + collisionValue += collision.relativeVelocity.magnitude * 0.4f; + } + } + + private void OnCollisionStay(Collision collision) + { + if (!(collision.transform.root == base.transform.root) && !(collision.transform.root == holdable.holder)) + { + collisionValue += collision.relativeVelocity.magnitude * 0.2f; + } + } +} diff --git a/SetMainCamera.cs b/SetMainCamera.cs new file mode 100644 index 0000000..82d3f5f --- /dev/null +++ b/SetMainCamera.cs @@ -0,0 +1,18 @@ +using UnityEngine; + +public class SetMainCamera : MonoBehaviour +{ + public bool mainCamera; + + private void Awake() + { + if (mainCamera) + { + base.gameObject.tag = "MainCamera"; + } + else + { + base.gameObject.tag = "Untagged"; + } + } +} diff --git a/SetRigidbodySettings.cs b/SetRigidbodySettings.cs new file mode 100644 index 0000000..2521b75 --- /dev/null +++ b/SetRigidbodySettings.cs @@ -0,0 +1,20 @@ +using UnityEngine; + +public class SetRigidbodySettings : MonoBehaviour +{ + public float maxAngular; + + private void Start() + { + Rigidbody[] componentsInChildren = GetComponentsInChildren<Rigidbody>(); + foreach (Rigidbody rigidbody in componentsInChildren) + { + rigidbody.maxAngularVelocity = maxAngular; + rigidbody.maxDepenetrationVelocity = 10000f; + } + } + + private void Update() + { + } +} diff --git a/SetWobblerIfHeld.cs b/SetWobblerIfHeld.cs new file mode 100644 index 0000000..538ef49 --- /dev/null +++ b/SetWobblerIfHeld.cs @@ -0,0 +1,29 @@ +using UnityEngine; + +public class SetWobblerIfHeld : MonoBehaviour +{ + private AddScreenShake shaker; + + private HoldableObject held; + + private void Start() + { + shaker = GetComponent<AddScreenShake>(); + held = GetComponent<HoldableObject>(); + } + + private void Update() + { + if ((bool)held.holder) + { + if (!shaker.wobbleShake) + { + shaker.wobbleShake = held.holder.GetComponentInChildren<WobbleShake>(); + } + } + else if ((bool)shaker.wobbleShake) + { + shaker.wobbleShake = null; + } + } +} diff --git a/ShootPosition.cs b/ShootPosition.cs new file mode 100644 index 0000000..8ea660a --- /dev/null +++ b/ShootPosition.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class ShootPosition : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/Slither.cs b/Slither.cs new file mode 100644 index 0000000..bd176f4 --- /dev/null +++ b/Slither.cs @@ -0,0 +1,29 @@ +using UnityEngine; + +public class Slither : MonoBehaviour +{ + public float offset; + + public float timeMultiplier = 1f; + + public AnimationCurve slitherCurve; + + public float forceMultiplier; + + private GenericForceMovement movement; + + private void Start() + { + movement = GetComponent<GenericForceMovement>(); + timeMultiplier *= Random.Range(0.9f, 1.1f); + } + + private void FixedUpdate() + { + Vector3 normalized = Vector3.Cross(movement.movementDirection, Vector3.up).normalized; + for (int i = 0; i < movement.rigs.Length; i++) + { + movement.rigs[i].rig.AddForce(normalized * forceMultiplier * slitherCurve.Evaluate((Time.time * timeMultiplier + offset * (float)i) % 1f) / ((float)i * 0.2f + 1f), ForceMode.Acceleration); + } + } +} diff --git a/SnakeAI.cs b/SnakeAI.cs new file mode 100644 index 0000000..0971888 --- /dev/null +++ b/SnakeAI.cs @@ -0,0 +1,23 @@ +using UnityEngine; + +public class SnakeAI : MonoBehaviour +{ + private GenericForceMovement movement; + + public Transform target; + + private Transform head; + + private void Start() + { + movement = GetComponent<GenericForceMovement>(); + head = GetComponentInChildren<Head>().transform; + target = Object.FindObjectOfType<Player>().transform.root.GetComponentInChildren<Hip>().transform; + GetComponent<AddForceToTarget>().target = target.GetComponent<Rigidbody>(); + } + + private void Update() + { + movement.movementDirection = (target.transform.position - head.position).normalized; + } +} diff --git a/SparksExecutioner.cs b/SparksExecutioner.cs new file mode 100644 index 0000000..5b28cf8 --- /dev/null +++ b/SparksExecutioner.cs @@ -0,0 +1,16 @@ +using UnityEngine; + +public class SparksExecutioner : MonoBehaviour +{ + public float Lifetime = 1f; + + private void Start() + { + Invoke("Kill", Lifetime); + } + + private void Kill() + { + Object.Destroy(base.gameObject); + } +} diff --git a/SpawnerHolder.cs b/SpawnerHolder.cs new file mode 100644 index 0000000..b74c1d9 --- /dev/null +++ b/SpawnerHolder.cs @@ -0,0 +1,7 @@ +using UnityEngine; + +public class SpawnerHolder : MonoBehaviour +{ + [HideInInspector] + public Transform spawner; +} diff --git a/SquaredDrag.cs b/SquaredDrag.cs new file mode 100644 index 0000000..98acbad --- /dev/null +++ b/SquaredDrag.cs @@ -0,0 +1,22 @@ +using UnityEngine; + +public class SquaredDrag : MonoBehaviour +{ + public float drag; + + public float angularDrag; + + public float exponent; + + private Rigidbody rig; + + private void Start() + { + } + + private void FixedUpdate() + { + rig.velocity += Mathf.Pow(rig.velocity.magnitude, exponent) * rig.velocity.normalized; + rig.velocity += Mathf.Pow(rig.velocity.magnitude, exponent) * rig.velocity.normalized; + } +} diff --git a/StabilizeRigidbody.cs b/StabilizeRigidbody.cs new file mode 100644 index 0000000..c1a658f --- /dev/null +++ b/StabilizeRigidbody.cs @@ -0,0 +1,16 @@ +using UnityEngine; + +public class StabilizeRigidbody : MonoBehaviour +{ + private Rigidbody rig; + + private void Start() + { + rig = GetComponent<Rigidbody>(); + } + + private void FixedUpdate() + { + rig.velocity = new Vector3(rig.velocity.x, rig.velocity.y * 0.3f, rig.velocity.z); + } +} diff --git a/Standing.cs b/Standing.cs new file mode 100644 index 0000000..6162215 --- /dev/null +++ b/Standing.cs @@ -0,0 +1,55 @@ +using UnityEngine; + +public class Standing : MonoBehaviour +{ + public RigidbodyMovment[] rigsToLift; + + public AnimationCurve[] animationLiftCurves; + + private StandingDataHandler standingData; + + private AnimationHandler animationHandler; + + public float offset; + + private PlayerDeath death; + + private Strength str; + + private float muscleMultiplier = 1f; + + private float legAngleMultiplier; + + private MovementDataHandler moveData; + + private void Start() + { + death = GetComponent<PlayerDeath>(); + str = GetComponent<Strength>(); + standingData = GetComponent<StandingDataHandler>(); + moveData = GetComponent<MovementDataHandler>(); + animationHandler = GetComponent<AnimationHandler>(); + } + + private void FixedUpdate() + { + if (!death.dead) + { + muscleMultiplier = str.strength; + if (standingData.isGrounded) + { + Stand(animationLiftCurves[animationHandler.animationState]); + } + } + } + + private void Stand(AnimationCurve curve) + { + legAngleMultiplier = 1f; + RigidbodyMovment[] array = rigsToLift; + foreach (RigidbodyMovment rigidbodyMovment in array) + { + rigidbodyMovment.rig.AddForce(Vector3.up * muscleMultiplier * rigidbodyMovment.force * legAngleMultiplier * curve.Evaluate(standingData.distanceToGround + offset + moveData.slopeVelocityStrenght * -0.2f), ForceMode.Acceleration); + } + } +} diff --git a/StandingDataHandler.cs b/StandingDataHandler.cs new file mode 100644 index 0000000..10a1473 --- /dev/null +++ b/StandingDataHandler.cs @@ -0,0 +1,69 @@ +using UnityEngine; + +public class StandingDataHandler : MonoBehaviour +{ + public Rigidbody mainRig; + + public float sinceGrounded; + + public float sinceLanded; + + public bool isGrounded; + + public float distanceToGround = 1f; + + private bool hasRecievedTouchedGround; + + private MovementDataHandler moveMentData; + + private PlayerKnockback knockback; + + private WobbleShake wobbleShake; + + private void Start() + { + wobbleShake = GetComponentInChildren<WobbleShake>(); + knockback = GetComponent<PlayerKnockback>(); + } + + private void FixedUpdate() + { + sinceGrounded += Time.fixedDeltaTime; + sinceLanded += Time.fixedDeltaTime; + moveMentData = GetComponent<MovementDataHandler>(); + if ((double)sinceGrounded > 0.1) + { + isGrounded = false; + } + } + + private void LateUpdate() + { + hasRecievedTouchedGround = false; + } + + public void TouchGround(float distance, Vector3 normal) + { + if (sinceGrounded > 0.5f && (bool)wobbleShake) + { + wobbleShake.AddShake(-Vector3.up * 5f * Mathf.Pow(sinceGrounded, 1.5f), 0.8f); + } + if (sinceGrounded > 0.5f) + { + Land(sinceGrounded); + } + sinceGrounded = 0f; + isGrounded = true; + if (distance > distanceToGround || !hasRecievedTouchedGround) + { + distanceToGround = distance; + } + hasRecievedTouchedGround = true; + moveMentData.SetSlope(normal); + } + + private void Land(float landForce) + { + sinceLanded = 0f; + } +} diff --git a/StartRotation.cs b/StartRotation.cs new file mode 100644 index 0000000..4ae91b2 --- /dev/null +++ b/StartRotation.cs @@ -0,0 +1,18 @@ +using UnityEngine; + +public class StartRotation : MonoBehaviour +{ + public Quaternion startRotation; + + public Quaternion startRotationLocal; + + private void Start() + { + startRotation = base.transform.rotation; + startRotationLocal = base.transform.localRotation; + } + + private void Update() + { + } +} diff --git a/StayInPlace.cs b/StayInPlace.cs new file mode 100644 index 0000000..d10ebba --- /dev/null +++ b/StayInPlace.cs @@ -0,0 +1,50 @@ +using UnityEngine; + +public class StayInPlace : MonoBehaviour +{ + private InputHandler input; + + public Rigidbody rig; + + public float force; + + private Vector3 stopPosition; + + private bool isBroken; + + private PlayerDeath death; + + private Strength str; + + private float strength = 1f; + + private void Start() + { + str = GetComponent<Strength>(); + input = GetComponent<InputHandler>(); + death = GetComponent<PlayerDeath>(); + stopPosition = rig.position; + } + + private void FixedUpdate() + { + if (death.dead) + { + return; + } + strength = str.strength; + if (input.inputMovementDirection.magnitude > 0.1f) + { + stopPosition = rig.position + rig.velocity * 0.25f; + isBroken = false; + } + else if (!isBroken) + { + if (Vector3.Distance(stopPosition, rig.position) > 1f) + { + isBroken = true; + } + rig.AddForce((stopPosition - rig.position) * force * strength, ForceMode.Acceleration); + } + } +} @@ -0,0 +1,11 @@ +using System; + +[Serializable] +public class Step +{ + public float minTime; + + public float maxTime; + + public float minAngle; +} diff --git a/StepHandler.cs b/StepHandler.cs new file mode 100644 index 0000000..fd8110b --- /dev/null +++ b/StepHandler.cs @@ -0,0 +1,53 @@ +using UnityEngine; + +public class StepHandler : MonoBehaviour +{ + public float staticCounter; + + public Step[] steps; + + public bool isLeft; + + private float counter; + + private Transform leftLeg; + + private Transform rightLeg; + + private AnimationHandler animationHandler; + + private Transform hip; + + private void Start() + { + if (staticCounter == 0f) + { + leftLeg = GetComponentInChildren<LegLeft>().transform; + rightLeg = GetComponentInChildren<LegRight>().transform; + animationHandler = GetComponent<AnimationHandler>(); + hip = GetComponentInChildren<Hip>().transform; + } + } + + private void Update() + { + counter += Time.deltaTime; + if (staticCounter != 0f) + { + if (counter > staticCounter) + { + Switch(); + } + } + else if (counter > steps[animationHandler.animationState].minTime && (steps[animationHandler.animationState].minAngle == 0f || steps[animationHandler.animationState].minAngle < Vector3.Angle(leftLeg.forward, rightLeg.forward)) && isLeft == hip.InverseTransformPoint(leftLeg.position + leftLeg.forward).z > hip.InverseTransformPoint(rightLeg.position + rightLeg.forward).z) + { + Switch(); + } + } + + private void Switch() + { + isLeft = !isLeft; + counter = 0f; + } +} diff --git a/Strength.cs b/Strength.cs new file mode 100644 index 0000000..f458b21 --- /dev/null +++ b/Strength.cs @@ -0,0 +1,21 @@ +using UnityEngine; + +public class Strength : MonoBehaviour +{ + public float strength = 1f; + + private PlayerDeath death; + + private RagdollHandler ragdoll; + + private void Start() + { + ragdoll = GetComponent<RagdollHandler>(); + death = GetComponent<PlayerDeath>(); + } + + private void Update() + { + strength = ragdoll.ragdollValue * death.muscleFunction; + } +} diff --git a/SyncCausticsWaterLevel.cs b/SyncCausticsWaterLevel.cs new file mode 100644 index 0000000..7bfadff --- /dev/null +++ b/SyncCausticsWaterLevel.cs @@ -0,0 +1,22 @@ +using UnityEngine; + +[AddComponentMenu("Relief Terrain/Helpers/Sync Caustics Water Level")] +[ExecuteInEditMode] +public class SyncCausticsWaterLevel : MonoBehaviour +{ + public GameObject refGameObject; + + public float yOffset; + + private void Update() + { + if ((bool)refGameObject && (bool)refGameObject.GetComponent<Renderer>()) + { + refGameObject.GetComponent<Renderer>().sharedMaterial.SetFloat("TERRAIN_CausticsWaterLevel", base.transform.position.y + yOffset); + } + else + { + Shader.SetGlobalFloat("TERRAIN_CausticsWaterLevel", base.transform.position.y + yOffset); + } + } +} diff --git a/TMPro/TMP_DigitValidator.cs b/TMPro/TMP_DigitValidator.cs new file mode 100644 index 0000000..80e3a77 --- /dev/null +++ b/TMPro/TMP_DigitValidator.cs @@ -0,0 +1,17 @@ +using System; + +namespace TMPro; + +[Serializable] +public class TMP_DigitValidator : TMP_InputValidator +{ + public override char Validate(ref string text, ref int pos, char ch) + { + if (ch >= '0' && ch <= '9') + { + pos++; + return ch; + } + return '\0'; + } +} diff --git a/TMPro/TMP_TextEventHandler.cs b/TMPro/TMP_TextEventHandler.cs new file mode 100644 index 0000000..d952b46 --- /dev/null +++ b/TMPro/TMP_TextEventHandler.cs @@ -0,0 +1,208 @@ +using System; +using UnityEngine; +using UnityEngine.Events; +using UnityEngine.EventSystems; + +namespace TMPro; + +public class TMP_TextEventHandler : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IEventSystemHandler +{ + [Serializable] + public class CharacterSelectionEvent : UnityEvent<char, int> + { + } + + [Serializable] + public class WordSelectionEvent : UnityEvent<string, int, int> + { + } + + [Serializable] + public class LineSelectionEvent : UnityEvent<string, int, int> + { + } + + [Serializable] + public class LinkSelectionEvent : UnityEvent<string, string, int> + { + } + + [SerializeField] + private CharacterSelectionEvent m_OnCharacterSelection = new CharacterSelectionEvent(); + + [SerializeField] + private WordSelectionEvent m_OnWordSelection = new WordSelectionEvent(); + + [SerializeField] + private LineSelectionEvent m_OnLineSelection = new LineSelectionEvent(); + + [SerializeField] + private LinkSelectionEvent m_OnLinkSelection = new LinkSelectionEvent(); + + private TMP_Text m_TextComponent; + + private Camera m_Camera; + + private Canvas m_Canvas; + + private int m_selectedLink = -1; + + private int m_lastCharIndex = -1; + + private int m_lastWordIndex = -1; + + private int m_lastLineIndex = -1; + + public CharacterSelectionEvent onCharacterSelection + { + get + { + return m_OnCharacterSelection; + } + set + { + m_OnCharacterSelection = value; + } + } + + public WordSelectionEvent onWordSelection + { + get + { + return m_OnWordSelection; + } + set + { + m_OnWordSelection = value; + } + } + + public LineSelectionEvent onLineSelection + { + get + { + return m_OnLineSelection; + } + set + { + m_OnLineSelection = value; + } + } + + public LinkSelectionEvent onLinkSelection + { + get + { + return m_OnLinkSelection; + } + set + { + m_OnLinkSelection = value; + } + } + + private void Awake() + { + m_TextComponent = base.gameObject.GetComponent<TMP_Text>(); + if (m_TextComponent.GetType() == typeof(TextMeshProUGUI)) + { + m_Canvas = base.gameObject.GetComponentInParent<Canvas>(); + if (m_Canvas != null) + { + if (m_Canvas.renderMode == RenderMode.ScreenSpaceOverlay) + { + m_Camera = null; + } + else + { + m_Camera = m_Canvas.worldCamera; + } + } + } + else + { + m_Camera = Camera.main; + } + } + + private void LateUpdate() + { + if (!TMP_TextUtilities.IsIntersectingRectTransform(m_TextComponent.rectTransform, Input.mousePosition, m_Camera)) + { + return; + } + int num = TMP_TextUtilities.FindIntersectingCharacter(m_TextComponent, Input.mousePosition, m_Camera, visibleOnly: true); + if (num != -1 && num != m_lastCharIndex) + { + m_lastCharIndex = num; + SendOnCharacterSelection(m_TextComponent.textInfo.characterInfo[num].character, num); + } + int num2 = TMP_TextUtilities.FindIntersectingWord(m_TextComponent, Input.mousePosition, m_Camera); + if (num2 != -1 && num2 != m_lastWordIndex) + { + m_lastWordIndex = num2; + TMP_WordInfo tMP_WordInfo = m_TextComponent.textInfo.wordInfo[num2]; + SendOnWordSelection(tMP_WordInfo.GetWord(), tMP_WordInfo.firstCharacterIndex, tMP_WordInfo.characterCount); + } + int num3 = TMP_TextUtilities.FindIntersectingLine(m_TextComponent, Input.mousePosition, m_Camera); + if (num3 != -1 && num3 != m_lastLineIndex) + { + m_lastLineIndex = num3; + TMP_LineInfo tMP_LineInfo = m_TextComponent.textInfo.lineInfo[num3]; + char[] array = new char[tMP_LineInfo.characterCount]; + for (int i = 0; i < tMP_LineInfo.characterCount && i < m_TextComponent.textInfo.characterInfo.Length; i++) + { + array[i] = m_TextComponent.textInfo.characterInfo[i + tMP_LineInfo.firstCharacterIndex].character; + } + string line = new string(array); + SendOnLineSelection(line, tMP_LineInfo.firstCharacterIndex, tMP_LineInfo.characterCount); + } + int num4 = TMP_TextUtilities.FindIntersectingLink(m_TextComponent, Input.mousePosition, m_Camera); + if (num4 != -1 && num4 != m_selectedLink) + { + m_selectedLink = num4; + TMP_LinkInfo tMP_LinkInfo = m_TextComponent.textInfo.linkInfo[num4]; + SendOnLinkSelection(tMP_LinkInfo.GetLinkID(), tMP_LinkInfo.GetLinkText(), num4); + } + } + + public void OnPointerEnter(PointerEventData eventData) + { + } + + public void OnPointerExit(PointerEventData eventData) + { + } + + private void SendOnCharacterSelection(char character, int characterIndex) + { + if (onCharacterSelection != null) + { + onCharacterSelection.Invoke(character, characterIndex); + } + } + + private void SendOnWordSelection(string word, int charIndex, int length) + { + if (onWordSelection != null) + { + onWordSelection.Invoke(word, charIndex, length); + } + } + + private void SendOnLineSelection(string line, int charIndex, int length) + { + if (onLineSelection != null) + { + onLineSelection.Invoke(line, charIndex, length); + } + } + + private void SendOnLinkSelection(string linkID, string linkText, int linkIndex) + { + if (onLinkSelection != null) + { + onLinkSelection.Invoke(linkID, linkText, linkIndex); + } + } +} diff --git a/TerrainShaderLod.cs b/TerrainShaderLod.cs new file mode 100644 index 0000000..258dca7 --- /dev/null +++ b/TerrainShaderLod.cs @@ -0,0 +1,6 @@ +public enum TerrainShaderLod +{ + POM, + PM, + SIMPLE +} diff --git a/TimeTrail.cs b/TimeTrail.cs new file mode 100644 index 0000000..0f021a5 --- /dev/null +++ b/TimeTrail.cs @@ -0,0 +1,69 @@ +using TMPro; +using UnityEngine; + +public class TimeTrail : MonoBehaviour +{ + public Transform populateArrayFromTransform; + + public Damagable[] targets; + + public TextMeshProUGUI text; + + public TextMeshProUGUI best; + + private int targetsKilled; + + private float counter; + + private bool done; + + private void Start() + { + text = GetComponentInChildren<TextMeshProUGUI>(); + if ((bool)populateArrayFromTransform) + { + targets = populateArrayFromTransform.GetComponentsInChildren<Damagable>(); + } + Damagable[] array = targets; + foreach (Damagable damagable in array) + { + damagable.outOfLiveEvent.AddListener(KillTarget); + } + } + + private void Update() + { + if (!done) + { + counter += Time.deltaTime; + } + if (Input.GetKey(KeyCode.P)) + { + PlayerPrefs.SetFloat("Best", 999f); + } + best.text = "BEST: " + PlayerPrefs.GetFloat("Best"); + text.text = counter.ToString("f2"); + } + + public void KillTarget() + { + targetsKilled++; + if (targetsKilled >= targets.Length) + { + Finish(); + } + } + + private void Finish() + { + done = true; + if (counter < PlayerPrefs.GetFloat("Best")) + { + PlayerPrefs.SetFloat("Best", counter); + } + } + + private void Restart() + { + } +} diff --git a/Torso.cs b/Torso.cs new file mode 100644 index 0000000..3cf28df --- /dev/null +++ b/Torso.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class Torso : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/TransformVelocity.cs b/TransformVelocity.cs new file mode 100644 index 0000000..da843fc --- /dev/null +++ b/TransformVelocity.cs @@ -0,0 +1,19 @@ +using UnityEngine; + +public class TransformVelocity : MonoBehaviour +{ + public Vector3 velocity; + + private Vector3 lastPosition; + + private void Start() + { + lastPosition = base.transform.position; + } + + private void FixedUpdate() + { + velocity = base.transform.position - lastPosition; + lastPosition = base.transform.position; + } +} diff --git a/UnityEngine.PostProcessing/AmbientOcclusionComponent.cs b/UnityEngine.PostProcessing/AmbientOcclusionComponent.cs new file mode 100644 index 0000000..d1dbda2 --- /dev/null +++ b/UnityEngine.PostProcessing/AmbientOcclusionComponent.cs @@ -0,0 +1,160 @@ +using UnityEngine.Rendering; + +namespace UnityEngine.PostProcessing; + +public sealed class AmbientOcclusionComponent : PostProcessingComponentCommandBuffer<AmbientOcclusionModel> +{ + private static class Uniforms + { + internal static readonly int _Intensity = Shader.PropertyToID("_Intensity"); + + internal static readonly int _Radius = Shader.PropertyToID("_Radius"); + + internal static readonly int _FogParams = Shader.PropertyToID("_FogParams"); + + internal static readonly int _Downsample = Shader.PropertyToID("_Downsample"); + + internal static readonly int _SampleCount = Shader.PropertyToID("_SampleCount"); + + internal static readonly int _OcclusionTexture1 = Shader.PropertyToID("_OcclusionTexture1"); + + internal static readonly int _OcclusionTexture2 = Shader.PropertyToID("_OcclusionTexture2"); + + internal static readonly int _OcclusionTexture = Shader.PropertyToID("_OcclusionTexture"); + + internal static readonly int _MainTex = Shader.PropertyToID("_MainTex"); + + internal static readonly int _TempRT = Shader.PropertyToID("_TempRT"); + } + + private enum OcclusionSource + { + DepthTexture, + DepthNormalsTexture, + GBuffer + } + + private const string k_BlitShaderString = "Hidden/Post FX/Blit"; + + private const string k_ShaderString = "Hidden/Post FX/Ambient Occlusion"; + + private readonly RenderTargetIdentifier[] m_MRT = new RenderTargetIdentifier[2] + { + BuiltinRenderTextureType.GBuffer0, + BuiltinRenderTextureType.CameraTarget + }; + + private OcclusionSource occlusionSource + { + get + { + if (context.isGBufferAvailable && !base.model.settings.forceForwardCompatibility) + { + return OcclusionSource.GBuffer; + } + if (base.model.settings.highPrecision && (!context.isGBufferAvailable || base.model.settings.forceForwardCompatibility)) + { + return OcclusionSource.DepthTexture; + } + return OcclusionSource.DepthNormalsTexture; + } + } + + private bool ambientOnlySupported => context.isHdr && base.model.settings.ambientOnly && context.isGBufferAvailable && !base.model.settings.forceForwardCompatibility; + + public override bool active => base.model.enabled && base.model.settings.intensity > 0f && !context.interrupted; + + public override DepthTextureMode GetCameraFlags() + { + DepthTextureMode depthTextureMode = DepthTextureMode.None; + if (occlusionSource == OcclusionSource.DepthTexture) + { + depthTextureMode |= DepthTextureMode.Depth; + } + if (occlusionSource != OcclusionSource.GBuffer) + { + depthTextureMode |= DepthTextureMode.DepthNormals; + } + return depthTextureMode; + } + + public override string GetName() + { + return "Ambient Occlusion"; + } + + public override CameraEvent GetCameraEvent() + { + return (!ambientOnlySupported || context.profile.debugViews.IsModeActive(BuiltinDebugViewsModel.Mode.AmbientOcclusion)) ? CameraEvent.BeforeImageEffectsOpaque : CameraEvent.BeforeReflections; + } + + public override void PopulateCommandBuffer(CommandBuffer cb) + { + AmbientOcclusionModel.Settings settings = base.model.settings; + Material mat = context.materialFactory.Get("Hidden/Post FX/Blit"); + Material material = context.materialFactory.Get("Hidden/Post FX/Ambient Occlusion"); + material.shaderKeywords = null; + material.SetFloat(Uniforms._Intensity, settings.intensity); + material.SetFloat(Uniforms._Radius, settings.radius); + material.SetFloat(Uniforms._Downsample, (!settings.downsampling) ? 1f : 0.5f); + material.SetInt(Uniforms._SampleCount, (int)settings.sampleCount); + if (!context.isGBufferAvailable && RenderSettings.fog) + { + material.SetVector(Uniforms._FogParams, new Vector3(RenderSettings.fogDensity, RenderSettings.fogStartDistance, RenderSettings.fogEndDistance)); + switch (RenderSettings.fogMode) + { + case FogMode.Linear: + material.EnableKeyword("FOG_LINEAR"); + break; + case FogMode.Exponential: + material.EnableKeyword("FOG_EXP"); + break; + case FogMode.ExponentialSquared: + material.EnableKeyword("FOG_EXP2"); + break; + } + } + else + { + material.EnableKeyword("FOG_OFF"); + } + int width = context.width; + int height = context.height; + int num = ((!settings.downsampling) ? 1 : 2); + int occlusionTexture = Uniforms._OcclusionTexture1; + cb.GetTemporaryRT(occlusionTexture, width / num, height / num, 0, FilterMode.Bilinear, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); + cb.Blit(null, occlusionTexture, material, (int)occlusionSource); + int occlusionTexture2 = Uniforms._OcclusionTexture2; + cb.GetTemporaryRT(occlusionTexture2, width, height, 0, FilterMode.Bilinear, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); + cb.SetGlobalTexture(Uniforms._MainTex, occlusionTexture); + cb.Blit(occlusionTexture, occlusionTexture2, material, (occlusionSource != OcclusionSource.GBuffer) ? 3 : 4); + cb.ReleaseTemporaryRT(occlusionTexture); + occlusionTexture = Uniforms._OcclusionTexture; + cb.GetTemporaryRT(occlusionTexture, width, height, 0, FilterMode.Bilinear, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); + cb.SetGlobalTexture(Uniforms._MainTex, occlusionTexture2); + cb.Blit(occlusionTexture2, occlusionTexture, material, 5); + cb.ReleaseTemporaryRT(occlusionTexture2); + if (context.profile.debugViews.IsModeActive(BuiltinDebugViewsModel.Mode.AmbientOcclusion)) + { + cb.SetGlobalTexture(Uniforms._MainTex, occlusionTexture); + cb.Blit(occlusionTexture, BuiltinRenderTextureType.CameraTarget, material, 8); + context.Interrupt(); + } + else if (ambientOnlySupported) + { + cb.SetRenderTarget(m_MRT, BuiltinRenderTextureType.CameraTarget); + cb.DrawMesh(GraphicsUtils.quad, Matrix4x4.identity, material, 0, 7); + } + else + { + RenderTextureFormat format = ((!context.isHdr) ? RenderTextureFormat.Default : RenderTextureFormat.DefaultHDR); + int tempRT = Uniforms._TempRT; + cb.GetTemporaryRT(tempRT, context.width, context.height, 0, FilterMode.Bilinear, format); + cb.Blit(BuiltinRenderTextureType.CameraTarget, tempRT, mat, 0); + cb.SetGlobalTexture(Uniforms._MainTex, tempRT); + cb.Blit(tempRT, BuiltinRenderTextureType.CameraTarget, material, 6); + cb.ReleaseTemporaryRT(tempRT); + } + cb.ReleaseTemporaryRT(occlusionTexture); + } +} diff --git a/UnityEngine.PostProcessing/AmbientOcclusionModel.cs b/UnityEngine.PostProcessing/AmbientOcclusionModel.cs new file mode 100644 index 0000000..c8fa258 --- /dev/null +++ b/UnityEngine.PostProcessing/AmbientOcclusionModel.cs @@ -0,0 +1,78 @@ +using System; + +namespace UnityEngine.PostProcessing; + +[Serializable] +public class AmbientOcclusionModel : PostProcessingModel +{ + public enum SampleCount + { + Lowest = 3, + Low = 6, + Medium = 10, + High = 16 + } + + [Serializable] + public struct Settings + { + [Range(0f, 4f)] + [Tooltip("Degree of darkness produced by the effect.")] + public float intensity; + + [Min(0.0001f)] + [Tooltip("Radius of sample points, which affects extent of darkened areas.")] + public float radius; + + [Tooltip("Number of sample points, which affects quality and performance.")] + public SampleCount sampleCount; + + [Tooltip("Halves the resolution of the effect to increase performance at the cost of visual quality.")] + public bool downsampling; + + [Tooltip("Forces compatibility with Forward rendered objects when working with the Deferred rendering path.")] + public bool forceForwardCompatibility; + + [Tooltip("Enables the ambient-only mode in that the effect only affects ambient lighting. This mode is only available with the Deferred rendering path and HDR rendering.")] + public bool ambientOnly; + + [Tooltip("Toggles the use of a higher precision depth texture with the forward rendering path (may impact performances). Has no effect with the deferred rendering path.")] + public bool highPrecision; + + public static Settings defaultSettings + { + get + { + Settings result = default(Settings); + result.intensity = 1f; + result.radius = 0.3f; + result.sampleCount = SampleCount.Medium; + result.downsampling = true; + result.forceForwardCompatibility = false; + result.ambientOnly = false; + result.highPrecision = false; + return result; + } + } + } + + [SerializeField] + private Settings m_Settings = Settings.defaultSettings; + + public Settings settings + { + get + { + return m_Settings; + } + set + { + m_Settings = value; + } + } + + public override void Reset() + { + m_Settings = Settings.defaultSettings; + } +} diff --git a/UnityEngine.PostProcessing/AntialiasingModel.cs b/UnityEngine.PostProcessing/AntialiasingModel.cs new file mode 100644 index 0000000..d5bda1d --- /dev/null +++ b/UnityEngine.PostProcessing/AntialiasingModel.cs @@ -0,0 +1,222 @@ +using System; + +namespace UnityEngine.PostProcessing; + +[Serializable] +public class AntialiasingModel : PostProcessingModel +{ + public enum Method + { + Fxaa, + Taa + } + + public enum FxaaPreset + { + ExtremePerformance, + Performance, + Default, + Quality, + ExtremeQuality + } + + [Serializable] + public struct FxaaQualitySettings + { + [Tooltip("The amount of desired sub-pixel aliasing removal. Effects the sharpeness of the output.")] + [Range(0f, 1f)] + public float subpixelAliasingRemovalAmount; + + [Tooltip("The minimum amount of local contrast required to qualify a region as containing an edge.")] + [Range(0.063f, 0.333f)] + public float edgeDetectionThreshold; + + [Tooltip("Local contrast adaptation value to disallow the algorithm from executing on the darker regions.")] + [Range(0f, 0.0833f)] + public float minimumRequiredLuminance; + + public static FxaaQualitySettings[] presets = new FxaaQualitySettings[5] + { + new FxaaQualitySettings + { + subpixelAliasingRemovalAmount = 0f, + edgeDetectionThreshold = 0.333f, + minimumRequiredLuminance = 0.0833f + }, + new FxaaQualitySettings + { + subpixelAliasingRemovalAmount = 0.25f, + edgeDetectionThreshold = 0.25f, + minimumRequiredLuminance = 0.0833f + }, + new FxaaQualitySettings + { + subpixelAliasingRemovalAmount = 0.75f, + edgeDetectionThreshold = 0.166f, + minimumRequiredLuminance = 0.0833f + }, + new FxaaQualitySettings + { + subpixelAliasingRemovalAmount = 1f, + edgeDetectionThreshold = 0.125f, + minimumRequiredLuminance = 0.0625f + }, + new FxaaQualitySettings + { + subpixelAliasingRemovalAmount = 1f, + edgeDetectionThreshold = 0.063f, + minimumRequiredLuminance = 0.0312f + } + }; + } + + [Serializable] + public struct FxaaConsoleSettings + { + [Tooltip("The amount of spread applied to the sampling coordinates while sampling for subpixel information.")] + [Range(0.33f, 0.5f)] + public float subpixelSpreadAmount; + + [Tooltip("This value dictates how sharp the edges in the image are kept; a higher value implies sharper edges.")] + [Range(2f, 8f)] + public float edgeSharpnessAmount; + + [Tooltip("The minimum amount of local contrast required to qualify a region as containing an edge.")] + [Range(0.125f, 0.25f)] + public float edgeDetectionThreshold; + + [Tooltip("Local contrast adaptation value to disallow the algorithm from executing on the darker regions.")] + [Range(0.04f, 0.06f)] + public float minimumRequiredLuminance; + + public static FxaaConsoleSettings[] presets = new FxaaConsoleSettings[5] + { + new FxaaConsoleSettings + { + subpixelSpreadAmount = 0.33f, + edgeSharpnessAmount = 8f, + edgeDetectionThreshold = 0.25f, + minimumRequiredLuminance = 0.06f + }, + new FxaaConsoleSettings + { + subpixelSpreadAmount = 0.33f, + edgeSharpnessAmount = 8f, + edgeDetectionThreshold = 0.125f, + minimumRequiredLuminance = 0.06f + }, + new FxaaConsoleSettings + { + subpixelSpreadAmount = 0.5f, + edgeSharpnessAmount = 8f, + edgeDetectionThreshold = 0.125f, + minimumRequiredLuminance = 0.05f + }, + new FxaaConsoleSettings + { + subpixelSpreadAmount = 0.5f, + edgeSharpnessAmount = 4f, + edgeDetectionThreshold = 0.125f, + minimumRequiredLuminance = 0.04f + }, + new FxaaConsoleSettings + { + subpixelSpreadAmount = 0.5f, + edgeSharpnessAmount = 2f, + edgeDetectionThreshold = 0.125f, + minimumRequiredLuminance = 0.04f + } + }; + } + + [Serializable] + public struct FxaaSettings + { + public FxaaPreset preset; + + public static FxaaSettings defaultSettings + { + get + { + FxaaSettings result = default(FxaaSettings); + result.preset = FxaaPreset.Default; + return result; + } + } + } + + [Serializable] + public struct TaaSettings + { + [Tooltip("The diameter (in texels) inside which jitter samples are spread. Smaller values result in crisper but more aliased output, while larger values result in more stable but blurrier output.")] + [Range(0.1f, 1f)] + public float jitterSpread; + + [Tooltip("Controls the amount of sharpening applied to the color buffer.")] + [Range(0f, 3f)] + public float sharpen; + + [Tooltip("The blend coefficient for a stationary fragment. Controls the percentage of history sample blended into the final color.")] + [Range(0f, 0.99f)] + public float stationaryBlending; + + [Tooltip("The blend coefficient for a fragment with significant motion. Controls the percentage of history sample blended into the final color.")] + [Range(0f, 0.99f)] + public float motionBlending; + + public static TaaSettings defaultSettings + { + get + { + TaaSettings result = default(TaaSettings); + result.jitterSpread = 0.75f; + result.sharpen = 0.3f; + result.stationaryBlending = 0.95f; + result.motionBlending = 0.85f; + return result; + } + } + } + + [Serializable] + public struct Settings + { + public Method method; + + public FxaaSettings fxaaSettings; + + public TaaSettings taaSettings; + + public static Settings defaultSettings + { + get + { + Settings result = default(Settings); + result.method = Method.Fxaa; + result.fxaaSettings = FxaaSettings.defaultSettings; + result.taaSettings = TaaSettings.defaultSettings; + return result; + } + } + } + + [SerializeField] + private Settings m_Settings = Settings.defaultSettings; + + public Settings settings + { + get + { + return m_Settings; + } + set + { + m_Settings = value; + } + } + + public override void Reset() + { + m_Settings = Settings.defaultSettings; + } +} diff --git a/UnityEngine.PostProcessing/BloomComponent.cs b/UnityEngine.PostProcessing/BloomComponent.cs new file mode 100644 index 0000000..aeec498 --- /dev/null +++ b/UnityEngine.PostProcessing/BloomComponent.cs @@ -0,0 +1,106 @@ +namespace UnityEngine.PostProcessing; + +public sealed class BloomComponent : PostProcessingComponentRenderTexture<BloomModel> +{ + private static class Uniforms + { + internal static readonly int _AutoExposure = Shader.PropertyToID("_AutoExposure"); + + internal static readonly int _Threshold = Shader.PropertyToID("_Threshold"); + + internal static readonly int _Curve = Shader.PropertyToID("_Curve"); + + internal static readonly int _PrefilterOffs = Shader.PropertyToID("_PrefilterOffs"); + + internal static readonly int _SampleScale = Shader.PropertyToID("_SampleScale"); + + internal static readonly int _BaseTex = Shader.PropertyToID("_BaseTex"); + + internal static readonly int _BloomTex = Shader.PropertyToID("_BloomTex"); + + internal static readonly int _Bloom_Settings = Shader.PropertyToID("_Bloom_Settings"); + + internal static readonly int _Bloom_DirtTex = Shader.PropertyToID("_Bloom_DirtTex"); + + internal static readonly int _Bloom_DirtIntensity = Shader.PropertyToID("_Bloom_DirtIntensity"); + } + + private const int k_MaxPyramidBlurLevel = 16; + + private readonly RenderTexture[] m_BlurBuffer1 = new RenderTexture[16]; + + private readonly RenderTexture[] m_BlurBuffer2 = new RenderTexture[16]; + + public override bool active => base.model.enabled && base.model.settings.bloom.intensity > 0f && !context.interrupted; + + public void Prepare(RenderTexture source, Material uberMaterial, Texture autoExposure) + { + BloomModel.BloomSettings bloom = base.model.settings.bloom; + BloomModel.LensDirtSettings lensDirt = base.model.settings.lensDirt; + Material material = context.materialFactory.Get("Hidden/Post FX/Bloom"); + material.shaderKeywords = null; + material.SetTexture(Uniforms._AutoExposure, autoExposure); + int width = context.width / 2; + int num = context.height / 2; + RenderTextureFormat format = ((!Application.isMobilePlatform) ? RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default); + float num2 = Mathf.Log(num, 2f) + bloom.radius - 8f; + int num3 = (int)num2; + int num4 = Mathf.Clamp(num3, 1, 16); + float thresholdLinear = bloom.thresholdLinear; + material.SetFloat(Uniforms._Threshold, thresholdLinear); + float num5 = thresholdLinear * bloom.softKnee + 1E-05f; + material.SetVector(value: new Vector3(thresholdLinear - num5, num5 * 2f, 0.25f / num5), nameID: Uniforms._Curve); + material.SetFloat(Uniforms._PrefilterOffs, (!bloom.antiFlicker) ? 0f : (-0.5f)); + float num6 = 0.5f + num2 - (float)num3; + material.SetFloat(Uniforms._SampleScale, num6); + if (bloom.antiFlicker) + { + material.EnableKeyword("ANTI_FLICKER"); + } + RenderTexture renderTexture = context.renderTextureFactory.Get(width, num, 0, format); + Graphics.Blit(source, renderTexture, material, 0); + RenderTexture renderTexture2 = renderTexture; + for (int i = 0; i < num4; i++) + { + m_BlurBuffer1[i] = context.renderTextureFactory.Get(renderTexture2.width / 2, renderTexture2.height / 2, 0, format); + int pass = ((i == 0) ? 1 : 2); + Graphics.Blit(renderTexture2, m_BlurBuffer1[i], material, pass); + renderTexture2 = m_BlurBuffer1[i]; + } + for (int num7 = num4 - 2; num7 >= 0; num7--) + { + RenderTexture renderTexture3 = m_BlurBuffer1[num7]; + material.SetTexture(Uniforms._BaseTex, renderTexture3); + m_BlurBuffer2[num7] = context.renderTextureFactory.Get(renderTexture3.width, renderTexture3.height, 0, format); + Graphics.Blit(renderTexture2, m_BlurBuffer2[num7], material, 3); + renderTexture2 = m_BlurBuffer2[num7]; + } + RenderTexture renderTexture4 = renderTexture2; + for (int j = 0; j < 16; j++) + { + if (m_BlurBuffer1[j] != null) + { + context.renderTextureFactory.Release(m_BlurBuffer1[j]); + } + if (m_BlurBuffer2[j] != null && m_BlurBuffer2[j] != renderTexture4) + { + context.renderTextureFactory.Release(m_BlurBuffer2[j]); + } + m_BlurBuffer1[j] = null; + m_BlurBuffer2[j] = null; + } + context.renderTextureFactory.Release(renderTexture); + uberMaterial.SetTexture(Uniforms._BloomTex, renderTexture4); + uberMaterial.SetVector(Uniforms._Bloom_Settings, new Vector2(num6, bloom.intensity)); + if (lensDirt.intensity > 0f && lensDirt.texture != null) + { + uberMaterial.SetTexture(Uniforms._Bloom_DirtTex, lensDirt.texture); + uberMaterial.SetFloat(Uniforms._Bloom_DirtIntensity, lensDirt.intensity); + uberMaterial.EnableKeyword("BLOOM_LENS_DIRT"); + } + else + { + uberMaterial.EnableKeyword("BLOOM"); + } + } +} diff --git a/UnityEngine.PostProcessing/BloomModel.cs b/UnityEngine.PostProcessing/BloomModel.cs new file mode 100644 index 0000000..0569d62 --- /dev/null +++ b/UnityEngine.PostProcessing/BloomModel.cs @@ -0,0 +1,117 @@ +using System; + +namespace UnityEngine.PostProcessing; + +[Serializable] +public class BloomModel : PostProcessingModel +{ + [Serializable] + public struct BloomSettings + { + [Min(0f)] + [Tooltip("Strength of the bloom filter.")] + public float intensity; + + [Min(0f)] + [Tooltip("Filters out pixels under this level of brightness.")] + public float threshold; + + [Range(0f, 1f)] + [Tooltip("Makes transition between under/over-threshold gradual (0 = hard threshold, 1 = soft threshold).")] + public float softKnee; + + [Range(1f, 7f)] + [Tooltip("Changes extent of veiling effects in a screen resolution-independent fashion.")] + public float radius; + + [Tooltip("Reduces flashing noise with an additional filter.")] + public bool antiFlicker; + + public float thresholdLinear + { + get + { + return Mathf.GammaToLinearSpace(threshold); + } + set + { + threshold = Mathf.LinearToGammaSpace(value); + } + } + + public static BloomSettings defaultSettings + { + get + { + BloomSettings result = default(BloomSettings); + result.intensity = 0.5f; + result.threshold = 1.1f; + result.softKnee = 0.5f; + result.radius = 4f; + result.antiFlicker = false; + return result; + } + } + } + + [Serializable] + public struct LensDirtSettings + { + [Tooltip("Dirtiness texture to add smudges or dust to the lens.")] + public Texture texture; + + [Min(0f)] + [Tooltip("Amount of lens dirtiness.")] + public float intensity; + + public static LensDirtSettings defaultSettings + { + get + { + LensDirtSettings result = default(LensDirtSettings); + result.texture = null; + result.intensity = 3f; + return result; + } + } + } + + [Serializable] + public struct Settings + { + public BloomSettings bloom; + + public LensDirtSettings lensDirt; + + public static Settings defaultSettings + { + get + { + Settings result = default(Settings); + result.bloom = BloomSettings.defaultSettings; + result.lensDirt = LensDirtSettings.defaultSettings; + return result; + } + } + } + + [SerializeField] + private Settings m_Settings = Settings.defaultSettings; + + public Settings settings + { + get + { + return m_Settings; + } + set + { + m_Settings = value; + } + } + + public override void Reset() + { + m_Settings = Settings.defaultSettings; + } +} diff --git a/UnityEngine.PostProcessing/BuiltinDebugViewsComponent.cs b/UnityEngine.PostProcessing/BuiltinDebugViewsComponent.cs new file mode 100644 index 0000000..a1a6d44 --- /dev/null +++ b/UnityEngine.PostProcessing/BuiltinDebugViewsComponent.cs @@ -0,0 +1,223 @@ +using System.Collections.Generic; +using UnityEngine.Rendering; + +namespace UnityEngine.PostProcessing; + +public sealed class BuiltinDebugViewsComponent : PostProcessingComponentCommandBuffer<BuiltinDebugViewsModel> +{ + private static class Uniforms + { + internal static readonly int _DepthScale = Shader.PropertyToID("_DepthScale"); + + internal static readonly int _TempRT = Shader.PropertyToID("_TempRT"); + + internal static readonly int _Opacity = Shader.PropertyToID("_Opacity"); + + internal static readonly int _MainTex = Shader.PropertyToID("_MainTex"); + + internal static readonly int _TempRT2 = Shader.PropertyToID("_TempRT2"); + + internal static readonly int _Amplitude = Shader.PropertyToID("_Amplitude"); + + internal static readonly int _Scale = Shader.PropertyToID("_Scale"); + } + + private enum Pass + { + Depth, + Normals, + MovecOpacity, + MovecImaging, + MovecArrows + } + + private class ArrowArray + { + public Mesh mesh { get; private set; } + + public int columnCount { get; private set; } + + public int rowCount { get; private set; } + + public void BuildMesh(int columns, int rows) + { + Vector3[] array = new Vector3[6] + { + new Vector3(0f, 0f, 0f), + new Vector3(0f, 1f, 0f), + new Vector3(0f, 1f, 0f), + new Vector3(-1f, 1f, 0f), + new Vector3(0f, 1f, 0f), + new Vector3(1f, 1f, 0f) + }; + int num = 6 * columns * rows; + List<Vector3> list = new List<Vector3>(num); + List<Vector2> list2 = new List<Vector2>(num); + for (int i = 0; i < rows; i++) + { + for (int j = 0; j < columns; j++) + { + Vector2 item = new Vector2((0.5f + (float)j) / (float)columns, (0.5f + (float)i) / (float)rows); + for (int k = 0; k < 6; k++) + { + list.Add(array[k]); + list2.Add(item); + } + } + } + int[] array2 = new int[num]; + for (int l = 0; l < num; l++) + { + array2[l] = l; + } + mesh = new Mesh + { + hideFlags = HideFlags.DontSave + }; + mesh.SetVertices(list); + mesh.SetUVs(0, list2); + mesh.SetIndices(array2, MeshTopology.Lines, 0); + mesh.UploadMeshData(markNoLogerReadable: true); + columnCount = columns; + rowCount = rows; + } + + public void Release() + { + GraphicsUtils.Destroy(mesh); + mesh = null; + } + } + + private const string k_ShaderString = "Hidden/Post FX/Builtin Debug Views"; + + private ArrowArray m_Arrows; + + public override bool active => base.model.IsModeActive(BuiltinDebugViewsModel.Mode.Depth) || base.model.IsModeActive(BuiltinDebugViewsModel.Mode.Normals) || base.model.IsModeActive(BuiltinDebugViewsModel.Mode.MotionVectors); + + public override DepthTextureMode GetCameraFlags() + { + BuiltinDebugViewsModel.Mode mode = base.model.settings.mode; + DepthTextureMode depthTextureMode = DepthTextureMode.None; + switch (mode) + { + case BuiltinDebugViewsModel.Mode.Normals: + depthTextureMode |= DepthTextureMode.DepthNormals; + break; + case BuiltinDebugViewsModel.Mode.MotionVectors: + depthTextureMode |= DepthTextureMode.Depth | DepthTextureMode.MotionVectors; + break; + case BuiltinDebugViewsModel.Mode.Depth: + depthTextureMode |= DepthTextureMode.Depth; + break; + } + return depthTextureMode; + } + + public override CameraEvent GetCameraEvent() + { + return (base.model.settings.mode != BuiltinDebugViewsModel.Mode.MotionVectors) ? CameraEvent.BeforeImageEffectsOpaque : CameraEvent.BeforeImageEffects; + } + + public override string GetName() + { + return "Builtin Debug Views"; + } + + public override void PopulateCommandBuffer(CommandBuffer cb) + { + BuiltinDebugViewsModel.Settings settings = base.model.settings; + Material material = context.materialFactory.Get("Hidden/Post FX/Builtin Debug Views"); + material.shaderKeywords = null; + if (context.isGBufferAvailable) + { + material.EnableKeyword("SOURCE_GBUFFER"); + } + switch (settings.mode) + { + case BuiltinDebugViewsModel.Mode.Depth: + DepthPass(cb); + break; + case BuiltinDebugViewsModel.Mode.Normals: + DepthNormalsPass(cb); + break; + case BuiltinDebugViewsModel.Mode.MotionVectors: + MotionVectorsPass(cb); + break; + } + context.Interrupt(); + } + + private void DepthPass(CommandBuffer cb) + { + Material mat = context.materialFactory.Get("Hidden/Post FX/Builtin Debug Views"); + BuiltinDebugViewsModel.DepthSettings depth = base.model.settings.depth; + cb.SetGlobalFloat(Uniforms._DepthScale, 1f / depth.scale); + cb.Blit(null, BuiltinRenderTextureType.CameraTarget, mat, 0); + } + + private void DepthNormalsPass(CommandBuffer cb) + { + Material mat = context.materialFactory.Get("Hidden/Post FX/Builtin Debug Views"); + cb.Blit(null, BuiltinRenderTextureType.CameraTarget, mat, 1); + } + + private void MotionVectorsPass(CommandBuffer cb) + { + Material material = context.materialFactory.Get("Hidden/Post FX/Builtin Debug Views"); + BuiltinDebugViewsModel.MotionVectorsSettings motionVectors = base.model.settings.motionVectors; + int num = Uniforms._TempRT; + cb.GetTemporaryRT(num, context.width, context.height, 0, FilterMode.Bilinear); + cb.SetGlobalFloat(Uniforms._Opacity, motionVectors.sourceOpacity); + cb.SetGlobalTexture(Uniforms._MainTex, BuiltinRenderTextureType.CameraTarget); + cb.Blit(BuiltinRenderTextureType.CameraTarget, num, material, 2); + if (motionVectors.motionImageOpacity > 0f && motionVectors.motionImageAmplitude > 0f) + { + int tempRT = Uniforms._TempRT2; + cb.GetTemporaryRT(tempRT, context.width, context.height, 0, FilterMode.Bilinear); + cb.SetGlobalFloat(Uniforms._Opacity, motionVectors.motionImageOpacity); + cb.SetGlobalFloat(Uniforms._Amplitude, motionVectors.motionImageAmplitude); + cb.SetGlobalTexture(Uniforms._MainTex, num); + cb.Blit(num, tempRT, material, 3); + cb.ReleaseTemporaryRT(num); + num = tempRT; + } + if (motionVectors.motionVectorsOpacity > 0f && motionVectors.motionVectorsAmplitude > 0f) + { + PrepareArrows(); + float num2 = 1f / (float)motionVectors.motionVectorsResolution; + float x = num2 * (float)context.height / (float)context.width; + cb.SetGlobalVector(Uniforms._Scale, new Vector2(x, num2)); + cb.SetGlobalFloat(Uniforms._Opacity, motionVectors.motionVectorsOpacity); + cb.SetGlobalFloat(Uniforms._Amplitude, motionVectors.motionVectorsAmplitude); + cb.DrawMesh(m_Arrows.mesh, Matrix4x4.identity, material, 0, 4); + } + cb.SetGlobalTexture(Uniforms._MainTex, num); + cb.Blit(num, BuiltinRenderTextureType.CameraTarget); + cb.ReleaseTemporaryRT(num); + } + + private void PrepareArrows() + { + int motionVectorsResolution = base.model.settings.motionVectors.motionVectorsResolution; + int num = motionVectorsResolution * Screen.width / Screen.height; + if (m_Arrows == null) + { + m_Arrows = new ArrowArray(); + } + if (m_Arrows.columnCount != num || m_Arrows.rowCount != motionVectorsResolution) + { + m_Arrows.Release(); + m_Arrows.BuildMesh(num, motionVectorsResolution); + } + } + + public override void OnDisable() + { + if (m_Arrows != null) + { + m_Arrows.Release(); + } + m_Arrows = null; + } +} diff --git a/UnityEngine.PostProcessing/BuiltinDebugViewsModel.cs b/UnityEngine.PostProcessing/BuiltinDebugViewsModel.cs new file mode 100644 index 0000000..7a6f53c --- /dev/null +++ b/UnityEngine.PostProcessing/BuiltinDebugViewsModel.cs @@ -0,0 +1,131 @@ +using System; + +namespace UnityEngine.PostProcessing; + +[Serializable] +public class BuiltinDebugViewsModel : PostProcessingModel +{ + [Serializable] + public struct DepthSettings + { + [Range(0f, 1f)] + [Tooltip("Scales the camera far plane before displaying the depth map.")] + public float scale; + + public static DepthSettings defaultSettings + { + get + { + DepthSettings result = default(DepthSettings); + result.scale = 1f; + return result; + } + } + } + + [Serializable] + public struct MotionVectorsSettings + { + [Range(0f, 1f)] + [Tooltip("Opacity of the source render.")] + public float sourceOpacity; + + [Range(0f, 1f)] + [Tooltip("Opacity of the per-pixel motion vector colors.")] + public float motionImageOpacity; + + [Min(0f)] + [Tooltip("Because motion vectors are mainly very small vectors, you can use this setting to make them more visible.")] + public float motionImageAmplitude; + + [Range(0f, 1f)] + [Tooltip("Opacity for the motion vector arrows.")] + public float motionVectorsOpacity; + + [Range(8f, 64f)] + [Tooltip("The arrow density on screen.")] + public int motionVectorsResolution; + + [Min(0f)] + [Tooltip("Tweaks the arrows length.")] + public float motionVectorsAmplitude; + + public static MotionVectorsSettings defaultSettings + { + get + { + MotionVectorsSettings result = default(MotionVectorsSettings); + result.sourceOpacity = 1f; + result.motionImageOpacity = 0f; + result.motionImageAmplitude = 16f; + result.motionVectorsOpacity = 1f; + result.motionVectorsResolution = 24; + result.motionVectorsAmplitude = 64f; + return result; + } + } + } + + public enum Mode + { + None, + Depth, + Normals, + MotionVectors, + AmbientOcclusion, + EyeAdaptation, + FocusPlane, + PreGradingLog, + LogLut, + UserLut + } + + [Serializable] + public struct Settings + { + public Mode mode; + + public DepthSettings depth; + + public MotionVectorsSettings motionVectors; + + public static Settings defaultSettings + { + get + { + Settings result = default(Settings); + result.mode = Mode.None; + result.depth = DepthSettings.defaultSettings; + result.motionVectors = MotionVectorsSettings.defaultSettings; + return result; + } + } + } + + [SerializeField] + private Settings m_Settings = Settings.defaultSettings; + + public Settings settings + { + get + { + return m_Settings; + } + set + { + m_Settings = value; + } + } + + public bool willInterrupt => !IsModeActive(Mode.None) && !IsModeActive(Mode.EyeAdaptation) && !IsModeActive(Mode.PreGradingLog) && !IsModeActive(Mode.LogLut) && !IsModeActive(Mode.UserLut); + + public override void Reset() + { + settings = Settings.defaultSettings; + } + + public bool IsModeActive(Mode mode) + { + return m_Settings.mode == mode; + } +} diff --git a/UnityEngine.PostProcessing/ChromaticAberrationComponent.cs b/UnityEngine.PostProcessing/ChromaticAberrationComponent.cs new file mode 100644 index 0000000..1e5b82a --- /dev/null +++ b/UnityEngine.PostProcessing/ChromaticAberrationComponent.cs @@ -0,0 +1,53 @@ +namespace UnityEngine.PostProcessing; + +public sealed class ChromaticAberrationComponent : PostProcessingComponentRenderTexture<ChromaticAberrationModel> +{ + private static class Uniforms + { + internal static readonly int _ChromaticAberration_Amount = Shader.PropertyToID("_ChromaticAberration_Amount"); + + internal static readonly int _ChromaticAberration_Spectrum = Shader.PropertyToID("_ChromaticAberration_Spectrum"); + } + + private Texture2D m_SpectrumLut; + + public override bool active => base.model.enabled && base.model.settings.intensity > 0f && !context.interrupted; + + public override void OnDisable() + { + GraphicsUtils.Destroy(m_SpectrumLut); + m_SpectrumLut = null; + } + + public override void Prepare(Material uberMaterial) + { + ChromaticAberrationModel.Settings settings = base.model.settings; + Texture2D texture2D = settings.spectralTexture; + if (texture2D == null) + { + if (m_SpectrumLut == null) + { + m_SpectrumLut = new Texture2D(3, 1, TextureFormat.RGB24, mipmap: false) + { + name = "Chromatic Aberration Spectrum Lookup", + filterMode = FilterMode.Bilinear, + wrapMode = TextureWrapMode.Clamp, + anisoLevel = 0, + hideFlags = HideFlags.DontSave + }; + Color[] pixels = new Color[3] + { + new Color(1f, 0f, 0f), + new Color(0f, 1f, 0f), + new Color(0f, 0f, 1f) + }; + m_SpectrumLut.SetPixels(pixels); + m_SpectrumLut.Apply(); + } + texture2D = m_SpectrumLut; + } + uberMaterial.EnableKeyword("CHROMATIC_ABERRATION"); + uberMaterial.SetFloat(Uniforms._ChromaticAberration_Amount, settings.intensity * 0.03f); + uberMaterial.SetTexture(Uniforms._ChromaticAberration_Spectrum, texture2D); + } +} diff --git a/UnityEngine.PostProcessing/ChromaticAberrationModel.cs b/UnityEngine.PostProcessing/ChromaticAberrationModel.cs new file mode 100644 index 0000000..a648f9f --- /dev/null +++ b/UnityEngine.PostProcessing/ChromaticAberrationModel.cs @@ -0,0 +1,49 @@ +using System; + +namespace UnityEngine.PostProcessing; + +[Serializable] +public class ChromaticAberrationModel : PostProcessingModel +{ + [Serializable] + public struct Settings + { + [Tooltip("Shift the hue of chromatic aberrations.")] + public Texture2D spectralTexture; + + [Range(0f, 1f)] + [Tooltip("Amount of tangential distortion.")] + public float intensity; + + public static Settings defaultSettings + { + get + { + Settings result = default(Settings); + result.spectralTexture = null; + result.intensity = 0.1f; + return result; + } + } + } + + [SerializeField] + private Settings m_Settings = Settings.defaultSettings; + + public Settings settings + { + get + { + return m_Settings; + } + set + { + m_Settings = value; + } + } + + public override void Reset() + { + m_Settings = Settings.defaultSettings; + } +} diff --git a/UnityEngine.PostProcessing/ColorGradingComponent.cs b/UnityEngine.PostProcessing/ColorGradingComponent.cs new file mode 100644 index 0000000..7d7c65a --- /dev/null +++ b/UnityEngine.PostProcessing/ColorGradingComponent.cs @@ -0,0 +1,341 @@ +namespace UnityEngine.PostProcessing; + +public sealed class ColorGradingComponent : PostProcessingComponentRenderTexture<ColorGradingModel> +{ + private static class Uniforms + { + internal static readonly int _LutParams = Shader.PropertyToID("_LutParams"); + + internal static readonly int _NeutralTonemapperParams1 = Shader.PropertyToID("_NeutralTonemapperParams1"); + + internal static readonly int _NeutralTonemapperParams2 = Shader.PropertyToID("_NeutralTonemapperParams2"); + + internal static readonly int _HueShift = Shader.PropertyToID("_HueShift"); + + internal static readonly int _Saturation = Shader.PropertyToID("_Saturation"); + + internal static readonly int _Contrast = Shader.PropertyToID("_Contrast"); + + internal static readonly int _Balance = Shader.PropertyToID("_Balance"); + + internal static readonly int _Lift = Shader.PropertyToID("_Lift"); + + internal static readonly int _InvGamma = Shader.PropertyToID("_InvGamma"); + + internal static readonly int _Gain = Shader.PropertyToID("_Gain"); + + internal static readonly int _Slope = Shader.PropertyToID("_Slope"); + + internal static readonly int _Power = Shader.PropertyToID("_Power"); + + internal static readonly int _Offset = Shader.PropertyToID("_Offset"); + + internal static readonly int _ChannelMixerRed = Shader.PropertyToID("_ChannelMixerRed"); + + internal static readonly int _ChannelMixerGreen = Shader.PropertyToID("_ChannelMixerGreen"); + + internal static readonly int _ChannelMixerBlue = Shader.PropertyToID("_ChannelMixerBlue"); + + internal static readonly int _Curves = Shader.PropertyToID("_Curves"); + + internal static readonly int _LogLut = Shader.PropertyToID("_LogLut"); + + internal static readonly int _LogLut_Params = Shader.PropertyToID("_LogLut_Params"); + + internal static readonly int _ExposureEV = Shader.PropertyToID("_ExposureEV"); + } + + private const int k_InternalLogLutSize = 32; + + private const int k_CurvePrecision = 128; + + private const float k_CurveStep = 1f / 128f; + + private Texture2D m_GradingCurves; + + private Color[] m_pixels = new Color[256]; + + public override bool active => base.model.enabled && !context.interrupted; + + private float StandardIlluminantY(float x) + { + return 2.87f * x - 3f * x * x - 0.27509508f; + } + + private Vector3 CIExyToLMS(float x, float y) + { + float num = 1f; + float num2 = num * x / y; + float num3 = num * (1f - x - y) / y; + float x2 = 0.7328f * num2 + 0.4296f * num - 0.1624f * num3; + float y2 = -0.7036f * num2 + 1.6975f * num + 0.0061f * num3; + float z = 0.003f * num2 + 0.0136f * num + 0.9834f * num3; + return new Vector3(x2, y2, z); + } + + private Vector3 CalculateColorBalance(float temperature, float tint) + { + float num = temperature / 55f; + float num2 = tint / 55f; + float x = 0.31271f - num * ((!(num < 0f)) ? 0.05f : 0.1f); + float y = StandardIlluminantY(x) + num2 * 0.05f; + Vector3 vector = new Vector3(0.949237f, 1.03542f, 1.08728f); + Vector3 vector2 = CIExyToLMS(x, y); + return new Vector3(vector.x / vector2.x, vector.y / vector2.y, vector.z / vector2.z); + } + + private static Color NormalizeColor(Color c) + { + float num = (c.r + c.g + c.b) / 3f; + if (Mathf.Approximately(num, 0f)) + { + return new Color(1f, 1f, 1f, c.a); + } + Color result = default(Color); + result.r = c.r / num; + result.g = c.g / num; + result.b = c.b / num; + result.a = c.a; + return result; + } + + private static Vector3 ClampVector(Vector3 v, float min, float max) + { + return new Vector3(Mathf.Clamp(v.x, min, max), Mathf.Clamp(v.y, min, max), Mathf.Clamp(v.z, min, max)); + } + + public static Vector3 GetLiftValue(Color lift) + { + Color color = NormalizeColor(lift); + float num = (color.r + color.g + color.b) / 3f; + float x = (color.r - num) * 0.1f + lift.a; + float y = (color.g - num) * 0.1f + lift.a; + float z = (color.b - num) * 0.1f + lift.a; + return ClampVector(new Vector3(x, y, z), -1f, 1f); + } + + public static Vector3 GetGammaValue(Color gamma) + { + Color color = NormalizeColor(gamma); + float num = (color.r + color.g + color.b) / 3f; + gamma.a *= ((!(gamma.a < 0f)) ? 5f : 0.8f); + float b = Mathf.Pow(2f, (color.r - num) * 0.5f) + gamma.a; + float b2 = Mathf.Pow(2f, (color.g - num) * 0.5f) + gamma.a; + float b3 = Mathf.Pow(2f, (color.b - num) * 0.5f) + gamma.a; + float x = 1f / Mathf.Max(0.01f, b); + float y = 1f / Mathf.Max(0.01f, b2); + float z = 1f / Mathf.Max(0.01f, b3); + return ClampVector(new Vector3(x, y, z), 0f, 5f); + } + + public static Vector3 GetGainValue(Color gain) + { + Color color = NormalizeColor(gain); + float num = (color.r + color.g + color.b) / 3f; + gain.a *= ((!(gain.a > 0f)) ? 1f : 3f); + float x = Mathf.Pow(2f, (color.r - num) * 0.5f) + gain.a; + float y = Mathf.Pow(2f, (color.g - num) * 0.5f) + gain.a; + float z = Mathf.Pow(2f, (color.b - num) * 0.5f) + gain.a; + return ClampVector(new Vector3(x, y, z), 0f, 4f); + } + + public static void CalculateLiftGammaGain(Color lift, Color gamma, Color gain, out Vector3 outLift, out Vector3 outGamma, out Vector3 outGain) + { + outLift = GetLiftValue(lift); + outGamma = GetGammaValue(gamma); + outGain = GetGainValue(gain); + } + + public static Vector3 GetSlopeValue(Color slope) + { + Color color = NormalizeColor(slope); + float num = (color.r + color.g + color.b) / 3f; + slope.a *= 0.5f; + float x = (color.r - num) * 0.1f + slope.a + 1f; + float y = (color.g - num) * 0.1f + slope.a + 1f; + float z = (color.b - num) * 0.1f + slope.a + 1f; + return ClampVector(new Vector3(x, y, z), 0f, 2f); + } + + public static Vector3 GetPowerValue(Color power) + { + Color color = NormalizeColor(power); + float num = (color.r + color.g + color.b) / 3f; + power.a *= 0.5f; + float b = (color.r - num) * 0.1f + power.a + 1f; + float b2 = (color.g - num) * 0.1f + power.a + 1f; + float b3 = (color.b - num) * 0.1f + power.a + 1f; + float x = 1f / Mathf.Max(0.01f, b); + float y = 1f / Mathf.Max(0.01f, b2); + float z = 1f / Mathf.Max(0.01f, b3); + return ClampVector(new Vector3(x, y, z), 0.5f, 2.5f); + } + + public static Vector3 GetOffsetValue(Color offset) + { + Color color = NormalizeColor(offset); + float num = (color.r + color.g + color.b) / 3f; + offset.a *= 0.5f; + float x = (color.r - num) * 0.05f + offset.a; + float y = (color.g - num) * 0.05f + offset.a; + float z = (color.b - num) * 0.05f + offset.a; + return ClampVector(new Vector3(x, y, z), -0.8f, 0.8f); + } + + public static void CalculateSlopePowerOffset(Color slope, Color power, Color offset, out Vector3 outSlope, out Vector3 outPower, out Vector3 outOffset) + { + outSlope = GetSlopeValue(slope); + outPower = GetPowerValue(power); + outOffset = GetOffsetValue(offset); + } + + private TextureFormat GetCurveFormat() + { + if (SystemInfo.SupportsTextureFormat(TextureFormat.RGBAHalf)) + { + return TextureFormat.RGBAHalf; + } + return TextureFormat.RGBA32; + } + + private Texture2D GetCurveTexture() + { + if (m_GradingCurves == null) + { + m_GradingCurves = new Texture2D(128, 2, GetCurveFormat(), mipmap: false, linear: true) + { + name = "Internal Curves Texture", + hideFlags = HideFlags.DontSave, + anisoLevel = 0, + wrapMode = TextureWrapMode.Clamp, + filterMode = FilterMode.Bilinear + }; + } + ColorGradingModel.CurvesSettings curves = base.model.settings.curves; + curves.hueVShue.Cache(); + curves.hueVSsat.Cache(); + for (int i = 0; i < 128; i++) + { + float t = (float)i * (1f / 128f); + float r = curves.hueVShue.Evaluate(t); + float g = curves.hueVSsat.Evaluate(t); + float b = curves.satVSsat.Evaluate(t); + float a = curves.lumVSsat.Evaluate(t); + ref Color reference = ref m_pixels[i]; + reference = new Color(r, g, b, a); + float a2 = curves.master.Evaluate(t); + float r2 = curves.red.Evaluate(t); + float g2 = curves.green.Evaluate(t); + float b2 = curves.blue.Evaluate(t); + ref Color reference2 = ref m_pixels[i + 128]; + reference2 = new Color(r2, g2, b2, a2); + } + m_GradingCurves.SetPixels(m_pixels); + m_GradingCurves.Apply(updateMipmaps: false, makeNoLongerReadable: false); + return m_GradingCurves; + } + + private bool IsLogLutValid(RenderTexture lut) + { + return lut != null && lut.IsCreated() && lut.height == 32; + } + + private RenderTextureFormat GetLutFormat() + { + if (SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf)) + { + return RenderTextureFormat.ARGBHalf; + } + return RenderTextureFormat.ARGB32; + } + + private void GenerateLut() + { + ColorGradingModel.Settings settings = base.model.settings; + if (!IsLogLutValid(base.model.bakedLut)) + { + GraphicsUtils.Destroy(base.model.bakedLut); + base.model.bakedLut = new RenderTexture(1024, 32, 0, GetLutFormat()) + { + name = "Color Grading Log LUT", + hideFlags = HideFlags.DontSave, + filterMode = FilterMode.Bilinear, + wrapMode = TextureWrapMode.Clamp, + anisoLevel = 0 + }; + } + Material material = context.materialFactory.Get("Hidden/Post FX/Lut Generator"); + material.SetVector(Uniforms._LutParams, new Vector4(32f, 0.00048828125f, 1f / 64f, 1.032258f)); + material.shaderKeywords = null; + ColorGradingModel.TonemappingSettings tonemapping = settings.tonemapping; + switch (tonemapping.tonemapper) + { + case ColorGradingModel.Tonemapper.Neutral: + { + material.EnableKeyword("TONEMAPPING_NEUTRAL"); + float num = tonemapping.neutralBlackIn * 20f + 1f; + float num2 = tonemapping.neutralBlackOut * 10f + 1f; + float num3 = tonemapping.neutralWhiteIn / 20f; + float num4 = 1f - tonemapping.neutralWhiteOut / 20f; + float t = num / num2; + float t2 = num3 / num4; + float y = Mathf.Max(0f, Mathf.LerpUnclamped(0.57f, 0.37f, t)); + float z = Mathf.LerpUnclamped(0.01f, 0.24f, t2); + float w = Mathf.Max(0f, Mathf.LerpUnclamped(0.02f, 0.2f, t)); + material.SetVector(Uniforms._NeutralTonemapperParams1, new Vector4(0.2f, y, z, w)); + material.SetVector(Uniforms._NeutralTonemapperParams2, new Vector4(0.02f, 0.3f, tonemapping.neutralWhiteLevel, tonemapping.neutralWhiteClip / 10f)); + break; + } + case ColorGradingModel.Tonemapper.ACES: + material.EnableKeyword("TONEMAPPING_FILMIC"); + break; + } + material.SetFloat(Uniforms._HueShift, settings.basic.hueShift / 360f); + material.SetFloat(Uniforms._Saturation, settings.basic.saturation); + material.SetFloat(Uniforms._Contrast, settings.basic.contrast); + material.SetVector(Uniforms._Balance, CalculateColorBalance(settings.basic.temperature, settings.basic.tint)); + CalculateLiftGammaGain(settings.colorWheels.linear.lift, settings.colorWheels.linear.gamma, settings.colorWheels.linear.gain, out var outLift, out var outGamma, out var outGain); + material.SetVector(Uniforms._Lift, outLift); + material.SetVector(Uniforms._InvGamma, outGamma); + material.SetVector(Uniforms._Gain, outGain); + CalculateSlopePowerOffset(settings.colorWheels.log.slope, settings.colorWheels.log.power, settings.colorWheels.log.offset, out var outSlope, out var outPower, out var outOffset); + material.SetVector(Uniforms._Slope, outSlope); + material.SetVector(Uniforms._Power, outPower); + material.SetVector(Uniforms._Offset, outOffset); + material.SetVector(Uniforms._ChannelMixerRed, settings.channelMixer.red); + material.SetVector(Uniforms._ChannelMixerGreen, settings.channelMixer.green); + material.SetVector(Uniforms._ChannelMixerBlue, settings.channelMixer.blue); + material.SetTexture(Uniforms._Curves, GetCurveTexture()); + Graphics.Blit(null, base.model.bakedLut, material, 0); + } + + public override void Prepare(Material uberMaterial) + { + if (base.model.isDirty || !IsLogLutValid(base.model.bakedLut)) + { + GenerateLut(); + base.model.isDirty = false; + } + uberMaterial.EnableKeyword((!context.profile.debugViews.IsModeActive(BuiltinDebugViewsModel.Mode.PreGradingLog)) ? "COLOR_GRADING" : "COLOR_GRADING_LOG_VIEW"); + RenderTexture bakedLut = base.model.bakedLut; + uberMaterial.SetTexture(Uniforms._LogLut, bakedLut); + uberMaterial.SetVector(Uniforms._LogLut_Params, new Vector3(1f / (float)bakedLut.width, 1f / (float)bakedLut.height, (float)bakedLut.height - 1f)); + float value = Mathf.Exp(base.model.settings.basic.postExposure * 0.6931472f); + uberMaterial.SetFloat(Uniforms._ExposureEV, value); + } + + public void OnGUI() + { + RenderTexture bakedLut = base.model.bakedLut; + Rect position = new Rect(context.viewport.x * (float)Screen.width + 8f, 8f, bakedLut.width, bakedLut.height); + GUI.DrawTexture(position, bakedLut); + } + + public override void OnDisable() + { + GraphicsUtils.Destroy(m_GradingCurves); + GraphicsUtils.Destroy(base.model.bakedLut); + m_GradingCurves = null; + base.model.bakedLut = null; + } +} diff --git a/UnityEngine.PostProcessing/ColorGradingCurve.cs b/UnityEngine.PostProcessing/ColorGradingCurve.cs new file mode 100644 index 0000000..49ea13a --- /dev/null +++ b/UnityEngine.PostProcessing/ColorGradingCurve.cs @@ -0,0 +1,64 @@ +using System; + +namespace UnityEngine.PostProcessing; + +[Serializable] +public sealed class ColorGradingCurve +{ + public AnimationCurve curve; + + [SerializeField] + private bool m_Loop; + + [SerializeField] + private float m_ZeroValue; + + [SerializeField] + private float m_Range; + + private AnimationCurve m_InternalLoopingCurve; + + public ColorGradingCurve(AnimationCurve curve, float zeroValue, bool loop, Vector2 bounds) + { + this.curve = curve; + m_ZeroValue = zeroValue; + m_Loop = loop; + m_Range = bounds.magnitude; + } + + public void Cache() + { + if (!m_Loop) + { + return; + } + int length = curve.length; + if (length >= 2) + { + if (m_InternalLoopingCurve == null) + { + m_InternalLoopingCurve = new AnimationCurve(); + } + Keyframe key = curve[length - 1]; + key.time -= m_Range; + Keyframe key2 = curve[0]; + key2.time += m_Range; + m_InternalLoopingCurve.keys = curve.keys; + m_InternalLoopingCurve.AddKey(key); + m_InternalLoopingCurve.AddKey(key2); + } + } + + public float Evaluate(float t) + { + if (curve.length == 0) + { + return m_ZeroValue; + } + if (!m_Loop || curve.length == 1) + { + return curve.Evaluate(t); + } + return m_InternalLoopingCurve.Evaluate(t); + } +} diff --git a/UnityEngine.PostProcessing/ColorGradingModel.cs b/UnityEngine.PostProcessing/ColorGradingModel.cs new file mode 100644 index 0000000..5d5a45b --- /dev/null +++ b/UnityEngine.PostProcessing/ColorGradingModel.cs @@ -0,0 +1,319 @@ +using System; + +namespace UnityEngine.PostProcessing; + +[Serializable] +public class ColorGradingModel : PostProcessingModel +{ + public enum Tonemapper + { + None, + ACES, + Neutral + } + + [Serializable] + public struct TonemappingSettings + { + [Tooltip("Tonemapping algorithm to use at the end of the color grading process. Use \"Neutral\" if you need a customizable tonemapper or \"Filmic\" to give a standard filmic look to your scenes.")] + public Tonemapper tonemapper; + + [Range(-0.1f, 0.1f)] + public float neutralBlackIn; + + [Range(1f, 20f)] + public float neutralWhiteIn; + + [Range(-0.09f, 0.1f)] + public float neutralBlackOut; + + [Range(1f, 19f)] + public float neutralWhiteOut; + + [Range(0.1f, 20f)] + public float neutralWhiteLevel; + + [Range(1f, 10f)] + public float neutralWhiteClip; + + public static TonemappingSettings defaultSettings + { + get + { + TonemappingSettings result = default(TonemappingSettings); + result.tonemapper = Tonemapper.Neutral; + result.neutralBlackIn = 0.02f; + result.neutralWhiteIn = 10f; + result.neutralBlackOut = 0f; + result.neutralWhiteOut = 10f; + result.neutralWhiteLevel = 5.3f; + result.neutralWhiteClip = 10f; + return result; + } + } + } + + [Serializable] + public struct BasicSettings + { + [Tooltip("Adjusts the overall exposure of the scene in EV units. This is applied after HDR effect and right before tonemapping so it won't affect previous effects in the chain.")] + public float postExposure; + + [Range(-100f, 100f)] + [Tooltip("Sets the white balance to a custom color temperature.")] + public float temperature; + + [Range(-100f, 100f)] + [Tooltip("Sets the white balance to compensate for a green or magenta tint.")] + public float tint; + + [Range(-180f, 180f)] + [Tooltip("Shift the hue of all colors.")] + public float hueShift; + + [Range(0f, 2f)] + [Tooltip("Pushes the intensity of all colors.")] + public float saturation; + + [Range(0f, 2f)] + [Tooltip("Expands or shrinks the overall range of tonal values.")] + public float contrast; + + public static BasicSettings defaultSettings + { + get + { + BasicSettings result = default(BasicSettings); + result.postExposure = 0f; + result.temperature = 0f; + result.tint = 0f; + result.hueShift = 0f; + result.saturation = 1f; + result.contrast = 1f; + return result; + } + } + } + + [Serializable] + public struct ChannelMixerSettings + { + public Vector3 red; + + public Vector3 green; + + public Vector3 blue; + + [HideInInspector] + public int currentEditingChannel; + + public static ChannelMixerSettings defaultSettings + { + get + { + ChannelMixerSettings result = default(ChannelMixerSettings); + result.red = new Vector3(1f, 0f, 0f); + result.green = new Vector3(0f, 1f, 0f); + result.blue = new Vector3(0f, 0f, 1f); + result.currentEditingChannel = 0; + return result; + } + } + } + + [Serializable] + public struct LogWheelsSettings + { + [Trackball("GetSlopeValue")] + public Color slope; + + [Trackball("GetPowerValue")] + public Color power; + + [Trackball("GetOffsetValue")] + public Color offset; + + public static LogWheelsSettings defaultSettings + { + get + { + LogWheelsSettings result = default(LogWheelsSettings); + result.slope = Color.clear; + result.power = Color.clear; + result.offset = Color.clear; + return result; + } + } + } + + [Serializable] + public struct LinearWheelsSettings + { + [Trackball("GetLiftValue")] + public Color lift; + + [Trackball("GetGammaValue")] + public Color gamma; + + [Trackball("GetGainValue")] + public Color gain; + + public static LinearWheelsSettings defaultSettings + { + get + { + LinearWheelsSettings result = default(LinearWheelsSettings); + result.lift = Color.clear; + result.gamma = Color.clear; + result.gain = Color.clear; + return result; + } + } + } + + public enum ColorWheelMode + { + Linear, + Log + } + + [Serializable] + public struct ColorWheelsSettings + { + public ColorWheelMode mode; + + [TrackballGroup] + public LogWheelsSettings log; + + [TrackballGroup] + public LinearWheelsSettings linear; + + public static ColorWheelsSettings defaultSettings + { + get + { + ColorWheelsSettings result = default(ColorWheelsSettings); + result.mode = ColorWheelMode.Log; + result.log = LogWheelsSettings.defaultSettings; + result.linear = LinearWheelsSettings.defaultSettings; + return result; + } + } + } + + [Serializable] + public struct CurvesSettings + { + public ColorGradingCurve master; + + public ColorGradingCurve red; + + public ColorGradingCurve green; + + public ColorGradingCurve blue; + + public ColorGradingCurve hueVShue; + + public ColorGradingCurve hueVSsat; + + public ColorGradingCurve satVSsat; + + public ColorGradingCurve lumVSsat; + + [HideInInspector] + public int e_CurrentEditingCurve; + + [HideInInspector] + public bool e_CurveY; + + [HideInInspector] + public bool e_CurveR; + + [HideInInspector] + public bool e_CurveG; + + [HideInInspector] + public bool e_CurveB; + + public static CurvesSettings defaultSettings + { + get + { + CurvesSettings result = default(CurvesSettings); + result.master = new ColorGradingCurve(new AnimationCurve(new Keyframe(0f, 0f, 1f, 1f), new Keyframe(1f, 1f, 1f, 1f)), 0f, loop: false, new Vector2(0f, 1f)); + result.red = new ColorGradingCurve(new AnimationCurve(new Keyframe(0f, 0f, 1f, 1f), new Keyframe(1f, 1f, 1f, 1f)), 0f, loop: false, new Vector2(0f, 1f)); + result.green = new ColorGradingCurve(new AnimationCurve(new Keyframe(0f, 0f, 1f, 1f), new Keyframe(1f, 1f, 1f, 1f)), 0f, loop: false, new Vector2(0f, 1f)); + result.blue = new ColorGradingCurve(new AnimationCurve(new Keyframe(0f, 0f, 1f, 1f), new Keyframe(1f, 1f, 1f, 1f)), 0f, loop: false, new Vector2(0f, 1f)); + result.hueVShue = new ColorGradingCurve(new AnimationCurve(), 0.5f, loop: true, new Vector2(0f, 1f)); + result.hueVSsat = new ColorGradingCurve(new AnimationCurve(), 0.5f, loop: true, new Vector2(0f, 1f)); + result.satVSsat = new ColorGradingCurve(new AnimationCurve(), 0.5f, loop: false, new Vector2(0f, 1f)); + result.lumVSsat = new ColorGradingCurve(new AnimationCurve(), 0.5f, loop: false, new Vector2(0f, 1f)); + result.e_CurrentEditingCurve = 0; + result.e_CurveY = true; + result.e_CurveR = false; + result.e_CurveG = false; + result.e_CurveB = false; + return result; + } + } + } + + [Serializable] + public struct Settings + { + public TonemappingSettings tonemapping; + + public BasicSettings basic; + + public ChannelMixerSettings channelMixer; + + public ColorWheelsSettings colorWheels; + + public CurvesSettings curves; + + public static Settings defaultSettings + { + get + { + Settings result = default(Settings); + result.tonemapping = TonemappingSettings.defaultSettings; + result.basic = BasicSettings.defaultSettings; + result.channelMixer = ChannelMixerSettings.defaultSettings; + result.colorWheels = ColorWheelsSettings.defaultSettings; + result.curves = CurvesSettings.defaultSettings; + return result; + } + } + } + + [SerializeField] + private Settings m_Settings = Settings.defaultSettings; + + public Settings settings + { + get + { + return m_Settings; + } + set + { + m_Settings = value; + OnValidate(); + } + } + + public bool isDirty { get; internal set; } + + public RenderTexture bakedLut { get; internal set; } + + public override void Reset() + { + m_Settings = Settings.defaultSettings; + OnValidate(); + } + + public override void OnValidate() + { + isDirty = true; + } +} diff --git a/UnityEngine.PostProcessing/DepthOfFieldComponent.cs b/UnityEngine.PostProcessing/DepthOfFieldComponent.cs new file mode 100644 index 0000000..a57657c --- /dev/null +++ b/UnityEngine.PostProcessing/DepthOfFieldComponent.cs @@ -0,0 +1,141 @@ +using System; + +namespace UnityEngine.PostProcessing; + +public sealed class DepthOfFieldComponent : PostProcessingComponentRenderTexture<DepthOfFieldModel> +{ + private static class Uniforms + { + internal static readonly int _DepthOfFieldTex = Shader.PropertyToID("_DepthOfFieldTex"); + + internal static readonly int _DepthOfFieldCoCTex = Shader.PropertyToID("_DepthOfFieldCoCTex"); + + internal static readonly int _Distance = Shader.PropertyToID("_Distance"); + + internal static readonly int _LensCoeff = Shader.PropertyToID("_LensCoeff"); + + internal static readonly int _MaxCoC = Shader.PropertyToID("_MaxCoC"); + + internal static readonly int _RcpMaxCoC = Shader.PropertyToID("_RcpMaxCoC"); + + internal static readonly int _RcpAspect = Shader.PropertyToID("_RcpAspect"); + + internal static readonly int _MainTex = Shader.PropertyToID("_MainTex"); + + internal static readonly int _CoCTex = Shader.PropertyToID("_CoCTex"); + + internal static readonly int _TaaParams = Shader.PropertyToID("_TaaParams"); + + internal static readonly int _DepthOfFieldParams = Shader.PropertyToID("_DepthOfFieldParams"); + } + + private const string k_ShaderString = "Hidden/Post FX/Depth Of Field"; + + private RenderTexture m_CoCHistory; + + private const float k_FilmHeight = 0.024f; + + public override bool active => base.model.enabled && !context.interrupted; + + public override DepthTextureMode GetCameraFlags() + { + return DepthTextureMode.Depth; + } + + private float CalculateFocalLength() + { + DepthOfFieldModel.Settings settings = base.model.settings; + if (!settings.useCameraFov) + { + return settings.focalLength / 1000f; + } + float num = context.camera.fieldOfView * ((float)Math.PI / 180f); + return 0.012f / Mathf.Tan(0.5f * num); + } + + private float CalculateMaxCoCRadius(int screenHeight) + { + float num = (float)base.model.settings.kernelSize * 4f + 6f; + return Mathf.Min(0.05f, num / (float)screenHeight); + } + + private bool CheckHistory(int width, int height) + { + return m_CoCHistory != null && m_CoCHistory.IsCreated() && m_CoCHistory.width == width && m_CoCHistory.height == height; + } + + private RenderTextureFormat SelectFormat(RenderTextureFormat primary, RenderTextureFormat secondary) + { + if (SystemInfo.SupportsRenderTextureFormat(primary)) + { + return primary; + } + if (SystemInfo.SupportsRenderTextureFormat(secondary)) + { + return secondary; + } + return RenderTextureFormat.Default; + } + + public void Prepare(RenderTexture source, Material uberMaterial, bool antialiasCoC, Vector2 taaJitter, float taaBlending) + { + DepthOfFieldModel.Settings settings = base.model.settings; + RenderTextureFormat format = RenderTextureFormat.DefaultHDR; + RenderTextureFormat format2 = SelectFormat(RenderTextureFormat.R8, RenderTextureFormat.RHalf); + float num = CalculateFocalLength(); + float num2 = Mathf.Max(settings.focusDistance, num); + float num3 = (float)source.width / (float)source.height; + float num4 = num * num / (settings.aperture * (num2 - num) * 0.024f * 2f); + float num5 = CalculateMaxCoCRadius(source.height); + Material material = context.materialFactory.Get("Hidden/Post FX/Depth Of Field"); + material.SetFloat(Uniforms._Distance, num2); + material.SetFloat(Uniforms._LensCoeff, num4); + material.SetFloat(Uniforms._MaxCoC, num5); + material.SetFloat(Uniforms._RcpMaxCoC, 1f / num5); + material.SetFloat(Uniforms._RcpAspect, 1f / num3); + RenderTexture renderTexture = context.renderTextureFactory.Get(context.width, context.height, 0, format2, RenderTextureReadWrite.Linear); + Graphics.Blit(null, renderTexture, material, 0); + if (antialiasCoC) + { + material.SetTexture(Uniforms._CoCTex, renderTexture); + float z = ((!CheckHistory(context.width, context.height)) ? 0f : taaBlending); + material.SetVector(Uniforms._TaaParams, new Vector3(taaJitter.x, taaJitter.y, z)); + RenderTexture temporary = RenderTexture.GetTemporary(context.width, context.height, 0, format2); + Graphics.Blit(m_CoCHistory, temporary, material, 1); + context.renderTextureFactory.Release(renderTexture); + if (m_CoCHistory != null) + { + RenderTexture.ReleaseTemporary(m_CoCHistory); + } + renderTexture = (m_CoCHistory = temporary); + } + RenderTexture renderTexture2 = context.renderTextureFactory.Get(context.width / 2, context.height / 2, 0, format); + material.SetTexture(Uniforms._CoCTex, renderTexture); + Graphics.Blit(source, renderTexture2, material, 2); + RenderTexture renderTexture3 = context.renderTextureFactory.Get(context.width / 2, context.height / 2, 0, format); + Graphics.Blit(renderTexture2, renderTexture3, material, (int)(3 + settings.kernelSize)); + Graphics.Blit(renderTexture3, renderTexture2, material, 7); + uberMaterial.SetVector(Uniforms._DepthOfFieldParams, new Vector3(num2, num4, num5)); + if (context.profile.debugViews.IsModeActive(BuiltinDebugViewsModel.Mode.FocusPlane)) + { + uberMaterial.EnableKeyword("DEPTH_OF_FIELD_COC_VIEW"); + context.Interrupt(); + } + else + { + uberMaterial.SetTexture(Uniforms._DepthOfFieldTex, renderTexture2); + uberMaterial.SetTexture(Uniforms._DepthOfFieldCoCTex, renderTexture); + uberMaterial.EnableKeyword("DEPTH_OF_FIELD"); + } + context.renderTextureFactory.Release(renderTexture3); + } + + public override void OnDisable() + { + if (m_CoCHistory != null) + { + RenderTexture.ReleaseTemporary(m_CoCHistory); + } + m_CoCHistory = null; + } +} diff --git a/UnityEngine.PostProcessing/DepthOfFieldModel.cs b/UnityEngine.PostProcessing/DepthOfFieldModel.cs new file mode 100644 index 0000000..6ead0de --- /dev/null +++ b/UnityEngine.PostProcessing/DepthOfFieldModel.cs @@ -0,0 +1,71 @@ +using System; + +namespace UnityEngine.PostProcessing; + +[Serializable] +public class DepthOfFieldModel : PostProcessingModel +{ + public enum KernelSize + { + Small, + Medium, + Large, + VeryLarge + } + + [Serializable] + public struct Settings + { + [Min(0.1f)] + [Tooltip("Distance to the point of focus.")] + public float focusDistance; + + [Range(0.05f, 32f)] + [Tooltip("Ratio of aperture (known as f-stop or f-number). The smaller the value is, the shallower the depth of field is.")] + public float aperture; + + [Range(1f, 300f)] + [Tooltip("Distance between the lens and the film. The larger the value is, the shallower the depth of field is.")] + public float focalLength; + + [Tooltip("Calculate the focal length automatically from the field-of-view value set on the camera. Using this setting isn't recommended.")] + public bool useCameraFov; + + [Tooltip("Convolution kernel size of the bokeh filter, which determines the maximum radius of bokeh. It also affects the performance (the larger the kernel is, the longer the GPU time is required).")] + public KernelSize kernelSize; + + public static Settings defaultSettings + { + get + { + Settings result = default(Settings); + result.focusDistance = 10f; + result.aperture = 5.6f; + result.focalLength = 50f; + result.useCameraFov = false; + result.kernelSize = KernelSize.Medium; + return result; + } + } + } + + [SerializeField] + private Settings m_Settings = Settings.defaultSettings; + + public Settings settings + { + get + { + return m_Settings; + } + set + { + m_Settings = value; + } + } + + public override void Reset() + { + m_Settings = Settings.defaultSettings; + } +} diff --git a/UnityEngine.PostProcessing/DitheringComponent.cs b/UnityEngine.PostProcessing/DitheringComponent.cs new file mode 100644 index 0000000..a9f0554 --- /dev/null +++ b/UnityEngine.PostProcessing/DitheringComponent.cs @@ -0,0 +1,51 @@ +namespace UnityEngine.PostProcessing; + +public sealed class DitheringComponent : PostProcessingComponentRenderTexture<DitheringModel> +{ + private static class Uniforms + { + internal static readonly int _DitheringTex = Shader.PropertyToID("_DitheringTex"); + + internal static readonly int _DitheringCoords = Shader.PropertyToID("_DitheringCoords"); + } + + private Texture2D[] noiseTextures; + + private int textureIndex; + + private const int k_TextureCount = 64; + + public override bool active => base.model.enabled && !context.interrupted; + + public override void OnDisable() + { + noiseTextures = null; + } + + private void LoadNoiseTextures() + { + noiseTextures = new Texture2D[64]; + for (int i = 0; i < 64; i++) + { + noiseTextures[i] = Resources.Load<Texture2D>("Bluenoise64/LDR_LLL1_" + i); + } + } + + public override void Prepare(Material uberMaterial) + { + if (++textureIndex >= 64) + { + textureIndex = 0; + } + float value = Random.value; + float value2 = Random.value; + if (noiseTextures == null) + { + LoadNoiseTextures(); + } + Texture2D texture2D = noiseTextures[textureIndex]; + uberMaterial.EnableKeyword("DITHERING"); + uberMaterial.SetTexture(Uniforms._DitheringTex, texture2D); + uberMaterial.SetVector(Uniforms._DitheringCoords, new Vector4((float)context.width / (float)texture2D.width, (float)context.height / (float)texture2D.height, value, value2)); + } +} diff --git a/UnityEngine.PostProcessing/DitheringModel.cs b/UnityEngine.PostProcessing/DitheringModel.cs new file mode 100644 index 0000000..1258f2e --- /dev/null +++ b/UnityEngine.PostProcessing/DitheringModel.cs @@ -0,0 +1,35 @@ +using System; +using System.Runtime.InteropServices; + +namespace UnityEngine.PostProcessing; + +[Serializable] +public class DitheringModel : PostProcessingModel +{ + [Serializable] + [StructLayout(LayoutKind.Sequential, Size = 1)] + public struct Settings + { + public static Settings defaultSettings => default(Settings); + } + + [SerializeField] + private Settings m_Settings = Settings.defaultSettings; + + public Settings settings + { + get + { + return m_Settings; + } + set + { + m_Settings = value; + } + } + + public override void Reset() + { + m_Settings = Settings.defaultSettings; + } +} diff --git a/UnityEngine.PostProcessing/EyeAdaptationComponent.cs b/UnityEngine.PostProcessing/EyeAdaptationComponent.cs new file mode 100644 index 0000000..fce1172 --- /dev/null +++ b/UnityEngine.PostProcessing/EyeAdaptationComponent.cs @@ -0,0 +1,168 @@ +namespace UnityEngine.PostProcessing; + +public sealed class EyeAdaptationComponent : PostProcessingComponentRenderTexture<EyeAdaptationModel> +{ + private static class Uniforms + { + internal static readonly int _Params = Shader.PropertyToID("_Params"); + + internal static readonly int _Speed = Shader.PropertyToID("_Speed"); + + internal static readonly int _ScaleOffsetRes = Shader.PropertyToID("_ScaleOffsetRes"); + + internal static readonly int _ExposureCompensation = Shader.PropertyToID("_ExposureCompensation"); + + internal static readonly int _AutoExposure = Shader.PropertyToID("_AutoExposure"); + + internal static readonly int _DebugWidth = Shader.PropertyToID("_DebugWidth"); + } + + private ComputeShader m_EyeCompute; + + private ComputeBuffer m_HistogramBuffer; + + private readonly RenderTexture[] m_AutoExposurePool = new RenderTexture[2]; + + private int m_AutoExposurePingPing; + + private RenderTexture m_CurrentAutoExposure; + + private RenderTexture m_DebugHistogram; + + private static uint[] s_EmptyHistogramBuffer; + + private bool m_FirstFrame = true; + + private const int k_HistogramBins = 64; + + private const int k_HistogramThreadX = 16; + + private const int k_HistogramThreadY = 16; + + public override bool active => base.model.enabled && SystemInfo.supportsComputeShaders && !context.interrupted; + + public void ResetHistory() + { + m_FirstFrame = true; + } + + public override void OnEnable() + { + m_FirstFrame = true; + } + + public override void OnDisable() + { + RenderTexture[] autoExposurePool = m_AutoExposurePool; + foreach (RenderTexture obj in autoExposurePool) + { + GraphicsUtils.Destroy(obj); + } + if (m_HistogramBuffer != null) + { + m_HistogramBuffer.Release(); + } + m_HistogramBuffer = null; + if (m_DebugHistogram != null) + { + m_DebugHistogram.Release(); + } + m_DebugHistogram = null; + } + + private Vector4 GetHistogramScaleOffsetRes() + { + EyeAdaptationModel.Settings settings = base.model.settings; + float num = settings.logMax - settings.logMin; + float num2 = 1f / num; + float y = (float)(-settings.logMin) * num2; + return new Vector4(num2, y, Mathf.Floor((float)context.width / 2f), Mathf.Floor((float)context.height / 2f)); + } + + public Texture Prepare(RenderTexture source, Material uberMaterial) + { + EyeAdaptationModel.Settings settings = base.model.settings; + if (m_EyeCompute == null) + { + m_EyeCompute = Resources.Load<ComputeShader>("Shaders/EyeHistogram"); + } + Material material = context.materialFactory.Get("Hidden/Post FX/Eye Adaptation"); + material.shaderKeywords = null; + if (m_HistogramBuffer == null) + { + m_HistogramBuffer = new ComputeBuffer(64, 4); + } + if (s_EmptyHistogramBuffer == null) + { + s_EmptyHistogramBuffer = new uint[64]; + } + Vector4 histogramScaleOffsetRes = GetHistogramScaleOffsetRes(); + RenderTexture renderTexture = context.renderTextureFactory.Get((int)histogramScaleOffsetRes.z, (int)histogramScaleOffsetRes.w, 0, source.format); + Graphics.Blit(source, renderTexture); + if (m_AutoExposurePool[0] == null || !m_AutoExposurePool[0].IsCreated()) + { + m_AutoExposurePool[0] = new RenderTexture(1, 1, 0, RenderTextureFormat.RFloat); + } + if (m_AutoExposurePool[1] == null || !m_AutoExposurePool[1].IsCreated()) + { + m_AutoExposurePool[1] = new RenderTexture(1, 1, 0, RenderTextureFormat.RFloat); + } + m_HistogramBuffer.SetData(s_EmptyHistogramBuffer); + int kernelIndex = m_EyeCompute.FindKernel("KEyeHistogram"); + m_EyeCompute.SetBuffer(kernelIndex, "_Histogram", m_HistogramBuffer); + m_EyeCompute.SetTexture(kernelIndex, "_Source", renderTexture); + m_EyeCompute.SetVector("_ScaleOffsetRes", histogramScaleOffsetRes); + m_EyeCompute.Dispatch(kernelIndex, Mathf.CeilToInt((float)renderTexture.width / 16f), Mathf.CeilToInt((float)renderTexture.height / 16f), 1); + context.renderTextureFactory.Release(renderTexture); + settings.highPercent = Mathf.Clamp(settings.highPercent, 1.01f, 99f); + settings.lowPercent = Mathf.Clamp(settings.lowPercent, 1f, settings.highPercent - 0.01f); + material.SetBuffer("_Histogram", m_HistogramBuffer); + material.SetVector(Uniforms._Params, new Vector4(settings.lowPercent * 0.01f, settings.highPercent * 0.01f, Mathf.Exp(settings.minLuminance * 0.6931472f), Mathf.Exp(settings.maxLuminance * 0.6931472f))); + material.SetVector(Uniforms._Speed, new Vector2(settings.speedDown, settings.speedUp)); + material.SetVector(Uniforms._ScaleOffsetRes, histogramScaleOffsetRes); + material.SetFloat(Uniforms._ExposureCompensation, settings.keyValue); + if (settings.dynamicKeyValue) + { + material.EnableKeyword("AUTO_KEY_VALUE"); + } + if (m_FirstFrame || !Application.isPlaying) + { + m_CurrentAutoExposure = m_AutoExposurePool[0]; + Graphics.Blit(null, m_CurrentAutoExposure, material, 1); + Graphics.Blit(m_AutoExposurePool[0], m_AutoExposurePool[1]); + } + else + { + int autoExposurePingPing = m_AutoExposurePingPing; + RenderTexture source2 = m_AutoExposurePool[++autoExposurePingPing % 2]; + RenderTexture renderTexture2 = m_AutoExposurePool[++autoExposurePingPing % 2]; + Graphics.Blit(source2, renderTexture2, material, (int)settings.adaptationType); + m_AutoExposurePingPing = ++autoExposurePingPing % 2; + m_CurrentAutoExposure = renderTexture2; + } + if (context.profile.debugViews.IsModeActive(BuiltinDebugViewsModel.Mode.EyeAdaptation)) + { + if (m_DebugHistogram == null || !m_DebugHistogram.IsCreated()) + { + m_DebugHistogram = new RenderTexture(256, 128, 0, RenderTextureFormat.ARGB32) + { + filterMode = FilterMode.Point, + wrapMode = TextureWrapMode.Clamp + }; + } + material.SetFloat(Uniforms._DebugWidth, m_DebugHistogram.width); + Graphics.Blit(null, m_DebugHistogram, material, 2); + } + m_FirstFrame = false; + return m_CurrentAutoExposure; + } + + public void OnGUI() + { + if (!(m_DebugHistogram == null) && m_DebugHistogram.IsCreated()) + { + Rect position = new Rect(context.viewport.x * (float)Screen.width + 8f, 8f, m_DebugHistogram.width, m_DebugHistogram.height); + GUI.DrawTexture(position, m_DebugHistogram); + } + } +} diff --git a/UnityEngine.PostProcessing/EyeAdaptationModel.cs b/UnityEngine.PostProcessing/EyeAdaptationModel.cs new file mode 100644 index 0000000..aab9a3d --- /dev/null +++ b/UnityEngine.PostProcessing/EyeAdaptationModel.cs @@ -0,0 +1,97 @@ +using System; + +namespace UnityEngine.PostProcessing; + +[Serializable] +public class EyeAdaptationModel : PostProcessingModel +{ + public enum EyeAdaptationType + { + Progressive, + Fixed + } + + [Serializable] + public struct Settings + { + [Range(1f, 99f)] + [Tooltip("Filters the dark part of the histogram when computing the average luminance to avoid very dark pixels from contributing to the auto exposure. Unit is in percent.")] + public float lowPercent; + + [Range(1f, 99f)] + [Tooltip("Filters the bright part of the histogram when computing the average luminance to avoid very dark pixels from contributing to the auto exposure. Unit is in percent.")] + public float highPercent; + + [Tooltip("Minimum average luminance to consider for auto exposure (in EV).")] + public float minLuminance; + + [Tooltip("Maximum average luminance to consider for auto exposure (in EV).")] + public float maxLuminance; + + [Min(0f)] + [Tooltip("Exposure bias. Use this to offset the global exposure of the scene.")] + public float keyValue; + + [Tooltip("Set this to true to let Unity handle the key value automatically based on average luminance.")] + public bool dynamicKeyValue; + + [Tooltip("Use \"Progressive\" if you want the auto exposure to be animated. Use \"Fixed\" otherwise.")] + public EyeAdaptationType adaptationType; + + [Min(0f)] + [Tooltip("Adaptation speed from a dark to a light environment.")] + public float speedUp; + + [Min(0f)] + [Tooltip("Adaptation speed from a light to a dark environment.")] + public float speedDown; + + [Range(-16f, -1f)] + [Tooltip("Lower bound for the brightness range of the generated histogram (in EV). The bigger the spread between min & max, the lower the precision will be.")] + public int logMin; + + [Range(1f, 16f)] + [Tooltip("Upper bound for the brightness range of the generated histogram (in EV). The bigger the spread between min & max, the lower the precision will be.")] + public int logMax; + + public static Settings defaultSettings + { + get + { + Settings result = default(Settings); + result.lowPercent = 45f; + result.highPercent = 95f; + result.minLuminance = -5f; + result.maxLuminance = 1f; + result.keyValue = 0.25f; + result.dynamicKeyValue = true; + result.adaptationType = EyeAdaptationType.Progressive; + result.speedUp = 2f; + result.speedDown = 1f; + result.logMin = -8; + result.logMax = 4; + return result; + } + } + } + + [SerializeField] + private Settings m_Settings = Settings.defaultSettings; + + public Settings settings + { + get + { + return m_Settings; + } + set + { + m_Settings = value; + } + } + + public override void Reset() + { + m_Settings = Settings.defaultSettings; + } +} diff --git a/UnityEngine.PostProcessing/FogComponent.cs b/UnityEngine.PostProcessing/FogComponent.cs new file mode 100644 index 0000000..387ec64 --- /dev/null +++ b/UnityEngine.PostProcessing/FogComponent.cs @@ -0,0 +1,67 @@ +using UnityEngine.Rendering; + +namespace UnityEngine.PostProcessing; + +public sealed class FogComponent : PostProcessingComponentCommandBuffer<FogModel> +{ + private static class Uniforms + { + internal static readonly int _FogColor = Shader.PropertyToID("_FogColor"); + + internal static readonly int _Density = Shader.PropertyToID("_Density"); + + internal static readonly int _Start = Shader.PropertyToID("_Start"); + + internal static readonly int _End = Shader.PropertyToID("_End"); + + internal static readonly int _TempRT = Shader.PropertyToID("_TempRT"); + } + + private const string k_ShaderString = "Hidden/Post FX/Fog"; + + public override bool active => base.model.enabled && context.isGBufferAvailable && RenderSettings.fog && !context.interrupted; + + public override string GetName() + { + return "Fog"; + } + + public override DepthTextureMode GetCameraFlags() + { + return DepthTextureMode.Depth; + } + + public override CameraEvent GetCameraEvent() + { + return CameraEvent.AfterImageEffectsOpaque; + } + + public override void PopulateCommandBuffer(CommandBuffer cb) + { + FogModel.Settings settings = base.model.settings; + Material material = context.materialFactory.Get("Hidden/Post FX/Fog"); + material.shaderKeywords = null; + Color value = ((!GraphicsUtils.isLinearColorSpace) ? RenderSettings.fogColor : RenderSettings.fogColor.linear); + material.SetColor(Uniforms._FogColor, value); + material.SetFloat(Uniforms._Density, RenderSettings.fogDensity); + material.SetFloat(Uniforms._Start, RenderSettings.fogStartDistance); + material.SetFloat(Uniforms._End, RenderSettings.fogEndDistance); + switch (RenderSettings.fogMode) + { + case FogMode.Linear: + material.EnableKeyword("FOG_LINEAR"); + break; + case FogMode.Exponential: + material.EnableKeyword("FOG_EXP"); + break; + case FogMode.ExponentialSquared: + material.EnableKeyword("FOG_EXP2"); + break; + } + RenderTextureFormat format = ((!context.isHdr) ? RenderTextureFormat.Default : RenderTextureFormat.DefaultHDR); + cb.GetTemporaryRT(Uniforms._TempRT, context.width, context.height, 24, FilterMode.Bilinear, format); + cb.Blit(BuiltinRenderTextureType.CameraTarget, Uniforms._TempRT); + cb.Blit(Uniforms._TempRT, BuiltinRenderTextureType.CameraTarget, material, settings.excludeSkybox ? 1 : 0); + cb.ReleaseTemporaryRT(Uniforms._TempRT); + } +} diff --git a/UnityEngine.PostProcessing/FogModel.cs b/UnityEngine.PostProcessing/FogModel.cs new file mode 100644 index 0000000..4a7f4cd --- /dev/null +++ b/UnityEngine.PostProcessing/FogModel.cs @@ -0,0 +1,44 @@ +using System; + +namespace UnityEngine.PostProcessing; + +[Serializable] +public class FogModel : PostProcessingModel +{ + [Serializable] + public struct Settings + { + [Tooltip("Should the fog affect the skybox?")] + public bool excludeSkybox; + + public static Settings defaultSettings + { + get + { + Settings result = default(Settings); + result.excludeSkybox = true; + return result; + } + } + } + + [SerializeField] + private Settings m_Settings = Settings.defaultSettings; + + public Settings settings + { + get + { + return m_Settings; + } + set + { + m_Settings = value; + } + } + + public override void Reset() + { + m_Settings = Settings.defaultSettings; + } +} diff --git a/UnityEngine.PostProcessing/FxaaComponent.cs b/UnityEngine.PostProcessing/FxaaComponent.cs new file mode 100644 index 0000000..9d74204 --- /dev/null +++ b/UnityEngine.PostProcessing/FxaaComponent.cs @@ -0,0 +1,24 @@ +namespace UnityEngine.PostProcessing; + +public sealed class FxaaComponent : PostProcessingComponentRenderTexture<AntialiasingModel> +{ + private static class Uniforms + { + internal static readonly int _QualitySettings = Shader.PropertyToID("_QualitySettings"); + + internal static readonly int _ConsoleSettings = Shader.PropertyToID("_ConsoleSettings"); + } + + public override bool active => base.model.enabled && base.model.settings.method == AntialiasingModel.Method.Fxaa && !context.interrupted; + + public void Render(RenderTexture source, RenderTexture destination) + { + AntialiasingModel.FxaaSettings fxaaSettings = base.model.settings.fxaaSettings; + Material material = context.materialFactory.Get("Hidden/Post FX/FXAA"); + AntialiasingModel.FxaaQualitySettings fxaaQualitySettings = AntialiasingModel.FxaaQualitySettings.presets[(int)fxaaSettings.preset]; + AntialiasingModel.FxaaConsoleSettings fxaaConsoleSettings = AntialiasingModel.FxaaConsoleSettings.presets[(int)fxaaSettings.preset]; + material.SetVector(Uniforms._QualitySettings, new Vector3(fxaaQualitySettings.subpixelAliasingRemovalAmount, fxaaQualitySettings.edgeDetectionThreshold, fxaaQualitySettings.minimumRequiredLuminance)); + material.SetVector(Uniforms._ConsoleSettings, new Vector4(fxaaConsoleSettings.subpixelSpreadAmount, fxaaConsoleSettings.edgeSharpnessAmount, fxaaConsoleSettings.edgeDetectionThreshold, fxaaConsoleSettings.minimumRequiredLuminance)); + Graphics.Blit(source, destination, material, 0); + } +} diff --git a/UnityEngine.PostProcessing/GetSetAttribute.cs b/UnityEngine.PostProcessing/GetSetAttribute.cs new file mode 100644 index 0000000..1b34e7d --- /dev/null +++ b/UnityEngine.PostProcessing/GetSetAttribute.cs @@ -0,0 +1,13 @@ +namespace UnityEngine.PostProcessing; + +public sealed class GetSetAttribute : PropertyAttribute +{ + public readonly string name; + + public bool dirty; + + public GetSetAttribute(string name) + { + this.name = name; + } +} diff --git a/UnityEngine.PostProcessing/GrainComponent.cs b/UnityEngine.PostProcessing/GrainComponent.cs new file mode 100644 index 0000000..c01dcda --- /dev/null +++ b/UnityEngine.PostProcessing/GrainComponent.cs @@ -0,0 +1,52 @@ +namespace UnityEngine.PostProcessing; + +public sealed class GrainComponent : PostProcessingComponentRenderTexture<GrainModel> +{ + private static class Uniforms + { + internal static readonly int _Grain_Params1 = Shader.PropertyToID("_Grain_Params1"); + + internal static readonly int _Grain_Params2 = Shader.PropertyToID("_Grain_Params2"); + + internal static readonly int _GrainTex = Shader.PropertyToID("_GrainTex"); + + internal static readonly int _Phase = Shader.PropertyToID("_Phase"); + } + + private RenderTexture m_GrainLookupRT; + + public override bool active => base.model.enabled && base.model.settings.intensity > 0f && SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf) && !context.interrupted; + + public override void OnDisable() + { + GraphicsUtils.Destroy(m_GrainLookupRT); + m_GrainLookupRT = null; + } + + public override void Prepare(Material uberMaterial) + { + GrainModel.Settings settings = base.model.settings; + uberMaterial.EnableKeyword("GRAIN"); + float realtimeSinceStartup = Time.realtimeSinceStartup; + float value = Random.value; + float value2 = Random.value; + if (m_GrainLookupRT == null || !m_GrainLookupRT.IsCreated()) + { + GraphicsUtils.Destroy(m_GrainLookupRT); + m_GrainLookupRT = new RenderTexture(192, 192, 0, RenderTextureFormat.ARGBHalf) + { + filterMode = FilterMode.Bilinear, + wrapMode = TextureWrapMode.Repeat, + anisoLevel = 0, + name = "Grain Lookup Texture" + }; + m_GrainLookupRT.Create(); + } + Material material = context.materialFactory.Get("Hidden/Post FX/Grain Generator"); + material.SetFloat(Uniforms._Phase, realtimeSinceStartup / 20f); + Graphics.Blit(null, m_GrainLookupRT, material, settings.colored ? 1 : 0); + uberMaterial.SetTexture(Uniforms._GrainTex, m_GrainLookupRT); + uberMaterial.SetVector(Uniforms._Grain_Params1, new Vector2(settings.luminanceContribution, settings.intensity * 20f)); + uberMaterial.SetVector(Uniforms._Grain_Params2, new Vector4((float)context.width / (float)m_GrainLookupRT.width / settings.size, (float)context.height / (float)m_GrainLookupRT.height / settings.size, value, value2)); + } +} diff --git a/UnityEngine.PostProcessing/GrainModel.cs b/UnityEngine.PostProcessing/GrainModel.cs new file mode 100644 index 0000000..20ca694 --- /dev/null +++ b/UnityEngine.PostProcessing/GrainModel.cs @@ -0,0 +1,59 @@ +using System; + +namespace UnityEngine.PostProcessing; + +[Serializable] +public class GrainModel : PostProcessingModel +{ + [Serializable] + public struct Settings + { + [Tooltip("Enable the use of colored grain.")] + public bool colored; + + [Range(0f, 1f)] + [Tooltip("Grain strength. Higher means more visible grain.")] + public float intensity; + + [Range(0.3f, 3f)] + [Tooltip("Grain particle size.")] + public float size; + + [Range(0f, 1f)] + [Tooltip("Controls the noisiness response curve based on scene luminance. Lower values mean less noise in dark areas.")] + public float luminanceContribution; + + public static Settings defaultSettings + { + get + { + Settings result = default(Settings); + result.colored = true; + result.intensity = 0.5f; + result.size = 1f; + result.luminanceContribution = 0.8f; + return result; + } + } + } + + [SerializeField] + private Settings m_Settings = Settings.defaultSettings; + + public Settings settings + { + get + { + return m_Settings; + } + set + { + m_Settings = value; + } + } + + public override void Reset() + { + m_Settings = Settings.defaultSettings; + } +} diff --git a/UnityEngine.PostProcessing/GraphicsUtils.cs b/UnityEngine.PostProcessing/GraphicsUtils.cs new file mode 100644 index 0000000..9062c77 --- /dev/null +++ b/UnityEngine.PostProcessing/GraphicsUtils.cs @@ -0,0 +1,115 @@ +namespace UnityEngine.PostProcessing; + +public static class GraphicsUtils +{ + private static Texture2D s_WhiteTexture; + + private static Mesh s_Quad; + + public static bool isLinearColorSpace => QualitySettings.activeColorSpace == ColorSpace.Linear; + + public static bool supportsDX11 => SystemInfo.graphicsShaderLevel >= 50 && SystemInfo.supportsComputeShaders; + + public static Texture2D whiteTexture + { + get + { + if (s_WhiteTexture != null) + { + return s_WhiteTexture; + } + s_WhiteTexture = new Texture2D(1, 1, TextureFormat.ARGB32, mipmap: false); + s_WhiteTexture.SetPixel(0, 0, new Color(1f, 1f, 1f, 1f)); + s_WhiteTexture.Apply(); + return s_WhiteTexture; + } + } + + public static Mesh quad + { + get + { + if (s_Quad != null) + { + return s_Quad; + } + Vector3[] vertices = new Vector3[4] + { + new Vector3(-1f, -1f, 0f), + new Vector3(1f, 1f, 0f), + new Vector3(1f, -1f, 0f), + new Vector3(-1f, 1f, 0f) + }; + Vector2[] uv = new Vector2[4] + { + new Vector2(0f, 0f), + new Vector2(1f, 1f), + new Vector2(1f, 0f), + new Vector2(0f, 1f) + }; + int[] triangles = new int[6] { 0, 1, 2, 1, 0, 3 }; + Mesh mesh = new Mesh(); + mesh.vertices = vertices; + mesh.uv = uv; + mesh.triangles = triangles; + s_Quad = mesh; + s_Quad.RecalculateNormals(); + s_Quad.RecalculateBounds(); + return s_Quad; + } + } + + public static void Blit(Material material, int pass) + { + GL.PushMatrix(); + GL.LoadOrtho(); + material.SetPass(pass); + GL.Begin(5); + GL.TexCoord2(0f, 0f); + GL.Vertex3(0f, 0f, 0.1f); + GL.TexCoord2(1f, 0f); + GL.Vertex3(1f, 0f, 0.1f); + GL.TexCoord2(0f, 1f); + GL.Vertex3(0f, 1f, 0.1f); + GL.TexCoord2(1f, 1f); + GL.Vertex3(1f, 1f, 0.1f); + GL.End(); + GL.PopMatrix(); + } + + public static void ClearAndBlit(Texture source, RenderTexture destination, Material material, int pass, bool clearColor = true, bool clearDepth = false) + { + RenderTexture active = RenderTexture.active; + RenderTexture.active = destination; + GL.Clear(clearDepth: false, clearColor, Color.clear); + GL.PushMatrix(); + GL.LoadOrtho(); + material.SetTexture("_MainTex", source); + material.SetPass(pass); + GL.Begin(5); + GL.TexCoord2(0f, 0f); + GL.Vertex3(0f, 0f, 0.1f); + GL.TexCoord2(1f, 0f); + GL.Vertex3(1f, 0f, 0.1f); + GL.TexCoord2(0f, 1f); + GL.Vertex3(0f, 1f, 0.1f); + GL.TexCoord2(1f, 1f); + GL.Vertex3(1f, 1f, 0.1f); + GL.End(); + GL.PopMatrix(); + RenderTexture.active = active; + } + + public static void Destroy(Object obj) + { + if (obj != null) + { + Object.Destroy(obj); + } + } + + public static void Dispose() + { + Destroy(s_Quad); + } +} diff --git a/UnityEngine.PostProcessing/MaterialFactory.cs b/UnityEngine.PostProcessing/MaterialFactory.cs new file mode 100644 index 0000000..dbbed34 --- /dev/null +++ b/UnityEngine.PostProcessing/MaterialFactory.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; + +namespace UnityEngine.PostProcessing; + +public sealed class MaterialFactory : IDisposable +{ + private Dictionary<string, Material> m_Materials; + + public MaterialFactory() + { + m_Materials = new Dictionary<string, Material>(); + } + + public Material Get(string shaderName) + { + if (!m_Materials.TryGetValue(shaderName, out var value)) + { + Shader shader = Shader.Find(shaderName); + if (shader == null) + { + throw new ArgumentException($"Shader not found ({shaderName})"); + } + Material material = new Material(shader); + material.name = string.Format("PostFX - {0}", shaderName.Substring(shaderName.LastIndexOf("/") + 1)); + material.hideFlags = HideFlags.DontSave; + value = material; + m_Materials.Add(shaderName, value); + } + return value; + } + + public void Dispose() + { + Dictionary<string, Material>.Enumerator enumerator = m_Materials.GetEnumerator(); + while (enumerator.MoveNext()) + { + Material value = enumerator.Current.Value; + GraphicsUtils.Destroy(value); + } + m_Materials.Clear(); + } +} diff --git a/UnityEngine.PostProcessing/MinAttribute.cs b/UnityEngine.PostProcessing/MinAttribute.cs new file mode 100644 index 0000000..cc991ef --- /dev/null +++ b/UnityEngine.PostProcessing/MinAttribute.cs @@ -0,0 +1,11 @@ +namespace UnityEngine.PostProcessing; + +public sealed class MinAttribute : PropertyAttribute +{ + public readonly float min; + + public MinAttribute(float min) + { + this.min = min; + } +} diff --git a/UnityEngine.PostProcessing/MotionBlurComponent.cs b/UnityEngine.PostProcessing/MotionBlurComponent.cs new file mode 100644 index 0000000..59199e1 --- /dev/null +++ b/UnityEngine.PostProcessing/MotionBlurComponent.cs @@ -0,0 +1,421 @@ +using UnityEngine.Rendering; + +namespace UnityEngine.PostProcessing; + +public sealed class MotionBlurComponent : PostProcessingComponentCommandBuffer<MotionBlurModel> +{ + private static class Uniforms + { + internal static readonly int _VelocityScale = Shader.PropertyToID("_VelocityScale"); + + internal static readonly int _MaxBlurRadius = Shader.PropertyToID("_MaxBlurRadius"); + + internal static readonly int _RcpMaxBlurRadius = Shader.PropertyToID("_RcpMaxBlurRadius"); + + internal static readonly int _VelocityTex = Shader.PropertyToID("_VelocityTex"); + + internal static readonly int _MainTex = Shader.PropertyToID("_MainTex"); + + internal static readonly int _Tile2RT = Shader.PropertyToID("_Tile2RT"); + + internal static readonly int _Tile4RT = Shader.PropertyToID("_Tile4RT"); + + internal static readonly int _Tile8RT = Shader.PropertyToID("_Tile8RT"); + + internal static readonly int _TileMaxOffs = Shader.PropertyToID("_TileMaxOffs"); + + internal static readonly int _TileMaxLoop = Shader.PropertyToID("_TileMaxLoop"); + + internal static readonly int _TileVRT = Shader.PropertyToID("_TileVRT"); + + internal static readonly int _NeighborMaxTex = Shader.PropertyToID("_NeighborMaxTex"); + + internal static readonly int _LoopCount = Shader.PropertyToID("_LoopCount"); + + internal static readonly int _TempRT = Shader.PropertyToID("_TempRT"); + + internal static readonly int _History1LumaTex = Shader.PropertyToID("_History1LumaTex"); + + internal static readonly int _History2LumaTex = Shader.PropertyToID("_History2LumaTex"); + + internal static readonly int _History3LumaTex = Shader.PropertyToID("_History3LumaTex"); + + internal static readonly int _History4LumaTex = Shader.PropertyToID("_History4LumaTex"); + + internal static readonly int _History1ChromaTex = Shader.PropertyToID("_History1ChromaTex"); + + internal static readonly int _History2ChromaTex = Shader.PropertyToID("_History2ChromaTex"); + + internal static readonly int _History3ChromaTex = Shader.PropertyToID("_History3ChromaTex"); + + internal static readonly int _History4ChromaTex = Shader.PropertyToID("_History4ChromaTex"); + + internal static readonly int _History1Weight = Shader.PropertyToID("_History1Weight"); + + internal static readonly int _History2Weight = Shader.PropertyToID("_History2Weight"); + + internal static readonly int _History3Weight = Shader.PropertyToID("_History3Weight"); + + internal static readonly int _History4Weight = Shader.PropertyToID("_History4Weight"); + } + + private enum Pass + { + VelocitySetup, + TileMax1, + TileMax2, + TileMaxV, + NeighborMax, + Reconstruction, + FrameCompression, + FrameBlendingChroma, + FrameBlendingRaw + } + + public class ReconstructionFilter + { + private RenderTextureFormat m_VectorRTFormat = RenderTextureFormat.RGHalf; + + private RenderTextureFormat m_PackedRTFormat = RenderTextureFormat.ARGB2101010; + + public ReconstructionFilter() + { + CheckTextureFormatSupport(); + } + + private void CheckTextureFormatSupport() + { + if (!SystemInfo.SupportsRenderTextureFormat(m_PackedRTFormat)) + { + m_PackedRTFormat = RenderTextureFormat.ARGB32; + } + } + + public bool IsSupported() + { + return SystemInfo.supportsMotionVectors; + } + + public void ProcessImage(PostProcessingContext context, CommandBuffer cb, ref MotionBlurModel.Settings settings, RenderTargetIdentifier source, RenderTargetIdentifier destination, Material material) + { + int num = (int)(5f * (float)context.height / 100f); + int num2 = ((num - 1) / 8 + 1) * 8; + float value = settings.shutterAngle / 360f; + cb.SetGlobalFloat(Uniforms._VelocityScale, value); + cb.SetGlobalFloat(Uniforms._MaxBlurRadius, num); + cb.SetGlobalFloat(Uniforms._RcpMaxBlurRadius, 1f / (float)num); + int velocityTex = Uniforms._VelocityTex; + cb.GetTemporaryRT(velocityTex, context.width, context.height, 0, FilterMode.Point, m_PackedRTFormat, RenderTextureReadWrite.Linear); + cb.Blit(null, velocityTex, material, 0); + int tile2RT = Uniforms._Tile2RT; + cb.GetTemporaryRT(tile2RT, context.width / 2, context.height / 2, 0, FilterMode.Point, m_VectorRTFormat, RenderTextureReadWrite.Linear); + cb.SetGlobalTexture(Uniforms._MainTex, velocityTex); + cb.Blit(velocityTex, tile2RT, material, 1); + int tile4RT = Uniforms._Tile4RT; + cb.GetTemporaryRT(tile4RT, context.width / 4, context.height / 4, 0, FilterMode.Point, m_VectorRTFormat, RenderTextureReadWrite.Linear); + cb.SetGlobalTexture(Uniforms._MainTex, tile2RT); + cb.Blit(tile2RT, tile4RT, material, 2); + cb.ReleaseTemporaryRT(tile2RT); + int tile8RT = Uniforms._Tile8RT; + cb.GetTemporaryRT(tile8RT, context.width / 8, context.height / 8, 0, FilterMode.Point, m_VectorRTFormat, RenderTextureReadWrite.Linear); + cb.SetGlobalTexture(Uniforms._MainTex, tile4RT); + cb.Blit(tile4RT, tile8RT, material, 2); + cb.ReleaseTemporaryRT(tile4RT); + Vector2 vector = Vector2.one * ((float)num2 / 8f - 1f) * -0.5f; + cb.SetGlobalVector(Uniforms._TileMaxOffs, vector); + cb.SetGlobalFloat(Uniforms._TileMaxLoop, (int)((float)num2 / 8f)); + int tileVRT = Uniforms._TileVRT; + cb.GetTemporaryRT(tileVRT, context.width / num2, context.height / num2, 0, FilterMode.Point, m_VectorRTFormat, RenderTextureReadWrite.Linear); + cb.SetGlobalTexture(Uniforms._MainTex, tile8RT); + cb.Blit(tile8RT, tileVRT, material, 3); + cb.ReleaseTemporaryRT(tile8RT); + int neighborMaxTex = Uniforms._NeighborMaxTex; + int width = context.width / num2; + int height = context.height / num2; + cb.GetTemporaryRT(neighborMaxTex, width, height, 0, FilterMode.Point, m_VectorRTFormat, RenderTextureReadWrite.Linear); + cb.SetGlobalTexture(Uniforms._MainTex, tileVRT); + cb.Blit(tileVRT, neighborMaxTex, material, 4); + cb.ReleaseTemporaryRT(tileVRT); + cb.SetGlobalFloat(Uniforms._LoopCount, Mathf.Clamp(settings.sampleCount / 2, 1, 64)); + cb.SetGlobalTexture(Uniforms._MainTex, source); + cb.Blit(source, destination, material, 5); + cb.ReleaseTemporaryRT(velocityTex); + cb.ReleaseTemporaryRT(neighborMaxTex); + } + } + + public class FrameBlendingFilter + { + private struct Frame + { + public RenderTexture lumaTexture; + + public RenderTexture chromaTexture; + + private float m_Time; + + private RenderTargetIdentifier[] m_MRT; + + public float CalculateWeight(float strength, float currentTime) + { + if (Mathf.Approximately(m_Time, 0f)) + { + return 0f; + } + float num = Mathf.Lerp(80f, 16f, strength); + return Mathf.Exp((m_Time - currentTime) * num); + } + + public void Release() + { + if (lumaTexture != null) + { + RenderTexture.ReleaseTemporary(lumaTexture); + } + if (chromaTexture != null) + { + RenderTexture.ReleaseTemporary(chromaTexture); + } + lumaTexture = null; + chromaTexture = null; + } + + public void MakeRecord(CommandBuffer cb, RenderTargetIdentifier source, int width, int height, Material material) + { + Release(); + lumaTexture = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.R8, RenderTextureReadWrite.Linear); + chromaTexture = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.R8, RenderTextureReadWrite.Linear); + lumaTexture.filterMode = FilterMode.Point; + chromaTexture.filterMode = FilterMode.Point; + if (m_MRT == null) + { + m_MRT = new RenderTargetIdentifier[2]; + } + ref RenderTargetIdentifier reference = ref m_MRT[0]; + reference = lumaTexture; + ref RenderTargetIdentifier reference2 = ref m_MRT[1]; + reference2 = chromaTexture; + cb.SetGlobalTexture(Uniforms._MainTex, source); + cb.SetRenderTarget(m_MRT, lumaTexture); + cb.DrawMesh(GraphicsUtils.quad, Matrix4x4.identity, material, 0, 6); + m_Time = Time.time; + } + + public void MakeRecordRaw(CommandBuffer cb, RenderTargetIdentifier source, int width, int height, RenderTextureFormat format) + { + Release(); + lumaTexture = RenderTexture.GetTemporary(width, height, 0, format); + lumaTexture.filterMode = FilterMode.Point; + cb.SetGlobalTexture(Uniforms._MainTex, source); + cb.Blit(source, lumaTexture); + m_Time = Time.time; + } + } + + private bool m_UseCompression; + + private RenderTextureFormat m_RawTextureFormat; + + private Frame[] m_FrameList; + + private int m_LastFrameCount; + + public FrameBlendingFilter() + { + m_UseCompression = CheckSupportCompression(); + m_RawTextureFormat = GetPreferredRenderTextureFormat(); + m_FrameList = new Frame[4]; + } + + public void Dispose() + { + Frame[] frameList = m_FrameList; + foreach (Frame frame in frameList) + { + frame.Release(); + } + } + + public void PushFrame(CommandBuffer cb, RenderTargetIdentifier source, int width, int height, Material material) + { + int frameCount = Time.frameCount; + if (frameCount != m_LastFrameCount) + { + int num = frameCount % m_FrameList.Length; + if (m_UseCompression) + { + m_FrameList[num].MakeRecord(cb, source, width, height, material); + } + else + { + m_FrameList[num].MakeRecordRaw(cb, source, width, height, m_RawTextureFormat); + } + m_LastFrameCount = frameCount; + } + } + + public void BlendFrames(CommandBuffer cb, float strength, RenderTargetIdentifier source, RenderTargetIdentifier destination, Material material) + { + float time = Time.time; + Frame frameRelative = GetFrameRelative(-1); + Frame frameRelative2 = GetFrameRelative(-2); + Frame frameRelative3 = GetFrameRelative(-3); + Frame frameRelative4 = GetFrameRelative(-4); + cb.SetGlobalTexture(Uniforms._History1LumaTex, frameRelative.lumaTexture); + cb.SetGlobalTexture(Uniforms._History2LumaTex, frameRelative2.lumaTexture); + cb.SetGlobalTexture(Uniforms._History3LumaTex, frameRelative3.lumaTexture); + cb.SetGlobalTexture(Uniforms._History4LumaTex, frameRelative4.lumaTexture); + cb.SetGlobalTexture(Uniforms._History1ChromaTex, frameRelative.chromaTexture); + cb.SetGlobalTexture(Uniforms._History2ChromaTex, frameRelative2.chromaTexture); + cb.SetGlobalTexture(Uniforms._History3ChromaTex, frameRelative3.chromaTexture); + cb.SetGlobalTexture(Uniforms._History4ChromaTex, frameRelative4.chromaTexture); + cb.SetGlobalFloat(Uniforms._History1Weight, frameRelative.CalculateWeight(strength, time)); + cb.SetGlobalFloat(Uniforms._History2Weight, frameRelative2.CalculateWeight(strength, time)); + cb.SetGlobalFloat(Uniforms._History3Weight, frameRelative3.CalculateWeight(strength, time)); + cb.SetGlobalFloat(Uniforms._History4Weight, frameRelative4.CalculateWeight(strength, time)); + cb.SetGlobalTexture(Uniforms._MainTex, source); + cb.Blit(source, destination, material, (!m_UseCompression) ? 8 : 7); + } + + private static bool CheckSupportCompression() + { + return SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.R8) && SystemInfo.supportedRenderTargetCount > 1; + } + + private static RenderTextureFormat GetPreferredRenderTextureFormat() + { + RenderTextureFormat[] array = new RenderTextureFormat[3] + { + RenderTextureFormat.RGB565, + RenderTextureFormat.ARGB1555, + RenderTextureFormat.ARGB4444 + }; + RenderTextureFormat[] array2 = array; + foreach (RenderTextureFormat renderTextureFormat in array2) + { + if (SystemInfo.SupportsRenderTextureFormat(renderTextureFormat)) + { + return renderTextureFormat; + } + } + return RenderTextureFormat.Default; + } + + private Frame GetFrameRelative(int offset) + { + int num = (Time.frameCount + m_FrameList.Length + offset) % m_FrameList.Length; + return m_FrameList[num]; + } + } + + private ReconstructionFilter m_ReconstructionFilter; + + private FrameBlendingFilter m_FrameBlendingFilter; + + private bool m_FirstFrame = true; + + public ReconstructionFilter reconstructionFilter + { + get + { + if (m_ReconstructionFilter == null) + { + m_ReconstructionFilter = new ReconstructionFilter(); + } + return m_ReconstructionFilter; + } + } + + public FrameBlendingFilter frameBlendingFilter + { + get + { + if (m_FrameBlendingFilter == null) + { + m_FrameBlendingFilter = new FrameBlendingFilter(); + } + return m_FrameBlendingFilter; + } + } + + public override bool active + { + get + { + MotionBlurModel.Settings settings = base.model.settings; + return base.model.enabled && ((settings.shutterAngle > 0f && reconstructionFilter.IsSupported()) || settings.frameBlending > 0f) && SystemInfo.graphicsDeviceType != GraphicsDeviceType.OpenGLES2 && !context.interrupted; + } + } + + public override string GetName() + { + return "Motion Blur"; + } + + public void ResetHistory() + { + if (m_FrameBlendingFilter != null) + { + m_FrameBlendingFilter.Dispose(); + } + m_FrameBlendingFilter = null; + } + + public override DepthTextureMode GetCameraFlags() + { + return DepthTextureMode.Depth | DepthTextureMode.MotionVectors; + } + + public override CameraEvent GetCameraEvent() + { + return CameraEvent.BeforeImageEffects; + } + + public override void OnEnable() + { + m_FirstFrame = true; + } + + public override void PopulateCommandBuffer(CommandBuffer cb) + { + if (m_FirstFrame) + { + m_FirstFrame = false; + return; + } + Material material = context.materialFactory.Get("Hidden/Post FX/Motion Blur"); + Material mat = context.materialFactory.Get("Hidden/Post FX/Blit"); + MotionBlurModel.Settings settings = base.model.settings; + RenderTextureFormat format = ((!context.isHdr) ? RenderTextureFormat.Default : RenderTextureFormat.DefaultHDR); + int tempRT = Uniforms._TempRT; + cb.GetTemporaryRT(tempRT, context.width, context.height, 0, FilterMode.Point, format); + if (settings.shutterAngle > 0f && settings.frameBlending > 0f) + { + reconstructionFilter.ProcessImage(context, cb, ref settings, BuiltinRenderTextureType.CameraTarget, tempRT, material); + frameBlendingFilter.BlendFrames(cb, settings.frameBlending, tempRT, BuiltinRenderTextureType.CameraTarget, material); + frameBlendingFilter.PushFrame(cb, tempRT, context.width, context.height, material); + } + else if (settings.shutterAngle > 0f) + { + cb.SetGlobalTexture(Uniforms._MainTex, BuiltinRenderTextureType.CameraTarget); + cb.Blit(BuiltinRenderTextureType.CameraTarget, tempRT, mat, 0); + reconstructionFilter.ProcessImage(context, cb, ref settings, tempRT, BuiltinRenderTextureType.CameraTarget, material); + } + else if (settings.frameBlending > 0f) + { + cb.SetGlobalTexture(Uniforms._MainTex, BuiltinRenderTextureType.CameraTarget); + cb.Blit(BuiltinRenderTextureType.CameraTarget, tempRT, mat, 0); + frameBlendingFilter.BlendFrames(cb, settings.frameBlending, tempRT, BuiltinRenderTextureType.CameraTarget, material); + frameBlendingFilter.PushFrame(cb, tempRT, context.width, context.height, material); + } + cb.ReleaseTemporaryRT(tempRT); + } + + public override void OnDisable() + { + if (m_FrameBlendingFilter != null) + { + m_FrameBlendingFilter.Dispose(); + } + } +} diff --git a/UnityEngine.PostProcessing/MotionBlurModel.cs b/UnityEngine.PostProcessing/MotionBlurModel.cs new file mode 100644 index 0000000..5b0a996 --- /dev/null +++ b/UnityEngine.PostProcessing/MotionBlurModel.cs @@ -0,0 +1,55 @@ +using System; + +namespace UnityEngine.PostProcessing; + +[Serializable] +public class MotionBlurModel : PostProcessingModel +{ + [Serializable] + public struct Settings + { + [Range(0f, 360f)] + [Tooltip("The angle of rotary shutter. Larger values give longer exposure.")] + public float shutterAngle; + + [Range(4f, 32f)] + [Tooltip("The amount of sample points, which affects quality and performances.")] + public int sampleCount; + + [Range(0f, 1f)] + [Tooltip("The strength of multiple frame blending. The opacity of preceding frames are determined from this coefficient and time differences.")] + public float frameBlending; + + public static Settings defaultSettings + { + get + { + Settings result = default(Settings); + result.shutterAngle = 270f; + result.sampleCount = 10; + result.frameBlending = 0f; + return result; + } + } + } + + [SerializeField] + private Settings m_Settings = Settings.defaultSettings; + + public Settings settings + { + get + { + return m_Settings; + } + set + { + m_Settings = value; + } + } + + public override void Reset() + { + m_Settings = Settings.defaultSettings; + } +} diff --git a/UnityEngine.PostProcessing/PostProcessingBehaviour.cs b/UnityEngine.PostProcessing/PostProcessingBehaviour.cs new file mode 100644 index 0000000..d99d027 --- /dev/null +++ b/UnityEngine.PostProcessing/PostProcessingBehaviour.cs @@ -0,0 +1,405 @@ +using System; +using System.Collections.Generic; +using UnityEngine.Rendering; + +namespace UnityEngine.PostProcessing; + +[ImageEffectAllowedInSceneView] +[RequireComponent(typeof(Camera))] +[DisallowMultipleComponent] +[ExecuteInEditMode] +[AddComponentMenu("Effects/Post-Processing Behaviour", -1)] +public class PostProcessingBehaviour : MonoBehaviour +{ + public PostProcessingProfile profile; + + public Func<Vector2, Matrix4x4> jitteredMatrixFunc; + + private Dictionary<Type, KeyValuePair<CameraEvent, CommandBuffer>> m_CommandBuffers; + + private List<PostProcessingComponentBase> m_Components; + + private Dictionary<PostProcessingComponentBase, bool> m_ComponentStates; + + private MaterialFactory m_MaterialFactory; + + private RenderTextureFactory m_RenderTextureFactory; + + private PostProcessingContext m_Context; + + private Camera m_Camera; + + private PostProcessingProfile m_PreviousProfile; + + private bool m_RenderingInSceneView; + + private BuiltinDebugViewsComponent m_DebugViews; + + private AmbientOcclusionComponent m_AmbientOcclusion; + + private ScreenSpaceReflectionComponent m_ScreenSpaceReflection; + + private FogComponent m_FogComponent; + + private MotionBlurComponent m_MotionBlur; + + private TaaComponent m_Taa; + + private EyeAdaptationComponent m_EyeAdaptation; + + private DepthOfFieldComponent m_DepthOfField; + + private BloomComponent m_Bloom; + + private ChromaticAberrationComponent m_ChromaticAberration; + + private ColorGradingComponent m_ColorGrading; + + private UserLutComponent m_UserLut; + + private GrainComponent m_Grain; + + private VignetteComponent m_Vignette; + + private DitheringComponent m_Dithering; + + private FxaaComponent m_Fxaa; + + private List<PostProcessingComponentBase> m_ComponentsToEnable = new List<PostProcessingComponentBase>(); + + private List<PostProcessingComponentBase> m_ComponentsToDisable = new List<PostProcessingComponentBase>(); + + private void OnEnable() + { + m_CommandBuffers = new Dictionary<Type, KeyValuePair<CameraEvent, CommandBuffer>>(); + m_MaterialFactory = new MaterialFactory(); + m_RenderTextureFactory = new RenderTextureFactory(); + m_Context = new PostProcessingContext(); + m_Components = new List<PostProcessingComponentBase>(); + m_DebugViews = AddComponent(new BuiltinDebugViewsComponent()); + m_AmbientOcclusion = AddComponent(new AmbientOcclusionComponent()); + m_ScreenSpaceReflection = AddComponent(new ScreenSpaceReflectionComponent()); + m_FogComponent = AddComponent(new FogComponent()); + m_MotionBlur = AddComponent(new MotionBlurComponent()); + m_Taa = AddComponent(new TaaComponent()); + m_EyeAdaptation = AddComponent(new EyeAdaptationComponent()); + m_DepthOfField = AddComponent(new DepthOfFieldComponent()); + m_Bloom = AddComponent(new BloomComponent()); + m_ChromaticAberration = AddComponent(new ChromaticAberrationComponent()); + m_ColorGrading = AddComponent(new ColorGradingComponent()); + m_UserLut = AddComponent(new UserLutComponent()); + m_Grain = AddComponent(new GrainComponent()); + m_Vignette = AddComponent(new VignetteComponent()); + m_Dithering = AddComponent(new DitheringComponent()); + m_Fxaa = AddComponent(new FxaaComponent()); + m_ComponentStates = new Dictionary<PostProcessingComponentBase, bool>(); + foreach (PostProcessingComponentBase component in m_Components) + { + m_ComponentStates.Add(component, value: false); + } + base.useGUILayout = false; + } + + private void OnPreCull() + { + m_Camera = GetComponent<Camera>(); + if (profile == null || m_Camera == null) + { + return; + } + PostProcessingContext postProcessingContext = m_Context.Reset(); + postProcessingContext.profile = profile; + postProcessingContext.renderTextureFactory = m_RenderTextureFactory; + postProcessingContext.materialFactory = m_MaterialFactory; + postProcessingContext.camera = m_Camera; + m_DebugViews.Init(postProcessingContext, profile.debugViews); + m_AmbientOcclusion.Init(postProcessingContext, profile.ambientOcclusion); + m_ScreenSpaceReflection.Init(postProcessingContext, profile.screenSpaceReflection); + m_FogComponent.Init(postProcessingContext, profile.fog); + m_MotionBlur.Init(postProcessingContext, profile.motionBlur); + m_Taa.Init(postProcessingContext, profile.antialiasing); + m_EyeAdaptation.Init(postProcessingContext, profile.eyeAdaptation); + m_DepthOfField.Init(postProcessingContext, profile.depthOfField); + m_Bloom.Init(postProcessingContext, profile.bloom); + m_ChromaticAberration.Init(postProcessingContext, profile.chromaticAberration); + m_ColorGrading.Init(postProcessingContext, profile.colorGrading); + m_UserLut.Init(postProcessingContext, profile.userLut); + m_Grain.Init(postProcessingContext, profile.grain); + m_Vignette.Init(postProcessingContext, profile.vignette); + m_Dithering.Init(postProcessingContext, profile.dithering); + m_Fxaa.Init(postProcessingContext, profile.antialiasing); + if (m_PreviousProfile != profile) + { + DisableComponents(); + m_PreviousProfile = profile; + } + CheckObservers(); + DepthTextureMode depthTextureMode = postProcessingContext.camera.depthTextureMode; + foreach (PostProcessingComponentBase component in m_Components) + { + if (component.active) + { + depthTextureMode |= component.GetCameraFlags(); + } + } + postProcessingContext.camera.depthTextureMode = depthTextureMode; + if (!m_RenderingInSceneView && m_Taa.active && !profile.debugViews.willInterrupt) + { + m_Taa.SetProjectionMatrix(jitteredMatrixFunc); + } + } + + private void OnPreRender() + { + if (!(profile == null)) + { + TryExecuteCommandBuffer(m_DebugViews); + TryExecuteCommandBuffer(m_AmbientOcclusion); + TryExecuteCommandBuffer(m_ScreenSpaceReflection); + TryExecuteCommandBuffer(m_FogComponent); + if (!m_RenderingInSceneView) + { + TryExecuteCommandBuffer(m_MotionBlur); + } + } + } + + private void OnPostRender() + { + if (!(profile == null) && !(m_Camera == null) && !m_RenderingInSceneView && m_Taa.active && !profile.debugViews.willInterrupt) + { + m_Context.camera.ResetProjectionMatrix(); + } + } + + private void OnRenderImage(RenderTexture source, RenderTexture destination) + { + if (profile == null || m_Camera == null) + { + Graphics.Blit(source, destination); + return; + } + bool flag = false; + bool active = m_Fxaa.active; + bool flag2 = m_Taa.active && !m_RenderingInSceneView; + bool flag3 = m_DepthOfField.active && !m_RenderingInSceneView; + Material material = m_MaterialFactory.Get("Hidden/Post FX/Uber Shader"); + material.shaderKeywords = null; + RenderTexture renderTexture = source; + if (flag2) + { + RenderTexture renderTexture2 = m_RenderTextureFactory.Get(renderTexture); + m_Taa.Render(renderTexture, renderTexture2); + renderTexture = renderTexture2; + } + Texture texture = GraphicsUtils.whiteTexture; + if (m_EyeAdaptation.active) + { + flag = true; + texture = m_EyeAdaptation.Prepare(renderTexture, material); + } + material.SetTexture("_AutoExposure", texture); + if (flag3) + { + flag = true; + m_DepthOfField.Prepare(renderTexture, material, flag2, m_Taa.jitterVector, m_Taa.model.settings.taaSettings.motionBlending); + } + if (m_Bloom.active) + { + flag = true; + m_Bloom.Prepare(renderTexture, material, texture); + } + flag |= TryPrepareUberImageEffect(m_ChromaticAberration, material); + flag |= TryPrepareUberImageEffect(m_ColorGrading, material); + flag |= TryPrepareUberImageEffect(m_Vignette, material); + flag |= TryPrepareUberImageEffect(m_UserLut, material); + Material material2 = ((!active) ? null : m_MaterialFactory.Get("Hidden/Post FX/FXAA")); + if (active) + { + material2.shaderKeywords = null; + TryPrepareUberImageEffect(m_Grain, material2); + TryPrepareUberImageEffect(m_Dithering, material2); + if (flag) + { + RenderTexture renderTexture3 = m_RenderTextureFactory.Get(renderTexture); + Graphics.Blit(renderTexture, renderTexture3, material, 0); + renderTexture = renderTexture3; + } + m_Fxaa.Render(renderTexture, destination); + } + else + { + flag |= TryPrepareUberImageEffect(m_Grain, material); + flag |= TryPrepareUberImageEffect(m_Dithering, material); + if (flag) + { + if (!GraphicsUtils.isLinearColorSpace) + { + material.EnableKeyword("UNITY_COLORSPACE_GAMMA"); + } + Graphics.Blit(renderTexture, destination, material, 0); + } + } + if (!flag && !active) + { + Graphics.Blit(renderTexture, destination); + } + m_RenderTextureFactory.ReleaseAll(); + } + + private void OnGUI() + { + if (Event.current.type == EventType.Repaint && !(profile == null) && !(m_Camera == null)) + { + if (m_EyeAdaptation.active && profile.debugViews.IsModeActive(BuiltinDebugViewsModel.Mode.EyeAdaptation)) + { + m_EyeAdaptation.OnGUI(); + } + else if (m_ColorGrading.active && profile.debugViews.IsModeActive(BuiltinDebugViewsModel.Mode.LogLut)) + { + m_ColorGrading.OnGUI(); + } + else if (m_UserLut.active && profile.debugViews.IsModeActive(BuiltinDebugViewsModel.Mode.UserLut)) + { + m_UserLut.OnGUI(); + } + } + } + + private void OnDisable() + { + foreach (KeyValuePair<CameraEvent, CommandBuffer> value in m_CommandBuffers.Values) + { + m_Camera.RemoveCommandBuffer(value.Key, value.Value); + value.Value.Dispose(); + } + m_CommandBuffers.Clear(); + if (profile != null) + { + DisableComponents(); + } + m_Components.Clear(); + m_MaterialFactory.Dispose(); + m_RenderTextureFactory.Dispose(); + GraphicsUtils.Dispose(); + } + + public void ResetTemporalEffects() + { + m_Taa.ResetHistory(); + m_MotionBlur.ResetHistory(); + m_EyeAdaptation.ResetHistory(); + } + + private void CheckObservers() + { + foreach (KeyValuePair<PostProcessingComponentBase, bool> componentState in m_ComponentStates) + { + PostProcessingComponentBase key = componentState.Key; + bool flag = key.GetModel().enabled; + if (flag != componentState.Value) + { + if (flag) + { + m_ComponentsToEnable.Add(key); + } + else + { + m_ComponentsToDisable.Add(key); + } + } + } + for (int i = 0; i < m_ComponentsToDisable.Count; i++) + { + PostProcessingComponentBase postProcessingComponentBase = m_ComponentsToDisable[i]; + m_ComponentStates[postProcessingComponentBase] = false; + postProcessingComponentBase.OnDisable(); + } + for (int j = 0; j < m_ComponentsToEnable.Count; j++) + { + PostProcessingComponentBase postProcessingComponentBase2 = m_ComponentsToEnable[j]; + m_ComponentStates[postProcessingComponentBase2] = true; + postProcessingComponentBase2.OnEnable(); + } + m_ComponentsToDisable.Clear(); + m_ComponentsToEnable.Clear(); + } + + private void DisableComponents() + { + foreach (PostProcessingComponentBase component in m_Components) + { + PostProcessingModel model = component.GetModel(); + if (model != null && model.enabled) + { + component.OnDisable(); + } + } + } + + private CommandBuffer AddCommandBuffer<T>(CameraEvent evt, string name) where T : PostProcessingModel + { + CommandBuffer commandBuffer = new CommandBuffer(); + commandBuffer.name = name; + CommandBuffer value = commandBuffer; + KeyValuePair<CameraEvent, CommandBuffer> value2 = new KeyValuePair<CameraEvent, CommandBuffer>(evt, value); + m_CommandBuffers.Add(typeof(T), value2); + m_Camera.AddCommandBuffer(evt, value2.Value); + return value2.Value; + } + + private void RemoveCommandBuffer<T>() where T : PostProcessingModel + { + Type typeFromHandle = typeof(T); + if (m_CommandBuffers.TryGetValue(typeFromHandle, out var value)) + { + m_Camera.RemoveCommandBuffer(value.Key, value.Value); + m_CommandBuffers.Remove(typeFromHandle); + value.Value.Dispose(); + } + } + + private CommandBuffer GetCommandBuffer<T>(CameraEvent evt, string name) where T : PostProcessingModel + { + if (!m_CommandBuffers.TryGetValue(typeof(T), out var value)) + { + return AddCommandBuffer<T>(evt, name); + } + if (value.Key != evt) + { + RemoveCommandBuffer<T>(); + return AddCommandBuffer<T>(evt, name); + } + return value.Value; + } + + private void TryExecuteCommandBuffer<T>(PostProcessingComponentCommandBuffer<T> component) where T : PostProcessingModel + { + if (component.active) + { + CommandBuffer commandBuffer = GetCommandBuffer<T>(component.GetCameraEvent(), component.GetName()); + commandBuffer.Clear(); + component.PopulateCommandBuffer(commandBuffer); + } + else + { + RemoveCommandBuffer<T>(); + } + } + + private bool TryPrepareUberImageEffect<T>(PostProcessingComponentRenderTexture<T> component, Material material) where T : PostProcessingModel + { + if (!component.active) + { + return false; + } + component.Prepare(material); + return true; + } + + private T AddComponent<T>(T component) where T : PostProcessingComponentBase + { + m_Components.Add(component); + return component; + } +} diff --git a/UnityEngine.PostProcessing/PostProcessingComponent.cs b/UnityEngine.PostProcessing/PostProcessingComponent.cs new file mode 100644 index 0000000..08c2ba7 --- /dev/null +++ b/UnityEngine.PostProcessing/PostProcessingComponent.cs @@ -0,0 +1,17 @@ +namespace UnityEngine.PostProcessing; + +public abstract class PostProcessingComponent<T> : PostProcessingComponentBase where T : PostProcessingModel +{ + public T model { get; internal set; } + + public virtual void Init(PostProcessingContext pcontext, T pmodel) + { + context = pcontext; + model = pmodel; + } + + public override PostProcessingModel GetModel() + { + return model; + } +} diff --git a/UnityEngine.PostProcessing/PostProcessingComponentBase.cs b/UnityEngine.PostProcessing/PostProcessingComponentBase.cs new file mode 100644 index 0000000..491f371 --- /dev/null +++ b/UnityEngine.PostProcessing/PostProcessingComponentBase.cs @@ -0,0 +1,23 @@ +namespace UnityEngine.PostProcessing; + +public abstract class PostProcessingComponentBase +{ + public PostProcessingContext context; + + public abstract bool active { get; } + + public virtual DepthTextureMode GetCameraFlags() + { + return DepthTextureMode.None; + } + + public virtual void OnEnable() + { + } + + public virtual void OnDisable() + { + } + + public abstract PostProcessingModel GetModel(); +} diff --git a/UnityEngine.PostProcessing/PostProcessingComponentCommandBuffer.cs b/UnityEngine.PostProcessing/PostProcessingComponentCommandBuffer.cs new file mode 100644 index 0000000..a8a9408 --- /dev/null +++ b/UnityEngine.PostProcessing/PostProcessingComponentCommandBuffer.cs @@ -0,0 +1,12 @@ +using UnityEngine.Rendering; + +namespace UnityEngine.PostProcessing; + +public abstract class PostProcessingComponentCommandBuffer<T> : PostProcessingComponent<T> where T : PostProcessingModel +{ + public abstract CameraEvent GetCameraEvent(); + + public abstract string GetName(); + + public abstract void PopulateCommandBuffer(CommandBuffer cb); +} diff --git a/UnityEngine.PostProcessing/PostProcessingComponentRenderTexture.cs b/UnityEngine.PostProcessing/PostProcessingComponentRenderTexture.cs new file mode 100644 index 0000000..8284bb2 --- /dev/null +++ b/UnityEngine.PostProcessing/PostProcessingComponentRenderTexture.cs @@ -0,0 +1,8 @@ +namespace UnityEngine.PostProcessing; + +public abstract class PostProcessingComponentRenderTexture<T> : PostProcessingComponent<T> where T : PostProcessingModel +{ + public virtual void Prepare(Material material) + { + } +} diff --git a/UnityEngine.PostProcessing/PostProcessingContext.cs b/UnityEngine.PostProcessing/PostProcessingContext.cs new file mode 100644 index 0000000..ab810a1 --- /dev/null +++ b/UnityEngine.PostProcessing/PostProcessingContext.cs @@ -0,0 +1,39 @@ +namespace UnityEngine.PostProcessing; + +public class PostProcessingContext +{ + public PostProcessingProfile profile; + + public Camera camera; + + public MaterialFactory materialFactory; + + public RenderTextureFactory renderTextureFactory; + + public bool interrupted { get; private set; } + + public bool isGBufferAvailable => camera.actualRenderingPath == RenderingPath.DeferredShading; + + public bool isHdr => camera.allowHDR; + + public int width => camera.pixelWidth; + + public int height => camera.pixelHeight; + + public Rect viewport => camera.rect; + + public void Interrupt() + { + interrupted = true; + } + + public PostProcessingContext Reset() + { + profile = null; + camera = null; + materialFactory = null; + renderTextureFactory = null; + interrupted = false; + return this; + } +} diff --git a/UnityEngine.PostProcessing/PostProcessingModel.cs b/UnityEngine.PostProcessing/PostProcessingModel.cs new file mode 100644 index 0000000..986b42b --- /dev/null +++ b/UnityEngine.PostProcessing/PostProcessingModel.cs @@ -0,0 +1,33 @@ +using System; + +namespace UnityEngine.PostProcessing; + +[Serializable] +public abstract class PostProcessingModel +{ + [SerializeField] + [GetSet("enabled")] + private bool m_Enabled; + + public bool enabled + { + get + { + return m_Enabled; + } + set + { + m_Enabled = value; + if (value) + { + OnValidate(); + } + } + } + + public abstract void Reset(); + + public virtual void OnValidate() + { + } +} diff --git a/UnityEngine.PostProcessing/PostProcessingProfile.cs b/UnityEngine.PostProcessing/PostProcessingProfile.cs new file mode 100644 index 0000000..3c847b3 --- /dev/null +++ b/UnityEngine.PostProcessing/PostProcessingProfile.cs @@ -0,0 +1,34 @@ +namespace UnityEngine.PostProcessing; + +public class PostProcessingProfile : ScriptableObject +{ + public BuiltinDebugViewsModel debugViews = new BuiltinDebugViewsModel(); + + public FogModel fog = new FogModel(); + + public AntialiasingModel antialiasing = new AntialiasingModel(); + + public AmbientOcclusionModel ambientOcclusion = new AmbientOcclusionModel(); + + public ScreenSpaceReflectionModel screenSpaceReflection = new ScreenSpaceReflectionModel(); + + public DepthOfFieldModel depthOfField = new DepthOfFieldModel(); + + public MotionBlurModel motionBlur = new MotionBlurModel(); + + public EyeAdaptationModel eyeAdaptation = new EyeAdaptationModel(); + + public BloomModel bloom = new BloomModel(); + + public ColorGradingModel colorGrading = new ColorGradingModel(); + + public UserLutModel userLut = new UserLutModel(); + + public ChromaticAberrationModel chromaticAberration = new ChromaticAberrationModel(); + + public GrainModel grain = new GrainModel(); + + public VignetteModel vignette = new VignetteModel(); + + public DitheringModel dithering = new DitheringModel(); +} diff --git a/UnityEngine.PostProcessing/RenderTextureFactory.cs b/UnityEngine.PostProcessing/RenderTextureFactory.cs new file mode 100644 index 0000000..51d9f15 --- /dev/null +++ b/UnityEngine.PostProcessing/RenderTextureFactory.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; + +namespace UnityEngine.PostProcessing; + +public sealed class RenderTextureFactory : IDisposable +{ + private HashSet<RenderTexture> m_TemporaryRTs; + + public RenderTextureFactory() + { + m_TemporaryRTs = new HashSet<RenderTexture>(); + } + + public RenderTexture Get(RenderTexture baseRenderTexture) + { + return Get(baseRenderTexture.width, baseRenderTexture.height, baseRenderTexture.depth, baseRenderTexture.format, (!baseRenderTexture.sRGB) ? RenderTextureReadWrite.Linear : RenderTextureReadWrite.sRGB, baseRenderTexture.filterMode, baseRenderTexture.wrapMode); + } + + public RenderTexture Get(int width, int height, int depthBuffer = 0, RenderTextureFormat format = RenderTextureFormat.ARGBHalf, RenderTextureReadWrite rw = RenderTextureReadWrite.Default, FilterMode filterMode = FilterMode.Bilinear, TextureWrapMode wrapMode = TextureWrapMode.Clamp, string name = "FactoryTempTexture") + { + RenderTexture temporary = RenderTexture.GetTemporary(width, height, depthBuffer, format, rw); + temporary.filterMode = filterMode; + temporary.wrapMode = wrapMode; + temporary.name = name; + m_TemporaryRTs.Add(temporary); + return temporary; + } + + public void Release(RenderTexture rt) + { + if (!(rt == null)) + { + if (!m_TemporaryRTs.Contains(rt)) + { + throw new ArgumentException($"Attempting to remove a RenderTexture that was not allocated: {rt}"); + } + m_TemporaryRTs.Remove(rt); + RenderTexture.ReleaseTemporary(rt); + } + } + + public void ReleaseAll() + { + HashSet<RenderTexture>.Enumerator enumerator = m_TemporaryRTs.GetEnumerator(); + while (enumerator.MoveNext()) + { + RenderTexture.ReleaseTemporary(enumerator.Current); + } + m_TemporaryRTs.Clear(); + } + + public void Dispose() + { + ReleaseAll(); + } +} diff --git a/UnityEngine.PostProcessing/ScreenSpaceReflectionComponent.cs b/UnityEngine.PostProcessing/ScreenSpaceReflectionComponent.cs new file mode 100644 index 0000000..e9f0c02 --- /dev/null +++ b/UnityEngine.PostProcessing/ScreenSpaceReflectionComponent.cs @@ -0,0 +1,217 @@ +using System; +using UnityEngine.Rendering; + +namespace UnityEngine.PostProcessing; + +public sealed class ScreenSpaceReflectionComponent : PostProcessingComponentCommandBuffer<ScreenSpaceReflectionModel> +{ + private static class Uniforms + { + internal static readonly int _RayStepSize = Shader.PropertyToID("_RayStepSize"); + + internal static readonly int _AdditiveReflection = Shader.PropertyToID("_AdditiveReflection"); + + internal static readonly int _BilateralUpsampling = Shader.PropertyToID("_BilateralUpsampling"); + + internal static readonly int _TreatBackfaceHitAsMiss = Shader.PropertyToID("_TreatBackfaceHitAsMiss"); + + internal static readonly int _AllowBackwardsRays = Shader.PropertyToID("_AllowBackwardsRays"); + + internal static readonly int _TraceBehindObjects = Shader.PropertyToID("_TraceBehindObjects"); + + internal static readonly int _MaxSteps = Shader.PropertyToID("_MaxSteps"); + + internal static readonly int _FullResolutionFiltering = Shader.PropertyToID("_FullResolutionFiltering"); + + internal static readonly int _HalfResolution = Shader.PropertyToID("_HalfResolution"); + + internal static readonly int _HighlightSuppression = Shader.PropertyToID("_HighlightSuppression"); + + internal static readonly int _PixelsPerMeterAtOneMeter = Shader.PropertyToID("_PixelsPerMeterAtOneMeter"); + + internal static readonly int _ScreenEdgeFading = Shader.PropertyToID("_ScreenEdgeFading"); + + internal static readonly int _ReflectionBlur = Shader.PropertyToID("_ReflectionBlur"); + + internal static readonly int _MaxRayTraceDistance = Shader.PropertyToID("_MaxRayTraceDistance"); + + internal static readonly int _FadeDistance = Shader.PropertyToID("_FadeDistance"); + + internal static readonly int _LayerThickness = Shader.PropertyToID("_LayerThickness"); + + internal static readonly int _SSRMultiplier = Shader.PropertyToID("_SSRMultiplier"); + + internal static readonly int _FresnelFade = Shader.PropertyToID("_FresnelFade"); + + internal static readonly int _FresnelFadePower = Shader.PropertyToID("_FresnelFadePower"); + + internal static readonly int _ReflectionBufferSize = Shader.PropertyToID("_ReflectionBufferSize"); + + internal static readonly int _ScreenSize = Shader.PropertyToID("_ScreenSize"); + + internal static readonly int _InvScreenSize = Shader.PropertyToID("_InvScreenSize"); + + internal static readonly int _ProjInfo = Shader.PropertyToID("_ProjInfo"); + + internal static readonly int _CameraClipInfo = Shader.PropertyToID("_CameraClipInfo"); + + internal static readonly int _ProjectToPixelMatrix = Shader.PropertyToID("_ProjectToPixelMatrix"); + + internal static readonly int _WorldToCameraMatrix = Shader.PropertyToID("_WorldToCameraMatrix"); + + internal static readonly int _CameraToWorldMatrix = Shader.PropertyToID("_CameraToWorldMatrix"); + + internal static readonly int _Axis = Shader.PropertyToID("_Axis"); + + internal static readonly int _CurrentMipLevel = Shader.PropertyToID("_CurrentMipLevel"); + + internal static readonly int _NormalAndRoughnessTexture = Shader.PropertyToID("_NormalAndRoughnessTexture"); + + internal static readonly int _HitPointTexture = Shader.PropertyToID("_HitPointTexture"); + + internal static readonly int _BlurTexture = Shader.PropertyToID("_BlurTexture"); + + internal static readonly int _FilteredReflections = Shader.PropertyToID("_FilteredReflections"); + + internal static readonly int _FinalReflectionTexture = Shader.PropertyToID("_FinalReflectionTexture"); + + internal static readonly int _TempTexture = Shader.PropertyToID("_TempTexture"); + } + + private enum PassIndex + { + RayTraceStep, + CompositeFinal, + Blur, + CompositeSSR, + MinMipGeneration, + HitPointToReflections, + BilateralKeyPack, + BlitDepthAsCSZ, + PoissonBlur + } + + private bool k_HighlightSuppression; + + private bool k_TraceBehindObjects = true; + + private bool k_TreatBackfaceHitAsMiss; + + private bool k_BilateralUpsample = true; + + private readonly int[] m_ReflectionTextures = new int[5]; + + public override bool active => base.model.enabled && context.isGBufferAvailable && !context.interrupted; + + public override DepthTextureMode GetCameraFlags() + { + return DepthTextureMode.Depth; + } + + public override void OnEnable() + { + m_ReflectionTextures[0] = Shader.PropertyToID("_ReflectionTexture0"); + m_ReflectionTextures[1] = Shader.PropertyToID("_ReflectionTexture1"); + m_ReflectionTextures[2] = Shader.PropertyToID("_ReflectionTexture2"); + m_ReflectionTextures[3] = Shader.PropertyToID("_ReflectionTexture3"); + m_ReflectionTextures[4] = Shader.PropertyToID("_ReflectionTexture4"); + } + + public override string GetName() + { + return "Screen Space Reflection"; + } + + public override CameraEvent GetCameraEvent() + { + return CameraEvent.AfterFinalPass; + } + + public override void PopulateCommandBuffer(CommandBuffer cb) + { + ScreenSpaceReflectionModel.Settings settings = base.model.settings; + Camera camera = context.camera; + int num = ((settings.reflection.reflectionQuality == ScreenSpaceReflectionModel.SSRResolution.High) ? 1 : 2); + int num2 = context.width / num; + int num3 = context.height / num; + float num4 = context.width; + float num5 = context.height; + float num6 = num4 / 2f; + float num7 = num5 / 2f; + Material material = context.materialFactory.Get("Hidden/Post FX/Screen Space Reflection"); + material.SetInt(Uniforms._RayStepSize, settings.reflection.stepSize); + material.SetInt(Uniforms._AdditiveReflection, (settings.reflection.blendType == ScreenSpaceReflectionModel.SSRReflectionBlendType.Additive) ? 1 : 0); + material.SetInt(Uniforms._BilateralUpsampling, k_BilateralUpsample ? 1 : 0); + material.SetInt(Uniforms._TreatBackfaceHitAsMiss, k_TreatBackfaceHitAsMiss ? 1 : 0); + material.SetInt(Uniforms._AllowBackwardsRays, settings.reflection.reflectBackfaces ? 1 : 0); + material.SetInt(Uniforms._TraceBehindObjects, k_TraceBehindObjects ? 1 : 0); + material.SetInt(Uniforms._MaxSteps, settings.reflection.iterationCount); + material.SetInt(Uniforms._FullResolutionFiltering, 0); + material.SetInt(Uniforms._HalfResolution, (settings.reflection.reflectionQuality != 0) ? 1 : 0); + material.SetInt(Uniforms._HighlightSuppression, k_HighlightSuppression ? 1 : 0); + float value = num4 / (-2f * Mathf.Tan(camera.fieldOfView / 180f * (float)Math.PI * 0.5f)); + material.SetFloat(Uniforms._PixelsPerMeterAtOneMeter, value); + material.SetFloat(Uniforms._ScreenEdgeFading, settings.screenEdgeMask.intensity); + material.SetFloat(Uniforms._ReflectionBlur, settings.reflection.reflectionBlur); + material.SetFloat(Uniforms._MaxRayTraceDistance, settings.reflection.maxDistance); + material.SetFloat(Uniforms._FadeDistance, settings.intensity.fadeDistance); + material.SetFloat(Uniforms._LayerThickness, settings.reflection.widthModifier); + material.SetFloat(Uniforms._SSRMultiplier, settings.intensity.reflectionMultiplier); + material.SetFloat(Uniforms._FresnelFade, settings.intensity.fresnelFade); + material.SetFloat(Uniforms._FresnelFadePower, settings.intensity.fresnelFadePower); + Matrix4x4 projectionMatrix = camera.projectionMatrix; + Vector4 value2 = new Vector4(-2f / (num4 * projectionMatrix[0]), -2f / (num5 * projectionMatrix[5]), (1f - projectionMatrix[2]) / projectionMatrix[0], (1f + projectionMatrix[6]) / projectionMatrix[5]); + Vector3 vector = ((!float.IsPositiveInfinity(camera.farClipPlane)) ? new Vector3(camera.nearClipPlane * camera.farClipPlane, camera.nearClipPlane - camera.farClipPlane, camera.farClipPlane) : new Vector3(camera.nearClipPlane, -1f, 1f)); + material.SetVector(Uniforms._ReflectionBufferSize, new Vector2(num2, num3)); + material.SetVector(Uniforms._ScreenSize, new Vector2(num4, num5)); + material.SetVector(Uniforms._InvScreenSize, new Vector2(1f / num4, 1f / num5)); + material.SetVector(Uniforms._ProjInfo, value2); + material.SetVector(Uniforms._CameraClipInfo, vector); + Matrix4x4 matrix4x = default(Matrix4x4); + matrix4x.SetRow(0, new Vector4(num6, 0f, 0f, num6)); + matrix4x.SetRow(1, new Vector4(0f, num7, 0f, num7)); + matrix4x.SetRow(2, new Vector4(0f, 0f, 1f, 0f)); + matrix4x.SetRow(3, new Vector4(0f, 0f, 0f, 1f)); + Matrix4x4 value3 = matrix4x * projectionMatrix; + material.SetMatrix(Uniforms._ProjectToPixelMatrix, value3); + material.SetMatrix(Uniforms._WorldToCameraMatrix, camera.worldToCameraMatrix); + material.SetMatrix(Uniforms._CameraToWorldMatrix, camera.worldToCameraMatrix.inverse); + RenderTextureFormat format = (context.isHdr ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32); + int normalAndRoughnessTexture = Uniforms._NormalAndRoughnessTexture; + int hitPointTexture = Uniforms._HitPointTexture; + int blurTexture = Uniforms._BlurTexture; + int filteredReflections = Uniforms._FilteredReflections; + int finalReflectionTexture = Uniforms._FinalReflectionTexture; + int tempTexture = Uniforms._TempTexture; + cb.GetTemporaryRT(normalAndRoughnessTexture, -1, -1, 0, FilterMode.Point, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); + cb.GetTemporaryRT(hitPointTexture, num2, num3, 0, FilterMode.Bilinear, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear); + for (int i = 0; i < 5; i++) + { + cb.GetTemporaryRT(m_ReflectionTextures[i], num2 >> i, num3 >> i, 0, FilterMode.Bilinear, format); + } + cb.GetTemporaryRT(filteredReflections, num2, num3, 0, (!k_BilateralUpsample) ? FilterMode.Bilinear : FilterMode.Point, format); + cb.GetTemporaryRT(finalReflectionTexture, num2, num3, 0, FilterMode.Point, format); + cb.Blit(BuiltinRenderTextureType.CameraTarget, normalAndRoughnessTexture, material, 6); + cb.Blit(BuiltinRenderTextureType.CameraTarget, hitPointTexture, material, 0); + cb.Blit(BuiltinRenderTextureType.CameraTarget, filteredReflections, material, 5); + cb.Blit(filteredReflections, m_ReflectionTextures[0], material, 8); + for (int j = 1; j < 5; j++) + { + int num8 = m_ReflectionTextures[j - 1]; + int num9 = j; + cb.GetTemporaryRT(blurTexture, num2 >> num9, num3 >> num9, 0, FilterMode.Bilinear, format); + cb.SetGlobalVector(Uniforms._Axis, new Vector4(1f, 0f, 0f, 0f)); + cb.SetGlobalFloat(Uniforms._CurrentMipLevel, (float)j - 1f); + cb.Blit(num8, blurTexture, material, 2); + cb.SetGlobalVector(Uniforms._Axis, new Vector4(0f, 1f, 0f, 0f)); + num8 = m_ReflectionTextures[j]; + cb.Blit(blurTexture, num8, material, 2); + cb.ReleaseTemporaryRT(blurTexture); + } + cb.Blit(m_ReflectionTextures[0], finalReflectionTexture, material, 3); + cb.GetTemporaryRT(tempTexture, camera.pixelWidth, camera.pixelHeight, 0, FilterMode.Bilinear, format); + cb.Blit(BuiltinRenderTextureType.CameraTarget, tempTexture, material, 1); + cb.Blit(tempTexture, BuiltinRenderTextureType.CameraTarget); + cb.ReleaseTemporaryRT(tempTexture); + } +} diff --git a/UnityEngine.PostProcessing/ScreenSpaceReflectionModel.cs b/UnityEngine.PostProcessing/ScreenSpaceReflectionModel.cs new file mode 100644 index 0000000..2552044 --- /dev/null +++ b/UnityEngine.PostProcessing/ScreenSpaceReflectionModel.cs @@ -0,0 +1,141 @@ +using System; + +namespace UnityEngine.PostProcessing; + +[Serializable] +public class ScreenSpaceReflectionModel : PostProcessingModel +{ + public enum SSRResolution + { + High = 0, + Low = 2 + } + + public enum SSRReflectionBlendType + { + PhysicallyBased, + Additive + } + + [Serializable] + public struct IntensitySettings + { + [Tooltip("Nonphysical multiplier for the SSR reflections. 1.0 is physically based.")] + [Range(0f, 2f)] + public float reflectionMultiplier; + + [Tooltip("How far away from the maxDistance to begin fading SSR.")] + [Range(0f, 1000f)] + public float fadeDistance; + + [Tooltip("Amplify Fresnel fade out. Increase if floor reflections look good close to the surface and bad farther 'under' the floor.")] + [Range(0f, 1f)] + public float fresnelFade; + + [Tooltip("Higher values correspond to a faster Fresnel fade as the reflection changes from the grazing angle.")] + [Range(0.1f, 10f)] + public float fresnelFadePower; + } + + [Serializable] + public struct ReflectionSettings + { + [Tooltip("How the reflections are blended into the render.")] + public SSRReflectionBlendType blendType; + + [Tooltip("Half resolution SSRR is much faster, but less accurate.")] + public SSRResolution reflectionQuality; + + [Tooltip("Maximum reflection distance in world units.")] + [Range(0.1f, 300f)] + public float maxDistance; + + [Tooltip("Max raytracing length.")] + [Range(16f, 1024f)] + public int iterationCount; + + [Tooltip("Log base 2 of ray tracing coarse step size. Higher traces farther, lower gives better quality silhouettes.")] + [Range(1f, 16f)] + public int stepSize; + + [Tooltip("Typical thickness of columns, walls, furniture, and other objects that reflection rays might pass behind.")] + [Range(0.01f, 10f)] + public float widthModifier; + + [Tooltip("Blurriness of reflections.")] + [Range(0.1f, 8f)] + public float reflectionBlur; + + [Tooltip("Disable for a performance gain in scenes where most glossy objects are horizontal, like floors, water, and tables. Leave on for scenes with glossy vertical objects.")] + public bool reflectBackfaces; + } + + [Serializable] + public struct ScreenEdgeMask + { + [Tooltip("Higher = fade out SSRR near the edge of the screen so that reflections don't pop under camera motion.")] + [Range(0f, 1f)] + public float intensity; + } + + [Serializable] + public struct Settings + { + public ReflectionSettings reflection; + + public IntensitySettings intensity; + + public ScreenEdgeMask screenEdgeMask; + + public static Settings defaultSettings + { + get + { + Settings result = default(Settings); + result.reflection = new ReflectionSettings + { + blendType = SSRReflectionBlendType.PhysicallyBased, + reflectionQuality = SSRResolution.Low, + maxDistance = 100f, + iterationCount = 256, + stepSize = 3, + widthModifier = 0.5f, + reflectionBlur = 1f, + reflectBackfaces = false + }; + result.intensity = new IntensitySettings + { + reflectionMultiplier = 1f, + fadeDistance = 100f, + fresnelFade = 1f, + fresnelFadePower = 1f + }; + result.screenEdgeMask = new ScreenEdgeMask + { + intensity = 0.03f + }; + return result; + } + } + } + + [SerializeField] + private Settings m_Settings = Settings.defaultSettings; + + public Settings settings + { + get + { + return m_Settings; + } + set + { + m_Settings = value; + } + } + + public override void Reset() + { + m_Settings = Settings.defaultSettings; + } +} diff --git a/UnityEngine.PostProcessing/TaaComponent.cs b/UnityEngine.PostProcessing/TaaComponent.cs new file mode 100644 index 0000000..83cf6dd --- /dev/null +++ b/UnityEngine.PostProcessing/TaaComponent.cs @@ -0,0 +1,176 @@ +using System; + +namespace UnityEngine.PostProcessing; + +public sealed class TaaComponent : PostProcessingComponentRenderTexture<AntialiasingModel> +{ + private static class Uniforms + { + internal static int _Jitter = Shader.PropertyToID("_Jitter"); + + internal static int _SharpenParameters = Shader.PropertyToID("_SharpenParameters"); + + internal static int _FinalBlendParameters = Shader.PropertyToID("_FinalBlendParameters"); + + internal static int _HistoryTex = Shader.PropertyToID("_HistoryTex"); + + internal static int _MainTex = Shader.PropertyToID("_MainTex"); + } + + private const string k_ShaderString = "Hidden/Post FX/Temporal Anti-aliasing"; + + private const int k_SampleCount = 8; + + private readonly RenderBuffer[] m_MRT = new RenderBuffer[2]; + + private int m_SampleIndex; + + private bool m_ResetHistory = true; + + private RenderTexture m_HistoryTexture; + + public override bool active => base.model.enabled && base.model.settings.method == AntialiasingModel.Method.Taa && SystemInfo.supportsMotionVectors && SystemInfo.supportedRenderTargetCount >= 2 && !context.interrupted; + + public Vector2 jitterVector { get; private set; } + + public override DepthTextureMode GetCameraFlags() + { + return DepthTextureMode.Depth | DepthTextureMode.MotionVectors; + } + + public void ResetHistory() + { + m_ResetHistory = true; + } + + public void SetProjectionMatrix(Func<Vector2, Matrix4x4> jitteredFunc) + { + AntialiasingModel.TaaSettings taaSettings = base.model.settings.taaSettings; + Vector2 vector = GenerateRandomOffset(); + vector *= taaSettings.jitterSpread; + context.camera.nonJitteredProjectionMatrix = context.camera.projectionMatrix; + if (jitteredFunc != null) + { + context.camera.projectionMatrix = jitteredFunc(vector); + } + else + { + context.camera.projectionMatrix = ((!context.camera.orthographic) ? GetPerspectiveProjectionMatrix(vector) : GetOrthographicProjectionMatrix(vector)); + } + context.camera.useJitteredProjectionMatrixForTransparentRendering = false; + vector.x /= context.width; + vector.y /= context.height; + Material material = context.materialFactory.Get("Hidden/Post FX/Temporal Anti-aliasing"); + material.SetVector(Uniforms._Jitter, vector); + jitterVector = vector; + } + + public void Render(RenderTexture source, RenderTexture destination) + { + Material material = context.materialFactory.Get("Hidden/Post FX/Temporal Anti-aliasing"); + material.shaderKeywords = null; + AntialiasingModel.TaaSettings taaSettings = base.model.settings.taaSettings; + if (m_ResetHistory || m_HistoryTexture == null || m_HistoryTexture.width != source.width || m_HistoryTexture.height != source.height) + { + if ((bool)m_HistoryTexture) + { + RenderTexture.ReleaseTemporary(m_HistoryTexture); + } + m_HistoryTexture = RenderTexture.GetTemporary(source.width, source.height, 0, source.format); + m_HistoryTexture.name = "TAA History"; + Graphics.Blit(source, m_HistoryTexture, material, 2); + } + material.SetVector(Uniforms._SharpenParameters, new Vector4(taaSettings.sharpen, 0f, 0f, 0f)); + material.SetVector(Uniforms._FinalBlendParameters, new Vector4(taaSettings.stationaryBlending, taaSettings.motionBlending, 6000f, 0f)); + material.SetTexture(Uniforms._MainTex, source); + material.SetTexture(Uniforms._HistoryTex, m_HistoryTexture); + RenderTexture temporary = RenderTexture.GetTemporary(source.width, source.height, 0, source.format); + temporary.name = "TAA History"; + ref RenderBuffer reference = ref m_MRT[0]; + reference = destination.colorBuffer; + ref RenderBuffer reference2 = ref m_MRT[1]; + reference2 = temporary.colorBuffer; + Graphics.SetRenderTarget(m_MRT, source.depthBuffer); + GraphicsUtils.Blit(material, context.camera.orthographic ? 1 : 0); + RenderTexture.ReleaseTemporary(m_HistoryTexture); + m_HistoryTexture = temporary; + m_ResetHistory = false; + } + + private float GetHaltonValue(int index, int radix) + { + float num = 0f; + float num2 = 1f / (float)radix; + while (index > 0) + { + num += (float)(index % radix) * num2; + index /= radix; + num2 /= (float)radix; + } + return num; + } + + private Vector2 GenerateRandomOffset() + { + Vector2 result = new Vector2(GetHaltonValue(m_SampleIndex & 0x3FF, 2), GetHaltonValue(m_SampleIndex & 0x3FF, 3)); + if (++m_SampleIndex >= 8) + { + m_SampleIndex = 0; + } + return result; + } + + private Matrix4x4 GetPerspectiveProjectionMatrix(Vector2 offset) + { + float num = Mathf.Tan((float)Math.PI / 360f * context.camera.fieldOfView); + float num2 = num * context.camera.aspect; + offset.x *= num2 / (0.5f * (float)context.width); + offset.y *= num / (0.5f * (float)context.height); + float num3 = (offset.x - num2) * context.camera.nearClipPlane; + float num4 = (offset.x + num2) * context.camera.nearClipPlane; + float num5 = (offset.y + num) * context.camera.nearClipPlane; + float num6 = (offset.y - num) * context.camera.nearClipPlane; + Matrix4x4 result = default(Matrix4x4); + result[0, 0] = 2f * context.camera.nearClipPlane / (num4 - num3); + result[0, 1] = 0f; + result[0, 2] = (num4 + num3) / (num4 - num3); + result[0, 3] = 0f; + result[1, 0] = 0f; + result[1, 1] = 2f * context.camera.nearClipPlane / (num5 - num6); + result[1, 2] = (num5 + num6) / (num5 - num6); + result[1, 3] = 0f; + result[2, 0] = 0f; + result[2, 1] = 0f; + result[2, 2] = (0f - (context.camera.farClipPlane + context.camera.nearClipPlane)) / (context.camera.farClipPlane - context.camera.nearClipPlane); + result[2, 3] = (0f - 2f * context.camera.farClipPlane * context.camera.nearClipPlane) / (context.camera.farClipPlane - context.camera.nearClipPlane); + result[3, 0] = 0f; + result[3, 1] = 0f; + result[3, 2] = -1f; + result[3, 3] = 0f; + return result; + } + + private Matrix4x4 GetOrthographicProjectionMatrix(Vector2 offset) + { + float orthographicSize = context.camera.orthographicSize; + float num = orthographicSize * context.camera.aspect; + offset.x *= num / (0.5f * (float)context.width); + offset.y *= orthographicSize / (0.5f * (float)context.height); + float left = offset.x - num; + float right = offset.x + num; + float top = offset.y + orthographicSize; + float bottom = offset.y - orthographicSize; + return Matrix4x4.Ortho(left, right, bottom, top, context.camera.nearClipPlane, context.camera.farClipPlane); + } + + public override void OnDisable() + { + if (m_HistoryTexture != null) + { + RenderTexture.ReleaseTemporary(m_HistoryTexture); + } + m_HistoryTexture = null; + m_SampleIndex = 0; + ResetHistory(); + } +} diff --git a/UnityEngine.PostProcessing/TrackballAttribute.cs b/UnityEngine.PostProcessing/TrackballAttribute.cs new file mode 100644 index 0000000..0f37d97 --- /dev/null +++ b/UnityEngine.PostProcessing/TrackballAttribute.cs @@ -0,0 +1,11 @@ +namespace UnityEngine.PostProcessing; + +public sealed class TrackballAttribute : PropertyAttribute +{ + public readonly string method; + + public TrackballAttribute(string method) + { + this.method = method; + } +} diff --git a/UnityEngine.PostProcessing/TrackballGroupAttribute.cs b/UnityEngine.PostProcessing/TrackballGroupAttribute.cs new file mode 100644 index 0000000..c64ea0e --- /dev/null +++ b/UnityEngine.PostProcessing/TrackballGroupAttribute.cs @@ -0,0 +1,5 @@ +namespace UnityEngine.PostProcessing; + +public sealed class TrackballGroupAttribute : PropertyAttribute +{ +} diff --git a/UnityEngine.PostProcessing/UserLutComponent.cs b/UnityEngine.PostProcessing/UserLutComponent.cs new file mode 100644 index 0000000..51f291a --- /dev/null +++ b/UnityEngine.PostProcessing/UserLutComponent.cs @@ -0,0 +1,35 @@ +namespace UnityEngine.PostProcessing; + +public sealed class UserLutComponent : PostProcessingComponentRenderTexture<UserLutModel> +{ + private static class Uniforms + { + internal static readonly int _UserLut = Shader.PropertyToID("_UserLut"); + + internal static readonly int _UserLut_Params = Shader.PropertyToID("_UserLut_Params"); + } + + public override bool active + { + get + { + UserLutModel.Settings settings = base.model.settings; + return base.model.enabled && settings.lut != null && settings.contribution > 0f && settings.lut.height == (int)Mathf.Sqrt(settings.lut.width) && !context.interrupted; + } + } + + public override void Prepare(Material uberMaterial) + { + UserLutModel.Settings settings = base.model.settings; + uberMaterial.EnableKeyword("USER_LUT"); + uberMaterial.SetTexture(Uniforms._UserLut, settings.lut); + uberMaterial.SetVector(Uniforms._UserLut_Params, new Vector4(1f / (float)settings.lut.width, 1f / (float)settings.lut.height, (float)settings.lut.height - 1f, settings.contribution)); + } + + public void OnGUI() + { + UserLutModel.Settings settings = base.model.settings; + Rect position = new Rect(context.viewport.x * (float)Screen.width + 8f, 8f, settings.lut.width, settings.lut.height); + GUI.DrawTexture(position, settings.lut); + } +} diff --git a/UnityEngine.PostProcessing/UserLutModel.cs b/UnityEngine.PostProcessing/UserLutModel.cs new file mode 100644 index 0000000..8cab02f --- /dev/null +++ b/UnityEngine.PostProcessing/UserLutModel.cs @@ -0,0 +1,49 @@ +using System; + +namespace UnityEngine.PostProcessing; + +[Serializable] +public class UserLutModel : PostProcessingModel +{ + [Serializable] + public struct Settings + { + [Tooltip("Custom lookup texture (strip format, e.g. 256x16).")] + public Texture2D lut; + + [Range(0f, 1f)] + [Tooltip("Blending factor.")] + public float contribution; + + public static Settings defaultSettings + { + get + { + Settings result = default(Settings); + result.lut = null; + result.contribution = 1f; + return result; + } + } + } + + [SerializeField] + private Settings m_Settings = Settings.defaultSettings; + + public Settings settings + { + get + { + return m_Settings; + } + set + { + m_Settings = value; + } + } + + public override void Reset() + { + m_Settings = Settings.defaultSettings; + } +} diff --git a/UnityEngine.PostProcessing/VignetteComponent.cs b/UnityEngine.PostProcessing/VignetteComponent.cs new file mode 100644 index 0000000..4b2f506 --- /dev/null +++ b/UnityEngine.PostProcessing/VignetteComponent.cs @@ -0,0 +1,38 @@ +namespace UnityEngine.PostProcessing; + +public sealed class VignetteComponent : PostProcessingComponentRenderTexture<VignetteModel> +{ + private static class Uniforms + { + internal static readonly int _Vignette_Color = Shader.PropertyToID("_Vignette_Color"); + + internal static readonly int _Vignette_Center = Shader.PropertyToID("_Vignette_Center"); + + internal static readonly int _Vignette_Settings = Shader.PropertyToID("_Vignette_Settings"); + + internal static readonly int _Vignette_Mask = Shader.PropertyToID("_Vignette_Mask"); + + internal static readonly int _Vignette_Opacity = Shader.PropertyToID("_Vignette_Opacity"); + } + + public override bool active => base.model.enabled && !context.interrupted; + + public override void Prepare(Material uberMaterial) + { + VignetteModel.Settings settings = base.model.settings; + uberMaterial.SetColor(Uniforms._Vignette_Color, settings.color); + if (settings.mode == VignetteModel.Mode.Classic) + { + uberMaterial.SetVector(Uniforms._Vignette_Center, settings.center); + uberMaterial.EnableKeyword("VIGNETTE_CLASSIC"); + float z = (1f - settings.roundness) * 6f + settings.roundness; + uberMaterial.SetVector(Uniforms._Vignette_Settings, new Vector4(settings.intensity * 3f, settings.smoothness * 5f, z, (!settings.rounded) ? 0f : 1f)); + } + else if (settings.mode == VignetteModel.Mode.Masked && settings.mask != null && settings.opacity > 0f) + { + uberMaterial.EnableKeyword("VIGNETTE_MASKED"); + uberMaterial.SetTexture(Uniforms._Vignette_Mask, settings.mask); + uberMaterial.SetFloat(Uniforms._Vignette_Opacity, settings.opacity); + } + } +} diff --git a/UnityEngine.PostProcessing/VignetteModel.cs b/UnityEngine.PostProcessing/VignetteModel.cs new file mode 100644 index 0000000..963ce2d --- /dev/null +++ b/UnityEngine.PostProcessing/VignetteModel.cs @@ -0,0 +1,87 @@ +using System; + +namespace UnityEngine.PostProcessing; + +[Serializable] +public class VignetteModel : PostProcessingModel +{ + public enum Mode + { + Classic, + Masked + } + + [Serializable] + public struct Settings + { + [Tooltip("Use the \"Classic\" mode for parametric controls. Use the \"Masked\" mode to use your own texture mask.")] + public Mode mode; + + [ColorUsage(false)] + [Tooltip("Vignette color. Use the alpha channel for transparency.")] + public Color color; + + [Tooltip("Sets the vignette center point (screen center is [0.5,0.5]).")] + public Vector2 center; + + [Range(0f, 1f)] + [Tooltip("Amount of vignetting on screen.")] + public float intensity; + + [Range(0.01f, 1f)] + [Tooltip("Smoothness of the vignette borders.")] + public float smoothness; + + [Range(0f, 1f)] + [Tooltip("Lower values will make a square-ish vignette.")] + public float roundness; + + [Tooltip("A black and white mask to use as a vignette.")] + public Texture mask; + + [Range(0f, 1f)] + [Tooltip("Mask opacity.")] + public float opacity; + + [Tooltip("Should the vignette be perfectly round or be dependent on the current aspect ratio?")] + public bool rounded; + + public static Settings defaultSettings + { + get + { + Settings result = default(Settings); + result.mode = Mode.Classic; + result.color = new Color(0f, 0f, 0f, 1f); + result.center = new Vector2(0.5f, 0.5f); + result.intensity = 0.45f; + result.smoothness = 0.2f; + result.roundness = 1f; + result.mask = null; + result.opacity = 1f; + result.rounded = false; + return result; + } + } + } + + [SerializeField] + private Settings m_Settings = Settings.defaultSettings; + + public Settings settings + { + get + { + return m_Settings; + } + set + { + m_Settings = value; + } + } + + public override void Reset() + { + m_Settings = Settings.defaultSettings; + } +} diff --git a/UnitySA.Characters.FirstPerson/FPCtrl.cs b/UnitySA.Characters.FirstPerson/FPCtrl.cs new file mode 100644 index 0000000..51d2efb --- /dev/null +++ b/UnitySA.Characters.FirstPerson/FPCtrl.cs @@ -0,0 +1,202 @@ +using UnityEngine; +using UnitySA.Utility; + +namespace UnitySA.Characters.FirstPerson; + +[RequireComponent(typeof(CharacterController))] +[RequireComponent(typeof(AudioSource))] +public class FPCtrl : MonoBehaviour +{ + [SerializeField] + private bool m_IsWalking; + + [SerializeField] + private float m_WalkSpeed; + + [SerializeField] + private float m_RunSpeed; + + [SerializeField] + [Range(0f, 1f)] + private float m_RunstepLenghten; + + [SerializeField] + private float m_JumpSpeed; + + [SerializeField] + private float m_StickToGroundForce; + + [SerializeField] + private float m_GravityMultiplier; + + [SerializeField] + private MLook m_MouseLook; + + [SerializeField] + private bool m_UseFovKick; + + [SerializeField] + private FOVZoom m_FovKick = new FOVZoom(); + + [SerializeField] + private bool m_UseHeadBob; + + [SerializeField] + private CurveCtrlBob m_HeadBob = new CurveCtrlBob(); + + [SerializeField] + private LerpCtrlBob m_JumpBob = new LerpCtrlBob(); + + [SerializeField] + private float m_StepInterval; + + private Camera m_Camera; + + private bool m_Jump; + + private float m_YRotation; + + private Vector2 m_Input; + + private Vector3 m_MoveDir = Vector3.zero; + + private CharacterController m_CharacterController; + + private CollisionFlags m_CollisionFlags; + + private bool m_PreviouslyGrounded; + + private Vector3 m_OriginalCameraPosition; + + private float m_StepCycle; + + private float m_NextStep; + + private bool m_Jumping; + + private void Start() + { + m_CharacterController = GetComponent<CharacterController>(); + m_Camera = Camera.main; + m_OriginalCameraPosition = m_Camera.transform.localPosition; + m_FovKick.Setup(m_Camera); + m_HeadBob.Setup(m_Camera, m_StepInterval); + m_StepCycle = 0f; + m_NextStep = m_StepCycle / 2f; + m_Jumping = false; + m_MouseLook.Init(base.transform, m_Camera.transform); + } + + private void Update() + { + RotateView(); + if (!m_Jump) + { + m_Jump = Input.GetButtonDown("Jump"); + } + if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) + { + StartCoroutine(m_JumpBob.DoBobCycle()); + m_MoveDir.y = 0f; + m_Jumping = false; + } + if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) + { + m_MoveDir.y = 0f; + } + m_PreviouslyGrounded = m_CharacterController.isGrounded; + } + + private void FixedUpdate() + { + GetInput(out var speed); + Vector3 vector = base.transform.forward * m_Input.y + base.transform.right * m_Input.x; + Physics.SphereCast(base.transform.position, m_CharacterController.radius, Vector3.down, out var hitInfo, m_CharacterController.height / 2f, -1, QueryTriggerInteraction.Ignore); + vector = Vector3.ProjectOnPlane(vector, hitInfo.normal).normalized; + m_MoveDir.x = vector.x * speed; + m_MoveDir.z = vector.z * speed; + if (m_CharacterController.isGrounded) + { + m_MoveDir.y = 0f - m_StickToGroundForce; + if (m_Jump) + { + m_MoveDir.y = m_JumpSpeed; + m_Jump = false; + m_Jumping = true; + } + } + else + { + m_MoveDir += Physics.gravity * m_GravityMultiplier * Time.fixedDeltaTime; + } + m_CollisionFlags = m_CharacterController.Move(m_MoveDir * Time.fixedDeltaTime); + ProgressStepCycle(speed); + UpdateCameraPosition(speed); + m_MouseLook.UpdateCursorLock(); + } + + private void ProgressStepCycle(float speed) + { + if (m_CharacterController.velocity.sqrMagnitude > 0f && (m_Input.x != 0f || m_Input.y != 0f)) + { + m_StepCycle += (m_CharacterController.velocity.magnitude + speed * ((!m_IsWalking) ? m_RunstepLenghten : 1f)) * Time.fixedDeltaTime; + } + if (m_StepCycle > m_NextStep) + { + m_NextStep = m_StepCycle + m_StepInterval; + } + } + + private void UpdateCameraPosition(float speed) + { + if (m_UseHeadBob) + { + Vector3 localPosition; + if (m_CharacterController.velocity.magnitude > 0f && m_CharacterController.isGrounded) + { + m_Camera.transform.localPosition = m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + speed * ((!m_IsWalking) ? m_RunstepLenghten : 1f)); + localPosition = m_Camera.transform.localPosition; + localPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset(); + } + else + { + localPosition = m_Camera.transform.localPosition; + localPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset(); + } + m_Camera.transform.localPosition = localPosition; + } + } + + private void GetInput(out float speed) + { + float axis = Input.GetAxis("Horizontal"); + float axis2 = Input.GetAxis("Vertical"); + bool isWalking = m_IsWalking; + m_IsWalking = !Input.GetKey(KeyCode.LeftShift); + speed = ((!m_IsWalking) ? m_RunSpeed : m_WalkSpeed); + m_Input = new Vector2(axis, axis2); + if (m_Input.sqrMagnitude > 1f) + { + m_Input.Normalize(); + } + if (m_IsWalking != isWalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0f) + { + StopAllCoroutines(); + StartCoroutine(m_IsWalking ? m_FovKick.FOVKickDown() : m_FovKick.FOVKickUp()); + } + } + + private void RotateView() + { + m_MouseLook.LookRotation(base.transform, m_Camera.transform); + } + + private void OnControllerColliderHit(ControllerColliderHit hit) + { + Rigidbody attachedRigidbody = hit.collider.attachedRigidbody; + if (m_CollisionFlags != CollisionFlags.Below && !(attachedRigidbody == null) && !attachedRigidbody.isKinematic) + { + attachedRigidbody.AddForceAtPosition(m_CharacterController.velocity * 0.1f, hit.point, ForceMode.Impulse); + } + } +} diff --git a/UnitySA.Characters.FirstPerson/MLook.cs b/UnitySA.Characters.FirstPerson/MLook.cs new file mode 100644 index 0000000..ce78022 --- /dev/null +++ b/UnitySA.Characters.FirstPerson/MLook.cs @@ -0,0 +1,111 @@ +using System; +using UnityEngine; + +namespace UnitySA.Characters.FirstPerson; + +[Serializable] +public class MLook +{ + public float XSensitivity = 2f; + + public float YSensitivity = 2f; + + public bool clampVerticalRotation = true; + + public float MinimumX = -90f; + + public float MaximumX = 90f; + + public bool smooth; + + public float smoothTime = 5f; + + public bool lockCursor = true; + + private Quaternion m_CharacterTargetRot; + + private Quaternion m_CameraTargetRot; + + private bool m_cursorIsLocked = true; + + public void Init(Transform character, Transform camera) + { + m_CharacterTargetRot = character.localRotation; + m_CameraTargetRot = camera.localRotation; + } + + public void LookRotation(Transform character, Transform camera) + { + float y = Input.GetAxis("Mouse X") * XSensitivity; + float num = Input.GetAxis("Mouse Y") * YSensitivity; + m_CharacterTargetRot *= Quaternion.Euler(0f, y, 0f); + m_CameraTargetRot *= Quaternion.Euler(0f - num, 0f, 0f); + if (clampVerticalRotation) + { + m_CameraTargetRot = ClampRotationAroundXAxis(m_CameraTargetRot); + } + if (smooth) + { + character.localRotation = Quaternion.Slerp(character.localRotation, m_CharacterTargetRot, smoothTime * Time.deltaTime); + camera.localRotation = Quaternion.Slerp(camera.localRotation, m_CameraTargetRot, smoothTime * Time.deltaTime); + } + else + { + character.localRotation = m_CharacterTargetRot; + camera.localRotation = m_CameraTargetRot; + } + UpdateCursorLock(); + } + + public void SetCursorLock(bool value) + { + lockCursor = value; + if (!lockCursor) + { + Cursor.lockState = CursorLockMode.None; + Cursor.visible = true; + } + } + + public void UpdateCursorLock() + { + if (lockCursor) + { + InternalLockUpdate(); + } + } + + private void InternalLockUpdate() + { + if (Input.GetKeyUp(KeyCode.Escape)) + { + m_cursorIsLocked = false; + } + else if (Input.GetMouseButtonUp(0)) + { + m_cursorIsLocked = true; + } + if (m_cursorIsLocked) + { + Cursor.lockState = CursorLockMode.Locked; + Cursor.visible = false; + } + else if (!m_cursorIsLocked) + { + Cursor.lockState = CursorLockMode.None; + Cursor.visible = true; + } + } + + private Quaternion ClampRotationAroundXAxis(Quaternion q) + { + q.x /= q.w; + q.y /= q.w; + q.z /= q.w; + q.w = 1f; + float value = 114.59156f * Mathf.Atan(q.x); + value = Mathf.Clamp(value, MinimumX, MaximumX); + q.x = Mathf.Tan((float)Math.PI / 360f * value); + return q; + } +} diff --git a/UnitySA.Utility/CurveCtrlBob.cs b/UnitySA.Utility/CurveCtrlBob.cs new file mode 100644 index 0000000..04e57e5 --- /dev/null +++ b/UnitySA.Utility/CurveCtrlBob.cs @@ -0,0 +1,50 @@ +using System; +using UnityEngine; + +namespace UnitySA.Utility; + +[Serializable] +public class CurveCtrlBob +{ + public float HorizontalBobRange = 0.33f; + + public float VerticalBobRange = 0.33f; + + public AnimationCurve Bobcurve = new AnimationCurve(new Keyframe(0f, 0f), new Keyframe(0.5f, 1f), new Keyframe(1f, 0f), new Keyframe(1.5f, -1f), new Keyframe(2f, 0f)); + + public float VerticaltoHorizontalRatio = 1f; + + private float m_CyclePositionX; + + private float m_CyclePositionY; + + private float m_BobBaseInterval; + + private Vector3 m_OriginalCameraPosition; + + private float m_Time; + + public void Setup(Camera camera, float bobBaseInterval) + { + m_BobBaseInterval = bobBaseInterval; + m_OriginalCameraPosition = camera.transform.localPosition; + m_Time = Bobcurve[Bobcurve.length - 1].time; + } + + public Vector3 DoHeadBob(float speed) + { + float x = m_OriginalCameraPosition.x + Bobcurve.Evaluate(m_CyclePositionX) * HorizontalBobRange; + float y = m_OriginalCameraPosition.y + Bobcurve.Evaluate(m_CyclePositionY) * VerticalBobRange; + m_CyclePositionX += speed * Time.deltaTime / m_BobBaseInterval; + m_CyclePositionY += speed * Time.deltaTime / m_BobBaseInterval * VerticaltoHorizontalRatio; + if (m_CyclePositionX > m_Time) + { + m_CyclePositionX -= m_Time; + } + if (m_CyclePositionY > m_Time) + { + m_CyclePositionY -= m_Time; + } + return new Vector3(x, y, 0f); + } +} diff --git a/UnitySA.Utility/FOVZoom.cs b/UnitySA.Utility/FOVZoom.cs new file mode 100644 index 0000000..555f205 --- /dev/null +++ b/UnitySA.Utility/FOVZoom.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections; +using UnityEngine; + +namespace UnitySA.Utility; + +[Serializable] +public class FOVZoom +{ + public Camera Camera; + + [HideInInspector] + public float originalFov; + + public float FOVIncrease = 3f; + + public float TimeToIncrease = 1f; + + public float TimeToDecrease = 1f; + + public AnimationCurve IncreaseCurve; + + public void Setup(Camera camera) + { + CheckStatus(camera); + Camera = camera; + originalFov = camera.fieldOfView; + } + + private void CheckStatus(Camera camera) + { + if (camera == null) + { + throw new Exception("FOVKick camera is null, please supply the camera to the constructor"); + } + if (IncreaseCurve == null) + { + throw new Exception("FOVKick Increase curve is null, please define the curve for the field of view kicks"); + } + } + + public void ChangeCamera(Camera camera) + { + Camera = camera; + } + + public IEnumerator FOVKickUp() + { + float t = Mathf.Abs((Camera.fieldOfView - originalFov) / FOVIncrease); + while (t < TimeToIncrease) + { + Camera.fieldOfView = originalFov + IncreaseCurve.Evaluate(t / TimeToIncrease) * FOVIncrease; + t += Time.deltaTime; + yield return new WaitForEndOfFrame(); + } + } + + public IEnumerator FOVKickDown() + { + float t = Mathf.Abs((Camera.fieldOfView - originalFov) / FOVIncrease); + while (t > 0f) + { + Camera.fieldOfView = originalFov + IncreaseCurve.Evaluate(t / TimeToDecrease) * FOVIncrease; + t -= Time.deltaTime; + yield return new WaitForEndOfFrame(); + } + Camera.fieldOfView = originalFov; + } +} diff --git a/UnitySA.Utility/LerpCtrlBob.cs b/UnitySA.Utility/LerpCtrlBob.cs new file mode 100644 index 0000000..9d23469 --- /dev/null +++ b/UnitySA.Utility/LerpCtrlBob.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections; +using UnityEngine; + +namespace UnitySA.Utility; + +[Serializable] +public class LerpCtrlBob +{ + public float BobDuration; + + public float BobAmount; + + private float m_Offset; + + public float Offset() + { + return m_Offset; + } + + public IEnumerator DoBobCycle() + { + float t2 = 0f; + while (t2 < BobDuration) + { + m_Offset = Mathf.Lerp(0f, BobAmount, t2 / BobDuration); + t2 += Time.deltaTime; + yield return new WaitForFixedUpdate(); + } + t2 = 0f; + while (t2 < BobDuration) + { + m_Offset = Mathf.Lerp(BobAmount, 0f, t2 / BobDuration); + t2 += Time.deltaTime; + yield return new WaitForFixedUpdate(); + } + m_Offset = 0f; + } +} diff --git a/Weapon.cs b/Weapon.cs new file mode 100644 index 0000000..feb9963 --- /dev/null +++ b/Weapon.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +public class Weapon : MonoBehaviour +{ + private void Start() + { + } + + private void Update() + { + } +} diff --git a/WeaponHandler.cs b/WeaponHandler.cs new file mode 100644 index 0000000..7b3d80f --- /dev/null +++ b/WeaponHandler.cs @@ -0,0 +1,75 @@ +using UnityEngine; + +public class WeaponHandler : MonoBehaviour +{ + [HideInInspector] + public Gun leftGun; + + [HideInInspector] + public Gun rightGun; + + [HideInInspector] + public Transform gunADS; + + [HideInInspector] + public float ADSFOV; + + public bool isDualWeilding; + + private void Start() + { + } + + private void Update() + { + } + + public void SetWeapon(Weapon w, bool mainHand) + { + } + + public void SetGun(Gun g, bool mainHand) + { + if (mainHand) + { + rightGun = g; + gunADS = g.GetComponentInChildren<ADS>().transform; + ADSFOV = g.ADSFOV; + } + else + { + leftGun = g; + } + if ((bool)leftGun && (bool)rightGun) + { + isDualWeilding = true; + } + } + + public void HoldAttack(bool shootWithRightGun, bool ADS) + { + if (shootWithRightGun) + { + if (rightGun.auto) + { + rightGun.Shoot(base.transform.root, ADS); + } + } + else if (leftGun.auto) + { + leftGun.Shoot(base.transform.root, ADS); + } + } + + public void PressAttack(bool shootWithRightGun, bool ADS) + { + if (shootWithRightGun) + { + rightGun.Shoot(base.transform.root, ADS); + } + else + { + leftGun.Shoot(base.transform.root, ADS); + } + } +} diff --git a/Wheel.cs b/Wheel.cs new file mode 100644 index 0000000..1152a14 --- /dev/null +++ b/Wheel.cs @@ -0,0 +1,24 @@ +using UnityEngine; + +public class Wheel : MonoBehaviour +{ + public Rigidbody rig; + + public bool isActive; + + private CollisionChecker checker; + + public Vector3 forward; + + private void Start() + { + rig = GetComponent<Rigidbody>(); + checker = GetComponent<CollisionChecker>(); + } + + private void Update() + { + isActive = checker.sinceGrounded < 0.1f; + forward = base.transform.GetChild(0).forward; + } +} diff --git a/WheelVisualizer.cs b/WheelVisualizer.cs new file mode 100644 index 0000000..679db09 --- /dev/null +++ b/WheelVisualizer.cs @@ -0,0 +1,37 @@ +using UnityEngine; + +public class WheelVisualizer : MonoBehaviour +{ + private Rigidbody rig; + + public float spinAmount; + + public float inputVelocityAmount; + + public float inputReturnVelocityAmount; + + public float inputFriction; + + private GenericInputHandler input; + + private float inputVelocity; + + private void Start() + { + rig = GetComponentInParent<Rigidbody>(); + input = GetComponentInParent<GenericInputHandler>(); + } + + private void FixedUpdate() + { + inputVelocity *= inputFriction; + } + + private void Update() + { + inputVelocity += input.inputDirection.x; + inputVelocity -= inputVelocity * inputReturnVelocityAmount * Time.deltaTime; + base.transform.localRotation = Quaternion.Euler(0f, inputVelocity * inputVelocityAmount, 0f); + base.transform.GetChild(0).Rotate(Vector3.right * spinAmount * Time.deltaTime * rig.transform.InverseTransformDirection(rig.velocity).z, Space.Self); + } +} diff --git a/WobbleShake.cs b/WobbleShake.cs new file mode 100644 index 0000000..4da2d38 --- /dev/null +++ b/WobbleShake.cs @@ -0,0 +1,50 @@ +using UnityEngine; + +public class WobbleShake : MonoBehaviour +{ + public Vector3 velocity = Vector3.zero; + + public float friction = 0.9f; + + public float movementMultiplier = 10f; + + private Camera mainCam; + + private void Start() + { + mainCam = base.transform.root.GetComponentInChildren<Camera>(); + } + + private void FixedUpdate() + { + Vector3 forward = Vector3.forward; + Vector3 vector = Vector3.Cross(base.transform.forward, forward).normalized * Vector3.Angle(base.transform.forward, forward); + forward = Vector3.up; + Vector3 vector2 = Vector3.Cross(base.transform.up, forward).normalized * Vector3.Angle(base.transform.up, forward); + velocity += (vector + vector2) * movementMultiplier; + velocity *= friction; + base.transform.Rotate(velocity, Space.World); + friction = Mathf.Lerp(friction, 0.7f, Time.fixedDeltaTime * 1f); + } + + public void AddShake(Vector3 shake, float newFriction) + { + Vector3 vector = new Vector3(0f - shake.y, shake.x, shake.z); + if (Mathf.Abs(newFriction - 0.7f) > Mathf.Abs(friction - 0.7f)) + { + friction = newFriction; + } + velocity += vector; + } + + public void AddShakeWorld(Vector3 shake, float newFriction) + { + if ((bool)mainCam) + { + shake = mainCam.transform.TransformDirection(shake); + Vector3 vector = new Vector3(0f - Mathf.Abs(shake.z + shake.y), 0f - shake.x, 0f); + friction = newFriction; + velocity += vector; + } + } +} diff --git a/_appControlerShaderOnTriplanarMesh.cs b/_appControlerShaderOnTriplanarMesh.cs new file mode 100644 index 0000000..27292cb --- /dev/null +++ b/_appControlerShaderOnTriplanarMesh.cs @@ -0,0 +1,45 @@ +using UnityEngine; + +public class _appControlerShaderOnTriplanarMesh : MonoBehaviour +{ + public bool shadows; + + public bool forward_path = true; + + private bool panel_enabled; + + public float model_dir; + + private void Awake() + { + panel_enabled = true; + } + + private void Update() + { + if (Input.GetKeyDown(KeyCode.P)) + { + panel_enabled = !panel_enabled; + } + } + + private void OnGUI() + { + GUILayout.Space(10f); + GUILayout.BeginVertical("box"); + GUILayout.Label(string.Empty + FPSmeter.fps); + if (panel_enabled) + { + shadows = GUILayout.Toggle(shadows, "disable Unity's shadows"); + Light component = GameObject.Find("Directional light").GetComponent<Light>(); + component.shadows = ((!shadows) ? LightShadows.Soft : LightShadows.None); + forward_path = GUILayout.Toggle(forward_path, "forward rendering"); + Camera component2 = GameObject.Find("Main Camera").GetComponent<Camera>(); + component2.renderingPath = (forward_path ? RenderingPath.Forward : RenderingPath.DeferredShading); + GUILayout.Label(" Drag model/env to rotate"); + GUILayout.Label(" Wheel - zoom camera"); + } + GUILayout.Label(" P - toggle panel"); + GUILayout.EndVertical(); + } +} diff --git a/_appControlerTerrain.cs b/_appControlerTerrain.cs new file mode 100644 index 0000000..6728256 --- /dev/null +++ b/_appControlerTerrain.cs @@ -0,0 +1,179 @@ +using UnityEngine; + +public class _appControlerTerrain : MonoBehaviour +{ + public bool shadows; + + public bool forward_path = true; + + public bool terrain_self_shadow; + + public bool terrain_smooth_shadows = true; + + private bool panel_enabled; + + public float light_dir = 285f; + + public float preset_param_interp; + + private RTP_LODmanager LODmanager; + + private void Awake() + { + GetLODManager(); + panel_enabled = true; + } + + private void Update() + { + if (Input.GetKeyDown(KeyCode.P)) + { + panel_enabled = !panel_enabled; + } + if (Input.GetKey(KeyCode.Period)) + { + base.transform.localPosition = new Vector3(base.transform.localPosition.x, Mathf.Min(base.transform.localPosition.y + 0.5f, 50f), base.transform.localPosition.z); + } + if (Input.GetKey(KeyCode.Comma)) + { + base.transform.localPosition = new Vector3(base.transform.localPosition.x, Mathf.Max(base.transform.localPosition.y - 0.5f, 0.9f), base.transform.localPosition.z); + } + } + + private void GetLODManager() + { + GameObject gameObject = GameObject.Find("_RTP_LODmanager"); + if (!(gameObject == null)) + { + LODmanager = (RTP_LODmanager)gameObject.GetComponent(typeof(RTP_LODmanager)); + } + } + + private void OnGUI() + { + if (!LODmanager) + { + GetLODManager(); + return; + } + GUILayout.Space(10f); + GUILayout.BeginVertical("box"); + GUILayout.Label(string.Empty + FPSmeter.fps); + if (panel_enabled) + { + shadows = GUILayout.Toggle(shadows, "disable Unity's shadows"); + Light component = GameObject.Find("Directional light").GetComponent<Light>(); + component.shadows = ((!shadows) ? LightShadows.Soft : LightShadows.None); + forward_path = GUILayout.Toggle(forward_path, "forward rendering"); + Camera component2 = GameObject.Find("Main Camera").GetComponent<Camera>(); + component2.renderingPath = (forward_path ? RenderingPath.Forward : RenderingPath.DeferredShading); + if (forward_path) + { + RenderSettings.ambientLight = new Color32(25, 25, 25, 0); + } + else + { + RenderSettings.ambientLight = new Color32(93, 103, 122, 0); + } + TerrainShaderLod rTP_LODlevel = LODmanager.RTP_LODlevel; + TerrainShaderLod terrainShaderLod = rTP_LODlevel; + switch (rTP_LODlevel) + { + case TerrainShaderLod.POM: + if (GUILayout.Button("POM shading")) + { + terrainShaderLod = TerrainShaderLod.PM; + } + break; + case TerrainShaderLod.PM: + if (GUILayout.Button("PM shading")) + { + terrainShaderLod = TerrainShaderLod.SIMPLE; + } + break; + case TerrainShaderLod.SIMPLE: + if (GUILayout.Button("SIMPLE shading")) + { + terrainShaderLod = TerrainShaderLod.POM; + } + break; + } + switch (terrainShaderLod) + { + case TerrainShaderLod.POM: + if (terrainShaderLod != rTP_LODlevel) + { + Terrain terrain2 = GameObject.Find("Terrain").GetComponent(typeof(Terrain)) as Terrain; + ReliefTerrain reliefTerrain2 = terrain2.GetComponent(typeof(ReliefTerrain)) as ReliefTerrain; + reliefTerrain2.globalSettingsHolder.Refresh(); + LODmanager.RTP_LODlevel = TerrainShaderLod.POM; + LODmanager.RefreshLODlevel(); + } + break; + case TerrainShaderLod.PM: + if (terrainShaderLod != rTP_LODlevel) + { + Terrain terrain3 = GameObject.Find("Terrain").GetComponent(typeof(Terrain)) as Terrain; + ReliefTerrain reliefTerrain3 = terrain3.GetComponent(typeof(ReliefTerrain)) as ReliefTerrain; + reliefTerrain3.globalSettingsHolder.Refresh(); + LODmanager.RTP_LODlevel = TerrainShaderLod.PM; + LODmanager.RefreshLODlevel(); + } + break; + case TerrainShaderLod.SIMPLE: + if (terrainShaderLod != rTP_LODlevel) + { + Terrain terrain = GameObject.Find("Terrain").GetComponent(typeof(Terrain)) as Terrain; + ReliefTerrain reliefTerrain = terrain.GetComponent(typeof(ReliefTerrain)) as ReliefTerrain; + reliefTerrain.globalSettingsHolder.Refresh(); + LODmanager.RTP_LODlevel = TerrainShaderLod.SIMPLE; + LODmanager.RefreshLODlevel(); + } + break; + } + if (terrainShaderLod == TerrainShaderLod.POM) + { + terrain_self_shadow = LODmanager.RTP_SHADOWS; + bool flag = GUILayout.Toggle(terrain_self_shadow, "self shadowing"); + if (flag != terrain_self_shadow) + { + LODmanager.RTP_SHADOWS = flag; + LODmanager.RefreshLODlevel(); + } + terrain_self_shadow = flag; + if (terrain_self_shadow) + { + terrain_smooth_shadows = LODmanager.RTP_SOFT_SHADOWS; + bool flag2 = GUILayout.Toggle(terrain_smooth_shadows, "smooth shadows"); + if (flag2 != terrain_smooth_shadows) + { + LODmanager.RTP_SOFT_SHADOWS = flag2; + LODmanager.RefreshLODlevel(); + } + terrain_smooth_shadows = flag2; + } + } + if (LODmanager.RTP_SNOW_FIRST) + { + Terrain terrain4 = GameObject.Find("Terrain").GetComponent(typeof(Terrain)) as Terrain; + ReliefTerrain reliefTerrain4 = terrain4.GetComponent(typeof(ReliefTerrain)) as ReliefTerrain; + GUILayout.BeginHorizontal(); + GUILayout.Label("Snow", GUILayout.MaxWidth(40f)); + float num = GUILayout.HorizontalSlider(reliefTerrain4.globalSettingsHolder._snow_strength, 0f, 1f); + if (num != reliefTerrain4.globalSettingsHolder._snow_strength) + { + reliefTerrain4.globalSettingsHolder._snow_strength = num; + reliefTerrain4.globalSettingsHolder.Refresh(); + } + GUILayout.EndHorizontal(); + } + GUILayout.Label("Light", GUILayout.MaxWidth(40f)); + light_dir = GUILayout.HorizontalSlider(light_dir, 0f, 360f); + component.transform.rotation = Quaternion.Euler(40f, light_dir, 0f); + GUILayout.Label(" F (hold) - freeze camera"); + GUILayout.Label(" ,/. - change cam position"); + } + GUILayout.Label(" P - toggle panel"); + GUILayout.EndVertical(); + } +} diff --git a/_appControlerTerrain2Geometry.cs b/_appControlerTerrain2Geometry.cs new file mode 100644 index 0000000..425640c --- /dev/null +++ b/_appControlerTerrain2Geometry.cs @@ -0,0 +1,179 @@ +using UnityEngine; + +public class _appControlerTerrain2Geometry : MonoBehaviour +{ + public bool shadows; + + public bool forward_path = true; + + public bool terrain_self_shadow; + + public bool terrain_smooth_shadows = true; + + private bool panel_enabled; + + public float light_dir = 285f; + + public float preset_param_interp; + + private RTP_LODmanager LODmanager; + + private void Awake() + { + GetLODManager(); + panel_enabled = true; + } + + private void Update() + { + if (Input.GetKeyDown(KeyCode.P)) + { + panel_enabled = !panel_enabled; + } + if (Input.GetKey(KeyCode.Period)) + { + base.transform.localPosition = new Vector3(base.transform.localPosition.x, Mathf.Min(base.transform.localPosition.y + 0.5f, 50f), base.transform.localPosition.z); + } + if (Input.GetKey(KeyCode.Comma)) + { + base.transform.localPosition = new Vector3(base.transform.localPosition.x, Mathf.Max(base.transform.localPosition.y - 0.5f, 0.9f), base.transform.localPosition.z); + } + } + + private void GetLODManager() + { + GameObject gameObject = GameObject.Find("_RTP_LODmanager"); + if (!(gameObject == null)) + { + LODmanager = (RTP_LODmanager)gameObject.GetComponent(typeof(RTP_LODmanager)); + } + } + + private void OnGUI() + { + if (!LODmanager) + { + GetLODManager(); + return; + } + GUILayout.Space(10f); + GUILayout.BeginVertical("box"); + GUILayout.Label(string.Empty + FPSmeter.fps); + if (panel_enabled) + { + shadows = GUILayout.Toggle(shadows, "disable Unity's shadows"); + Light component = GameObject.Find("Directional light").GetComponent<Light>(); + component.shadows = ((!shadows) ? LightShadows.Soft : LightShadows.None); + forward_path = GUILayout.Toggle(forward_path, "forward rendering"); + Camera component2 = GameObject.Find("Main Camera").GetComponent<Camera>(); + component2.renderingPath = (forward_path ? RenderingPath.Forward : RenderingPath.DeferredShading); + if (forward_path) + { + RenderSettings.ambientLight = new Color32(25, 25, 25, 0); + } + else + { + RenderSettings.ambientLight = new Color32(93, 103, 122, 0); + } + TerrainShaderLod rTP_LODlevel = LODmanager.RTP_LODlevel; + TerrainShaderLod terrainShaderLod = rTP_LODlevel; + switch (rTP_LODlevel) + { + case TerrainShaderLod.POM: + if (GUILayout.Button("POM shading")) + { + terrainShaderLod = TerrainShaderLod.PM; + } + break; + case TerrainShaderLod.PM: + if (GUILayout.Button("PM shading")) + { + terrainShaderLod = TerrainShaderLod.SIMPLE; + } + break; + case TerrainShaderLod.SIMPLE: + if (GUILayout.Button("SIMPLE shading")) + { + terrainShaderLod = TerrainShaderLod.POM; + } + break; + } + switch (terrainShaderLod) + { + case TerrainShaderLod.POM: + if (terrainShaderLod != rTP_LODlevel) + { + GameObject gameObject2 = GameObject.Find("terrainMesh"); + ReliefTerrain reliefTerrain2 = gameObject2.GetComponent(typeof(ReliefTerrain)) as ReliefTerrain; + reliefTerrain2.globalSettingsHolder.Refresh(); + LODmanager.RTP_LODlevel = TerrainShaderLod.POM; + LODmanager.RefreshLODlevel(); + } + break; + case TerrainShaderLod.PM: + if (terrainShaderLod != rTP_LODlevel) + { + GameObject gameObject3 = GameObject.Find("terrainMesh"); + ReliefTerrain reliefTerrain3 = gameObject3.GetComponent(typeof(ReliefTerrain)) as ReliefTerrain; + reliefTerrain3.globalSettingsHolder.Refresh(); + LODmanager.RTP_LODlevel = TerrainShaderLod.PM; + LODmanager.RefreshLODlevel(); + } + break; + case TerrainShaderLod.SIMPLE: + if (terrainShaderLod != rTP_LODlevel) + { + GameObject gameObject = GameObject.Find("terrainMesh"); + ReliefTerrain reliefTerrain = gameObject.GetComponent(typeof(ReliefTerrain)) as ReliefTerrain; + reliefTerrain.globalSettingsHolder.Refresh(); + LODmanager.RTP_LODlevel = TerrainShaderLod.SIMPLE; + LODmanager.RefreshLODlevel(); + } + break; + } + if (terrainShaderLod == TerrainShaderLod.POM) + { + terrain_self_shadow = LODmanager.RTP_SHADOWS; + bool flag = GUILayout.Toggle(terrain_self_shadow, "self shadowing"); + if (flag != terrain_self_shadow) + { + LODmanager.RTP_SHADOWS = flag; + LODmanager.RefreshLODlevel(); + } + terrain_self_shadow = flag; + if (terrain_self_shadow) + { + terrain_smooth_shadows = LODmanager.RTP_SOFT_SHADOWS; + bool flag2 = GUILayout.Toggle(terrain_smooth_shadows, "smooth shadows"); + if (flag2 != terrain_smooth_shadows) + { + LODmanager.RTP_SOFT_SHADOWS = flag2; + LODmanager.RefreshLODlevel(); + } + terrain_smooth_shadows = flag2; + } + } + if (LODmanager.RTP_SNOW_FIRST) + { + GameObject gameObject4 = GameObject.Find("terrainMesh"); + ReliefTerrain reliefTerrain4 = gameObject4.GetComponent(typeof(ReliefTerrain)) as ReliefTerrain; + GUILayout.BeginHorizontal(); + GUILayout.Label("Snow", GUILayout.MaxWidth(40f)); + float num = GUILayout.HorizontalSlider(reliefTerrain4.globalSettingsHolder._snow_strength, 0f, 1f); + if (num != reliefTerrain4.globalSettingsHolder._snow_strength) + { + reliefTerrain4.globalSettingsHolder._snow_strength = num; + reliefTerrain4.globalSettingsHolder.Refresh(); + } + GUILayout.EndHorizontal(); + } + GUILayout.Label("Light", GUILayout.MaxWidth(40f)); + light_dir = GUILayout.HorizontalSlider(light_dir, 0f, 360f); + component.transform.rotation = Quaternion.Euler(40f, light_dir, 0f); + GUILayout.Label(" F (hold) - freeze camera"); + GUILayout.Label(" ,/. - change cam position"); + } + GUILayout.Label(" P - toggle panel"); + GUILayout.EndVertical(); + } +} diff --git a/ch.sycoforge.Decal.Demo/AdvancedBulletHoles.cs b/ch.sycoforge.Decal.Demo/AdvancedBulletHoles.cs new file mode 100644 index 0000000..28e5311 --- /dev/null +++ b/ch.sycoforge.Decal.Demo/AdvancedBulletHoles.cs @@ -0,0 +1,55 @@ +using UnityEngine; + +namespace ch.sycoforge.Decal.Demo; + +public class AdvancedBulletHoles : MonoBehaviour +{ + public EasyDecal DecalPrefab; + + public GameObject ImpactParticles; + + public float CastRadius = 0.25f; + + private void Start() + { + if (DecalPrefab == null) + { + Debug.LogError("The AdvancedBulletHoles script has no decal prefab attached."); + } + EasyDecal.HideMesh = false; + } + + private void Update() + { + if (!Input.GetMouseButtonUp(0)) + { + return; + } + Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); + if (!Physics.Raycast(ray, out var hitInfo, 200f)) + { + return; + } + GameObject receiver = hitInfo.collider.gameObject; + Vector3 point = hitInfo.point; + RaycastHit[] array = Physics.SphereCastAll(ray, CastRadius, Vector3.Distance(Camera.main.transform.position, point) + 2f); + Vector3 normal = hitInfo.normal; + if (array.Length > 0) + { + RaycastHit[] array2 = array; + for (int i = 0; i < array2.Length; i++) + { + RaycastHit raycastHit = array2[i]; + Debug.DrawLine(ray.origin, raycastHit.point, Color.red); + normal += raycastHit.normal; + } + } + normal /= (float)(array.Length + 1); + EasyDecal.ProjectAt(DecalPrefab.gameObject, receiver, point, normal); + if (ImpactParticles != null) + { + Quaternion rotation = Quaternion.FromToRotation(Vector3.up, normal); + Object.Instantiate(ImpactParticles, point, rotation); + } + } +} diff --git a/ch.sycoforge.Decal.Demo/BasicBulletHoles.cs b/ch.sycoforge.Decal.Demo/BasicBulletHoles.cs new file mode 100644 index 0000000..0d6eef1 --- /dev/null +++ b/ch.sycoforge.Decal.Demo/BasicBulletHoles.cs @@ -0,0 +1,37 @@ +using UnityEngine; + +namespace ch.sycoforge.Decal.Demo; + +public class BasicBulletHoles : MonoBehaviour +{ + public EasyDecal DecalPrefab; + + private bool t; + + public void Start() + { + if (DecalPrefab == null) + { + Debug.LogError("The DynamicDemo script has no decal prefab attached."); + } + } + + public void Update() + { + if (!Input.GetMouseButtonUp(0)) + { + return; + } + Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); + if (Physics.Raycast(ray, out var hitInfo, 200f)) + { + Debug.DrawLine(ray.origin, hitInfo.point, Color.red); + EasyDecal easyDecal = EasyDecal.ProjectAt(DecalPrefab.gameObject, hitInfo.collider.gameObject, hitInfo.point, hitInfo.normal); + t = !t; + if (t) + { + easyDecal.CancelFade(); + } + } + } +} diff --git a/ch.sycoforge.Decal.Demo/BezierUtil.cs b/ch.sycoforge.Decal.Demo/BezierUtil.cs new file mode 100644 index 0000000..4784ce7 --- /dev/null +++ b/ch.sycoforge.Decal.Demo/BezierUtil.cs @@ -0,0 +1,77 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace ch.sycoforge.Decal.Demo; + +public static class BezierUtil +{ + public static List<Vector3> InterpolatePath(List<Vector3> path, int segments, float radius, float angleThreshold) + { + if (path.Count >= 3) + { + List<Vector3> list = new List<Vector3>(); + int num = path.Count - 1; + list.Add(path[0]); + int num2 = 0; + for (int i = 2; i < path.Count; i++) + { + Vector3 vector = path[i - 2]; + Vector3 vector2 = path[i - 1]; + Vector3 vector3 = path[i]; + Vector3 vector4 = vector2 - vector; + Vector3 vector5 = vector3 - vector2; + float num3 = Mathf.Abs(Vector3.Angle(vector4, vector5)); + if (!(num3 <= angleThreshold)) + { + float magnitude = vector4.magnitude; + float magnitude2 = vector5.magnitude; + vector4.Normalize(); + vector5.Normalize(); + magnitude = Mathf.Min(magnitude * 0.5f, radius); + magnitude2 = Mathf.Min(magnitude2 * 0.5f, radius); + Vector3 vector6 = vector2 - vector4 * magnitude; + Vector3 vector7 = vector2; + Vector3 vector8 = vector2 + vector5 * magnitude2; + for (int j = 0; j < segments; j++) + { + float num4 = (float)j / ((float)segments - 1f); + float num5 = 1f - num4; + Vector3 item = num5 * num5 * vector6 + 2f * num5 * num4 * vector7 + num4 * num4 * vector8; + list.Add(item); + } + num2 = i; + } + } + if (num2 <= num) + { + list.Add(path[num]); + } + return list; + } + return path; + } + + public static Vector3[] GetBezierApproximation(Vector3[] controlPoints, int outputSegmentCount) + { + Vector3[] array = new Vector3[outputSegmentCount + 1]; + for (int i = 0; i < outputSegmentCount; i++) + { + float t = (float)i / (float)outputSegmentCount; + ref Vector3 reference = ref array[i]; + reference = GetBezierPoint(t, controlPoints, 0, controlPoints.Length); + } + return array; + } + + public static Vector3 GetBezierPoint(float t, Vector3[] controlPoints, int index, int count) + { + if (count == 1) + { + return controlPoints[index]; + } + Vector3 bezierPoint = GetBezierPoint(t, controlPoints, index - 1, count - 1); + Vector3 bezierPoint2 = GetBezierPoint(t, controlPoints, index, count - 1); + Vector3 bezierPoint3 = GetBezierPoint(t, controlPoints, index + 1, count - 1); + return (1f - t) * (1f - t) * bezierPoint + 2f * (1f - t) * t * bezierPoint2 + t * t * bezierPoint3; + } +} diff --git a/ch.sycoforge.Decal.Demo/LineUtil.cs b/ch.sycoforge.Decal.Demo/LineUtil.cs new file mode 100644 index 0000000..864ee19 --- /dev/null +++ b/ch.sycoforge.Decal.Demo/LineUtil.cs @@ -0,0 +1,50 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace ch.sycoforge.Decal.Demo; + +public static class LineUtil +{ + public static void DrawPath(float thickness, Material material, List<Vector3> path) + { + if (path != null && (path == null || path.Count >= 2)) + { + if (thickness <= Mathf.Epsilon) + { + GL.Begin(1); + } + else + { + GL.Begin(7); + } + material.SetPass(0); + GL.Color(Color.blue); + Vector3 start = path[0]; + for (int i = 1; i < path.Count; i++) + { + Vector3 vector = path[i]; + DrawLine(thickness, start, vector); + start = vector; + } + GL.End(); + } + } + + private static void DrawLine(float thickness, Vector3 start, Vector3 end) + { + if (thickness <= Mathf.Epsilon) + { + GL.Vertex(start); + GL.Vertex(end); + return; + } + Camera main = Camera.main; + Vector3 normalized = (end - start).normalized; + Vector3 normalized2 = (start - main.transform.position).normalized; + Vector3 vector = Vector3.Cross(normalized2, normalized) * (thickness / 2f); + GL.Vertex(start - vector); + GL.Vertex(start + vector); + GL.Vertex(end + vector); + GL.Vertex(end - vector); + } +} diff --git a/ch.sycoforge.Decal.Demo/PathAgent.cs b/ch.sycoforge.Decal.Demo/PathAgent.cs new file mode 100644 index 0000000..27908d7 --- /dev/null +++ b/ch.sycoforge.Decal.Demo/PathAgent.cs @@ -0,0 +1,106 @@ +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.AI; + +namespace ch.sycoforge.Decal.Demo; + +[RequireComponent(typeof(NavMeshAgent))] +[RequireComponent(typeof(LineRenderer))] +public class PathAgent : MonoBehaviour +{ + public float PathThickness = 1f; + + [Tooltip("Distance from the ground.")] + public float NormalPathOffset; + + [Tooltip("Max radius between segments.")] + [Range(0.001f, 0.5f)] + public float Radius = 0.25f; + + [Tooltip("Discard segments when their angle is smaller than this value.")] + public float AngleThreshold = 5f; + + public bool DrawGizmos; + + public EasyDecal TargetAimDecal; + + public GameObject TargetPointDecalPrefab; + + private List<Vector3> path = new List<Vector3>(); + + private NavMeshAgent agent; + + private LineRenderer lineRenderer; + + private Vector3 decalOffset = Vector3.up * 0.5f; + + private const int MAXDISTANCE = 50; + + private void Start() + { + TargetAimDecal.gameObject.SetActive(value: false); + agent = GetComponent<NavMeshAgent>(); + lineRenderer = GetComponent<LineRenderer>(); + } + + private void Update() + { + Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); + CreatePath(ray); + SetTarget(ray); + } + + private void SetTarget(Ray mouseRay) + { + if (Input.GetMouseButtonUp(0) && Physics.Raycast(mouseRay, out var hitInfo, 50f)) + { + agent.SetDestination(hitInfo.point); + EasyDecal.ProjectAt(TargetPointDecalPrefab, hitInfo.collider.gameObject, hitInfo.point + decalOffset, Quaternion.identity); + } + } + + private void CreatePath(Ray mouseRay) + { + if (Physics.Raycast(mouseRay, out var hitInfo, 50f)) + { + Vector3 position = base.transform.position; + Vector3 point = hitInfo.point; + path.Clear(); + NavMeshPath navMeshPath = new NavMeshPath(); + if (NavMesh.CalculatePath(position, point, -1, navMeshPath) && navMeshPath.status == NavMeshPathStatus.PathComplete) + { + int num = navMeshPath.corners.Length; + Vector3 vector = base.transform.up; + for (int i = 0; i < num; i++) + { + if (i > 0 && NormalPathOffset > 0f && Physics.Raycast(navMeshPath.corners[i], Vector3.down, out var _, NormalPathOffset * 10f)) + { + vector = hitInfo.normal; + } + Vector3 item = navMeshPath.corners[i] + vector * NormalPathOffset; + path.Add(item); + } + Vector3[] array = BezierUtil.InterpolatePath(path, 10, Radius, AngleThreshold).ToArray(); + lineRenderer.SetVertexCount(array.Length); + lineRenderer.SetPositions(array); + TargetAimDecal.gameObject.SetActive(value: true); + TargetAimDecal.gameObject.transform.position = navMeshPath.corners[num - 1] + decalOffset; + return; + } + } + TargetAimDecal.gameObject.SetActive(value: false); + } + + private void OnDrawGizmos() + { + if (!DrawGizmos) + { + return; + } + Gizmos.color = Color.red; + foreach (Vector3 item in path) + { + Gizmos.DrawSphere(item, 0.05f); + } + } +} diff --git a/ch.sycoforge.Decal.Demo/ProxyRegister.cs b/ch.sycoforge.Decal.Demo/ProxyRegister.cs new file mode 100644 index 0000000..1a171bf --- /dev/null +++ b/ch.sycoforge.Decal.Demo/ProxyRegister.cs @@ -0,0 +1,13 @@ +using UnityEngine; + +namespace ch.sycoforge.Decal.Demo; + +public class ProxyRegister : MonoBehaviour +{ + public StaticProxyCollection ProxyCollection; + + private void Start() + { + EasyDecal.SetStaticProxyCollection(ProxyCollection); + } +} diff --git a/ch.sycoforge.Decal.Demo/Sinoid.cs b/ch.sycoforge.Decal.Demo/Sinoid.cs new file mode 100644 index 0000000..38ee213 --- /dev/null +++ b/ch.sycoforge.Decal.Demo/Sinoid.cs @@ -0,0 +1,29 @@ +using System; +using UnityEngine; + +namespace ch.sycoforge.Decal.Demo; + +public class Sinoid : MonoBehaviour +{ + public float AngularVelocity = 2f; + + public float SineFreq = 0.2f; + + public float Amplitude = 0.25f; + + private float accuTime; + + private Vector3 startPos; + + private void Start() + { + startPos = base.transform.position; + } + + private void Update() + { + accuTime += Time.deltaTime; + base.transform.position = startPos + Vector3.up * Amplitude * Mathf.Sin(accuTime * 2f * (float)Math.PI * SineFreq); + base.transform.Rotate((Vector3.up + Vector3.forward) * AngularVelocity * Time.deltaTime); + } +} |