You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2340 lines
83 KiB

5 years ago
  1. //CHANGE LOG
  2. /*
  3. ----[ v 3.2.1 ]----
  4. * Fog Volume data will ignore cameras without HideFlags.None
  5. * Less garbage allocation
  6. * Replaced PointLight component with a general purpose FogVolumeLight component
  7. * Added a LightManager component that is now responsible for handling lights
  8. It is automatically added to each FogVolume
  9. * Added spot lights
  10. * Added Fog Volume lights (point and spot) that work without a real point or spotlight
  11. * Added Fog Volume to the menu bar, including new options for light creation
  12. * New 'Light visibility' option in the inspector allows to modify the culling behaviour of point lights
  13. * Depth buffer won't be affected now with the camera clip planes.
  14. * A textured Fog Volume can be now excluded from the low-res process. Useful to render FV with a different camera, i.e water refraction
  15. * Directional Light allows now multiple volumes. User will have to reasign the target volume.
  16. * "Render in scene view" is now a per-volume option
  17. * Added an option to receive a depth map externally "_CustomCameraDepthTexture"
  18. * FV shadow map faded at the edges, so pixels are not stretched
  19. * Added Directional light option to the 'Fog Volume' menu
  20. - Only available when a directional light and at least one FogVolume is present
  21. ----[ v 3.2.1p1 ]----
  22. * Fixed an error that didn't update FrustumPlanes correctly
  23. * Camera script shows a message when user adds FogVolume.cs to the camera. The camera is then cleaned OnEnable()
  24. * Reasigned ShadowProjectorMesh when it is null
  25. ----[ v 3.2.1p2 ]----
  26. * Fixed a bug related with visibility
  27. * Mesh filter is hidden from inspector
  28. * Lights can now be turned on/off without the need for toggling "Real-time search".
  29. * Camera script can be removed when "Disable camera script"== ON in FogVolumeData
  30. * Directional light debug miniature can be moved now
  31. * Added a culling mask field for depth pass
  32. * LightManager is correctly hidden from inspector
  33. * Fixed unneeded shadow work performed in Depth pass
  34. ----[ v 3.2.1p3 ] ----
  35. * Better depth-buffer behaviour on non-windows platforms
  36. * Glitch fixing: shading rounding precission -venus scene-, more solid editing of quality-settings, better scene-game viewports relationship.
  37. * Lights now works on OpenGL (there was a too-many-uniforms error)
  38. * Better behaviour of surrogates in Mac
  39. * Better CPU perf
  40. * Updated VR showroom (now mostly event driven, using SteamVR's libs, improved VR start location -counter transformed start into meat space-, etc)
  41. ----[ v 3.2.1p4 ] ----
  42. * Added FogVolumePrimitiveManager which supports up to 20 primitives that can be visible at the same time.
  43. * The total amount of supported primitives is the same as for lights and is set to 1000. Only the 20 closest to the camera will be taken into account.
  44. * Fixed a bug where removing a light would always return false.
  45. * Overhauled the FogVolume menu to make it more accessible.
  46. * Reduced garbage allocation for version before Unity 2017.3 (GeometryUtility.CalculateFrustumPlanes()).
  47. * FogVolumeLightManager methods that are meant to be accessed by the user are:
  48. - AddSimulatedSpotLight()
  49. - AddSimulatedPointLight()
  50. - AddPointLight()
  51. - AddSpotLight()
  52. - RemoveLight()
  53. - SetPointOfInterest()
  54. * FogVolumePrimitiveManager methods that are meant to be accessed by the user are:
  55. - AddPrimitiveBox()
  56. - AddPrimitiveSphere()
  57. - RemovePrimitie()
  58. - SetPointOfInterest()
  59. ----[ v 3.3 ] ----
  60. * Fixed a bug that made primitives to not work in the build
  61. * Each FogVolume will now store it's material.
  62. - The path where the materials are stored is specified by the constant MaterialPath.
  63. ----[ v 3.3.1 ] ----
  64. * Unity returned FALSE with SystemInfo.supports3DTextures in webgl. But it is supported, so removed that damn thing to enable 3D textures in webgl.
  65. ----[ v 3.4 ] ----
  66. * Improved VR support. Parent object is not required now
  67. * Bilateral upsampling done for stereo rendering
  68. * DeNoise executed when not in play
  69. */
  70. using UnityEngine;
  71. using System.Reflection;
  72. using System.Collections.Generic;
  73. using System.Runtime.Serialization.Formatters;
  74. using UnityEngine.SceneManagement;
  75. #if UNITY_EDITOR
  76. using UnityEditor.SceneManagement;
  77. #endif
  78. using UnityEngine.Profiling;
  79. using FogVolumeUtilities;
  80. #if UNITY_EDITOR
  81. using UnityEditor;
  82. using System.IO;
  83. #endif
  84. [ExecuteInEditMode]
  85. //[RequireComponent(typeof(FogVolumeLightManager))]
  86. public class FogVolume : MonoBehaviour
  87. {
  88. #region InspectorData
  89. #if UNITY_EDITOR
  90. public bool showLighting,
  91. OtherTAB,
  92. showGradient,
  93. showPointLights,
  94. showNoiseProperties,
  95. showVolumeProperties,
  96. showColorTab,
  97. tempShadowCaster,
  98. showCustomizationOptions,
  99. showDebugOptions,
  100. showOtherOptions,
  101. generalInfo,
  102. TexturesGroup;
  103. public string BackgroundImagesPath;
  104. #endif
  105. #endregion
  106. public enum FogType
  107. {
  108. Uniform = 0,
  109. Textured = 1
  110. }
  111. public FogType _FogType;
  112. public bool RenderableInSceneView = true;
  113. GameObject FogVolumeGameObject;
  114. public FogVolume ShadowCaster;
  115. public Texture2D _PerformanceLUT;
  116. //public float bias = .5f;
  117. public Vector3 fogVolumeScale = new Vector3(20, 20, 20);
  118. [SerializeField]
  119. public Color FogMainColor = Color.white;
  120. public Color _FogColor = Color.white;
  121. public bool _AmbientAffectsFogColor = false;
  122. [Range(1, 5)]
  123. public float Exposure = 2.5f;
  124. [Range(-.5f, .5f)]
  125. public float Offset = 0;
  126. [Range(.01f, 3)]
  127. public float Gamma = 1;
  128. public bool Tonemap = false;
  129. public float Visibility = 25;
  130. [HideInInspector]
  131. public bool ColorAdjust = false;
  132. [Header("Lighting")]
  133. public int _SelfShadowSteps = 3;
  134. public int ShadowCameraSkippedFrames = 0;
  135. public Color _SelfShadowColor = Color.black;
  136. public float VolumeFogInscatteringAnisotropy = .5f;
  137. public float VolumeFogInscatteringIntensity = .1f;
  138. public float VolumeFogInscatteringStartDistance = 10f;
  139. public float VolumeFogInscatteringTransitionWideness = 1;
  140. public Color VolumeFogInscatteringColor = Color.white;
  141. public bool VolumeFogInscattering = false;
  142. public float HeightAbsorption, HeightAbsorptionMin = -1, HeightAbsorptionMax = -1;
  143. public bool SunAttached;
  144. [SerializeField]
  145. public Light Sun = null;
  146. [SerializeField]
  147. public bool _ShadeNoise = false;
  148. public bool _DirectionalLighting = false;
  149. public float _DirectionalLightingDistance = .01f;
  150. // public float DirectionalLightingClamp = 2;
  151. public float DirectLightingShadowDensity = 1;
  152. public Color LightExtinctionColor = new Color(81 / 255f, 45 / 255f, 26 / 255f, 0);
  153. public int DirectLightingShadowSteps = 1;
  154. public bool bAbsorption = true;
  155. public float Absorption = .5f;
  156. public float _LightExposure = 1;
  157. public bool Lambert = false;
  158. public float LambertianBias = 1;
  159. public float NormalDistance = .01f;
  160. public float DirectLightingAmount = 1;
  161. public float DirectLightingDistance = 10;
  162. [Range(1, 3)]
  163. public float ShadowBrightness = 1;
  164. public Color _AmbientColor = Color.gray;
  165. bool _ProxyVolume = false;
  166. // [SerializeField]
  167. // [Range(1, 10)]
  168. // public float Shade = 1;
  169. [SerializeField]
  170. [Range(.0f, .15f)]
  171. public float ShadowShift = 0.0094f;
  172. [Range(0, 5)]
  173. public float PointLightsIntensity = 1;
  174. // public PointLight[] PointLights;
  175. // public List<PointLight> PointLightsList;
  176. public float PointLightingDistance = 1000, PointLightingDistance2Camera = 50;
  177. public float PointLightCullSizeMultiplier = 1.0f;
  178. public bool PointLightsActive = false;
  179. public bool EnableInscattering = false;
  180. public Color InscatteringColor = Color.white;
  181. public Texture2D _LightHaloTexture, CoverageTex;
  182. public bool LightHalo;
  183. public float _HaloWidth = .75f;
  184. public float _HaloOpticalDispersion = 1;
  185. public float _HaloRadius = 1;
  186. public float _HaloIntensity = 1;
  187. public float _HaloAbsorption = .5f;
  188. [Range(-1, 1)]
  189. public float
  190. InscatteringShape = 0;
  191. public float InscatteringIntensity = .2f, InscatteringStartDistance = 00, InscatteringTransitionWideness = 1;
  192. [Header("Noise")]
  193. public bool EnableNoise = false;
  194. public int Octaves = 1;
  195. public float _DetailMaskingThreshold = 18;
  196. // public float DetailSamplingBaseOpacityLimit = .3f;
  197. public bool bSphericalFade = false;
  198. public float SphericalFadeDistance = 10;
  199. public float DetailDistance = 500;
  200. public float DetailTiling = 1;
  201. public float _DetailRelativeSpeed = 10;
  202. public float _BaseRelativeSpeed = 1;
  203. public float _NoiseDetailRange = .5f, _Curl = .5f;
  204. public float BaseTiling = 8;
  205. public float Coverage = 1.5f;
  206. public float NoiseDensity = 1;
  207. // [SerializeField]
  208. // public bool Procedural = false;
  209. //[SerializeField]
  210. //bool DoubleLayer = false;
  211. //[SerializeField]
  212. public float _3DNoiseScale = 80;
  213. // [SerializeField]
  214. [Range(10f, 300)]
  215. public int Iterations = 85;
  216. public FogVolumeRenderer.BlendMode _BlendMode = FogVolumeRenderer.BlendMode.TraditionalTransparency;
  217. //[SerializeField]
  218. // [Range(10, 2000)]
  219. public float IterationStep = 500, _OptimizationFactor = 0;
  220. public enum SamplingMethod
  221. {
  222. Eye2Box = 0,
  223. ViewAligned = 1
  224. }
  225. public SamplingMethod _SamplingMethod = (SamplingMethod)0;
  226. public enum DebugMode
  227. {
  228. Lit,
  229. Iterations,
  230. Inscattering,
  231. VolumetricShadows,
  232. VolumeFogInscatterClamp,
  233. VolumeFogPhase
  234. }
  235. public bool _VisibleByReflectionProbeStatic = true;
  236. FogVolumeRenderer _FogVolumeRenderer = null;
  237. public GameObject GameCameraGO = null;
  238. public DebugMode _DebugMode = DebugMode.Lit;
  239. public bool useHeightGradient = false;
  240. public float GradMin = 1, GradMax = -1, GradMin2 = -1, GradMax2 = -1;
  241. public Texture3D _NoiseVolume2;
  242. public Texture3D _NoiseVolume = null;
  243. [Range(0f, 10)]
  244. public float NoiseIntensity = 0.3f;
  245. public void setNoiseIntensity(float value)
  246. {
  247. NoiseIntensity = value;
  248. }
  249. //[Range(1, 200)]
  250. [Range(0f, 5f)]
  251. public float
  252. NoiseContrast = 12;
  253. public float FadeDistance = 5000;
  254. [Range(0, 20)]
  255. public float Vortex = 0;
  256. public enum VortexAxis
  257. {
  258. X = 0,
  259. Y = 1,
  260. Z = 2
  261. }
  262. public VortexAxis _VortexAxis = (VortexAxis)2;
  263. public bool bVolumeFog = false;
  264. public bool VolumeFogInscatterColorAffectedWithFogColor = true;
  265. public enum LightScatterMethod
  266. {
  267. BeersLaw = 0,
  268. InverseSquare = 1,
  269. Linear = 2
  270. }
  271. public LightScatterMethod _LightScatterMethod = (LightScatterMethod)1;
  272. [Range(0, 360)]
  273. public float rotation = 0;
  274. [Range(0, 10)]
  275. public float RotationSpeed = 0;
  276. public Vector4 Speed = new Vector4(0, 0, 0, 0);
  277. public Vector4 Stretch = new Vector4(0, 0, 0, 0);
  278. [SerializeField]
  279. [Header("Collision")]
  280. public bool SceneCollision = true;
  281. public bool ShowPrimitives = false;
  282. public bool EnableDistanceFields = false;
  283. //public List<FogVolumePrimitive> PrimitivesList;
  284. public float _PrimitiveEdgeSoftener = 1;
  285. public float _PrimitiveCutout = 0;
  286. public float Constrain = 0;
  287. [SerializeField]
  288. //[Range(1, 200)]
  289. //float _SceneIntersectionThreshold = 1000;
  290. //[SerializeField]
  291. [Range(1, 200)]
  292. public float _SceneIntersectionSoftness = 1;
  293. [SerializeField]
  294. [Range(0, .1f)]
  295. public float _jitter = 0.0045f;
  296. public MeshRenderer FogRenderer = null;
  297. public Texture2D[] _InspectorBackground;
  298. public int _InspectorBackgroundIndex = 0;
  299. public string Description = "";
  300. [Header("Gradient")]
  301. public bool EnableGradient = false;
  302. public Texture2D Gradient;
  303. // #if UNITY_EDITOR
  304. [SerializeField]
  305. public bool HideWireframe = true;
  306. // #endif
  307. [SerializeField]
  308. public bool SaveMaterials = false;
  309. [SerializeField]
  310. public bool RequestSavingMaterials = false;
  311. [SerializeField]
  312. public int
  313. DrawOrder = 0;
  314. [SerializeField]
  315. public bool ShowDebugGizmos = false;
  316. MeshFilter filter;
  317. Mesh mesh;
  318. public RenderTexture RT_Opacity, RT_OpacityBlur;
  319. public float ShadowCutoff = 1f;
  320. Vector3 currentFogVolume = Vector3.one;
  321. public bool CastShadows = false;
  322. public GameObject ShadowCameraGO;
  323. public int shadowCameraPosition = 20;
  324. public int ShadowCameraPosition
  325. {
  326. set
  327. {
  328. if (value != shadowCameraPosition)
  329. {
  330. shadowCameraPosition = value;
  331. _ShadowCamera.CameraTransform();
  332. }
  333. }
  334. get
  335. {
  336. return shadowCameraPosition;
  337. }
  338. }
  339. public ShadowCamera _ShadowCamera;
  340. public float _PushAlpha = 1;
  341. public float GetVisibility()
  342. {
  343. return Visibility;
  344. }
  345. // public Material _FogMaterial { get { return FogMaterial; } }
  346. [SerializeField]
  347. Material fogMaterial = null;
  348. public Material FogMaterial
  349. {
  350. get
  351. {
  352. if (fogMaterial == null)
  353. {
  354. CreateMaterial();
  355. }
  356. return fogMaterial;
  357. }
  358. }
  359. public Shader FogVolumeShader;
  360. #if UNITY_EDITOR
  361. private string m_prevFVName = null;
  362. #endif
  363. void RemoveMaterial()
  364. {
  365. #if UNITY_EDITOR
  366. Scene activeScene = EditorSceneManager.GetActiveScene();
  367. string activeScenePath =
  368. activeScene.path.Substring(0,
  369. activeScene.path.Length - activeScene.name.Length -
  370. 7);
  371. string materialName = m_prevFVName + "_Material";
  372. string[] materials = AssetDatabase.FindAssets(materialName);
  373. if (materials.Length != 0)
  374. {
  375. AssetDatabase.DeleteAsset(activeScenePath + "/" + activeScene.name + "/" +
  376. materialName + ".mat");
  377. }
  378. #endif
  379. }
  380. void CreateMaterial()
  381. {
  382. if (SaveMaterials)
  383. {
  384. #if UNITY_EDITOR
  385. Scene activeScene = EditorSceneManager.GetActiveScene();
  386. if (activeScene.path.Length == 0)
  387. {
  388. Debug.LogWarning("The scene must be saved in order to enable 'SaveMaterials'!");
  389. FogVolumeShader = Shader.Find("Hidden/FogVolume");
  390. fogMaterial = new Material(FogVolumeShader);
  391. SaveMaterials = false;
  392. return;
  393. }
  394. string activeScenePath =
  395. activeScene.path.Substring(0,
  396. activeScene.path.Length - activeScene.name.Length -
  397. 7);
  398. string materialName = FogVolumeGameObject.name + "_Material.mat";
  399. string[] materials = AssetDatabase.FindAssets(materialName);
  400. if (materials.Length == 0)
  401. {
  402. FogVolumeShader = Shader.Find("Hidden/FogVolume");
  403. fogMaterial = new Material(FogVolumeShader);
  404. bool subfolderExists = false;
  405. string[] subfolders = AssetDatabase.GetSubFolders(activeScenePath);
  406. for (int i = 0; i < subfolders.Length; i++)
  407. {
  408. if (subfolders[i].Substring(subfolders[i].Length - activeScene.name.Length, activeScene.name.Length) == activeScene.name)
  409. {
  410. subfolderExists = true;
  411. break;
  412. }
  413. }
  414. if (!subfolderExists)
  415. {
  416. AssetDatabase.CreateFolder(activeScenePath, activeScene.name);
  417. }
  418. AssetDatabase.CreateAsset(fogMaterial,
  419. activeScenePath + "/" + activeScene.name + "/" +
  420. materialName);
  421. }
  422. else
  423. {
  424. fogMaterial =
  425. AssetDatabase.LoadAssetAtPath(activeScenePath + "/" + activeScene.name +
  426. "/" + materialName,
  427. typeof(Material)) as Material;
  428. }
  429. #else
  430. FogVolumeShader = Shader.Find("Hidden/FogVolume");
  431. fogMaterial = new Material(FogVolumeShader);
  432. #endif
  433. }
  434. else
  435. {
  436. DestroyImmediate(fogMaterial);
  437. FogVolumeShader = Shader.Find("Hidden/FogVolume");
  438. // FogVolumeShader.maximumLOD = 600;
  439. fogMaterial = new Material(FogVolumeShader);
  440. try
  441. {
  442. fogMaterial.name = FogVolumeGameObject.name + " Material";
  443. }
  444. catch
  445. {
  446. print(name);
  447. }
  448. fogMaterial.hideFlags = HideFlags.HideAndDontSave;
  449. }
  450. }
  451. //void SetCameraDepth()
  452. //{
  453. // if (ForwardRenderingCamera)
  454. // ForwardRenderingCamera.depthTextureMode |= DepthTextureMode.Depth;
  455. //}
  456. #if UNITY_EDITOR
  457. void CreateLayer(string LayerName)
  458. {
  459. // https://forum.unity3d.com/threads/adding-layer-by-script.41970/reply?quote=2274824
  460. SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
  461. SerializedProperty layers = tagManager.FindProperty("layers");
  462. bool ExistLayer = false;
  463. //print(ExistLayer);
  464. for (int i = 8; i < layers.arraySize; i++)
  465. {
  466. SerializedProperty layerSP = layers.GetArrayElementAtIndex(i);
  467. //print(layerSP.stringValue);
  468. if (layerSP.stringValue == LayerName)
  469. {
  470. ExistLayer = true;
  471. break;
  472. }
  473. }
  474. for (int j = 8; j < layers.arraySize; j++)
  475. {
  476. SerializedProperty layerSP = layers.GetArrayElementAtIndex(j);
  477. if (layerSP.stringValue == "" && !ExistLayer)
  478. {
  479. layerSP.stringValue = LayerName;
  480. tagManager.ApplyModifiedProperties();
  481. break;
  482. }
  483. }
  484. // print(layers.arraySize);
  485. }
  486. #endif
  487. [SerializeField]
  488. GameObject ShadowProjector;
  489. MeshRenderer ShadowProjectorRenderer;
  490. MeshFilter ShadowProjectorMeshFilter;
  491. Material ShadowProjectorMaterial;
  492. //Shader ShadowProjectorShader;
  493. public Mesh ShadowProjectorMesh;
  494. public Color ShadowColor = new Color(.5f, .5f, .5f, .25f);
  495. //Vector3 ShadowProjectorScaleBackup = new Vector3(20, 20, 20);
  496. //Vector3 ShadowProjectorPositionBackup;
  497. public UnityEngine.Rendering.CompareFunction _ztest = UnityEngine.Rendering.CompareFunction.Disabled;
  498. void ShadowProjectorLock()
  499. {
  500. if (ShadowProjector)
  501. {
  502. ShadowProjector.transform.position = new Vector3(
  503. FogVolumeGameObject.transform.position.x,
  504. ShadowProjector.transform.position.y,
  505. FogVolumeGameObject.transform.position.z);
  506. Vector3 ShadowProjectorScale = new Vector3(fogVolumeScale.x, ShadowProjector.transform.localScale.y, fogVolumeScale.z);
  507. ShadowProjector.transform.localScale = ShadowProjectorScale;
  508. ShadowProjector.transform.localRotation = new Quaternion();
  509. }
  510. }
  511. void ShadowMapSetup()
  512. {
  513. if (ShadowCameraGO)
  514. {
  515. //print(ShadowCameraGO.name);
  516. //DestroyImmediate(ShadowCameraGO);
  517. // ShadowCameraGO.hideFlags = HideFlags.None;
  518. // ShadowCameraGO.hideFlags = HideFlags.HideInHierarchy;
  519. ShadowCameraGO.GetComponent<Camera>().cullingMask = 1 << LayerMask.NameToLayer("FogVolumeShadowCaster");
  520. ShadowCameraGO.GetComponent<Camera>().renderingPath = RenderingPath.Forward;
  521. _ShadowCamera.CameraTransform();
  522. }
  523. //The volume must be square, sir
  524. if (CastShadows)
  525. {
  526. fogVolumeScale.z = fogVolumeScale.x;
  527. }
  528. //Create shadow projector
  529. if (CastShadows)
  530. {
  531. ShadowProjector = GameObject.Find(FogVolumeGameObject.name + " Shadow Projector");
  532. if (ShadowProjector == null)
  533. {
  534. ShadowProjector = new GameObject();
  535. ShadowProjector.AddComponent<MeshFilter>();
  536. ShadowProjector.AddComponent<MeshRenderer>();
  537. ShadowProjector.transform.parent = FogVolumeGameObject.transform;
  538. ShadowProjector.transform.position = FogVolumeGameObject.transform.position;
  539. ShadowProjector.transform.rotation = FogVolumeGameObject.transform.rotation;
  540. ShadowProjector.transform.localScale = fogVolumeScale;
  541. ShadowProjector.GetComponent<MeshRenderer>().shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
  542. ShadowProjector.GetComponent<MeshRenderer>().receiveShadows = false;
  543. ShadowProjector.GetComponent<MeshRenderer>().reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off;
  544. ShadowProjector.GetComponent<MeshRenderer>().lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off;
  545. }
  546. //ShadowProjector.hideFlags = HideFlags.DontSave;
  547. ShadowProjectorMeshFilter = ShadowProjector.GetComponent<MeshFilter>();
  548. //doesnt work ShadowProjectorMesh = Resources.Load("ShadowVolume") as Mesh;
  549. ShadowProjectorMeshFilter.mesh = ShadowProjectorMesh;
  550. //3.1.3 for some reason, the mesh is lost in the VR showroom
  551. if (ShadowProjectorMesh == null)
  552. {
  553. GameObject tempShadowBoxGO = GameObject.CreatePrimitive(PrimitiveType.Cube);
  554. ShadowProjectorMesh = tempShadowBoxGO.GetComponent<MeshFilter>().mesh;
  555. DestroyImmediate(tempShadowBoxGO, true);
  556. }
  557. if (ShadowProjector.GetComponent<MeshFilter>().sharedMesh == null)
  558. ShadowProjector.GetComponent<MeshFilter>().mesh = ShadowProjectorMesh;
  559. if (ShadowProjectorMesh == null) print("Missing mesh");
  560. ShadowProjectorRenderer = ShadowProjector.GetComponent<MeshRenderer>();
  561. ShadowProjectorRenderer.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off;
  562. ShadowProjectorRenderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off;
  563. ShadowProjectorRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
  564. ShadowProjectorRenderer.receiveShadows = false;
  565. ShadowProjectorMaterial = ShadowProjectorRenderer.sharedMaterial;
  566. ShadowProjector.name = FogVolumeGameObject.name + " Shadow Projector";
  567. if (ShadowProjectorMaterial == null)
  568. {
  569. ShadowProjectorMaterial = new Material(Shader.Find("Fog Volume/Shadow Projector"));
  570. //ShadowProjectorMaterial = new Material(Shader.Find("Diffuse"));
  571. ShadowProjectorMaterial.name = "Shadow Projector Material";
  572. // ShadowProjectorMaterial.hideFlags = HideFlags.HideAndDontSave;
  573. }
  574. ShadowProjectorRenderer.sharedMaterial = ShadowProjectorMaterial;
  575. }
  576. }
  577. void SetShadowProyectorLayer()
  578. {
  579. //lets hide it when we don't render it in scene view. We will send it to the UI layer to make it easy
  580. if (ShadowProjector)
  581. {
  582. if (RenderableInSceneView == false)
  583. {
  584. if (ShadowProjector.layer == LayerMask.NameToLayer("Default"))
  585. {
  586. ShadowProjector.layer = LayerMask.NameToLayer("UI");
  587. // print("switch projector to UI");
  588. }
  589. }
  590. else
  591. {
  592. if (ShadowProjector.layer == LayerMask.NameToLayer("UI"))
  593. {
  594. ShadowProjector.layer = LayerMask.NameToLayer("Default");
  595. // print("switch projector to Default");
  596. }
  597. }
  598. }
  599. }
  600. void FindDirectionalLight()
  601. {
  602. //pick a light
  603. Light[] SceneLights = FindObjectsOfType<Light>();
  604. //first, try to get it from light settings
  605. if (!Sun)
  606. Sun = RenderSettings.sun;
  607. //not yet?
  608. if (!Sun)
  609. foreach (Light TempLight in SceneLights)
  610. {
  611. if (TempLight.type == LightType.Directional)
  612. {
  613. Sun = TempLight;
  614. break;
  615. }
  616. }
  617. if (Sun == null)
  618. {
  619. Debug.LogError("Fog Volume: No valid light found\nDirectional light is required. Light component can be disabled.");
  620. return;
  621. }
  622. else
  623. {
  624. //remove fog layers from light 3.1.8. Light must not affect the volume we want to use as density for the screen effect
  625. Sun.cullingMask &= ~(1 << LayerMask.NameToLayer("FogVolumeUniform"));
  626. Sun.cullingMask &= ~(1 << LayerMask.NameToLayer("FogVolume"));
  627. Sun.cullingMask &= ~(1 << LayerMask.NameToLayer("FogVolumeSurrogate"));
  628. // Sun.cullingMask &= ~(1 << LayerMask.NameToLayer("FogVolumeShadowCaster"));
  629. }
  630. }
  631. private Plane[] FrustumPlanes;
  632. Camera GameCamera;
  633. Material SurrogateMaterial;
  634. BoxCollider _BoxCollider;
  635. public FogVolumeData _FogVolumeData;
  636. GameObject _FogVolumeDataGO;
  637. public void FindFogVolumeData()
  638. {
  639. if (_FogVolumeDataGO == null)
  640. {
  641. FogVolumeData[] aFVD = FindObjectsOfType<FogVolumeData>();
  642. if (aFVD.Length == 0)
  643. {
  644. _FogVolumeDataGO = new GameObject();
  645. _FogVolumeData = _FogVolumeDataGO.AddComponent<FogVolumeData>();
  646. _FogVolumeDataGO.name = "Fog Volume Data";
  647. }
  648. else
  649. {
  650. _FogVolumeDataGO = aFVD[0].gameObject;
  651. _FogVolumeData = aFVD[0];
  652. }
  653. }
  654. else { _FogVolumeData = _FogVolumeDataGO.GetComponent<FogVolumeData>(); }
  655. }
  656. /* With ExcludeFromLowRes enabled a textured FV is excluded from the low-res process.
  657. * So it can be rendered by another camera, for example, a water reflection or refraction camera
  658. * Then, we have to feed it with a custom DepthTexture that ignores the clip planes. _CameraDepthTexture is not valid because
  659. * the clip planes of a camera like MirrorReflection.cs break FV. The provided shader Depth.shader will generate
  660. * a valid depth texture
  661. */
  662. public bool ExcludeFromLowRes = false;
  663. void MoveToLayer()
  664. {
  665. if (!CastShadows)
  666. {
  667. if (!ExcludeFromLowRes)
  668. {
  669. if (_FogType == FogType.Textured)
  670. {
  671. if (FogVolumeGameObject.layer != LayerMask.NameToLayer("FogVolume"))
  672. {
  673. FogVolumeGameObject.layer = LayerMask.NameToLayer("FogVolume");
  674. // print("Moved to FogVolume layer");
  675. }
  676. }
  677. else
  678. {
  679. if (FogVolumeGameObject.layer != LayerMask.NameToLayer("FogVolumeUniform"))
  680. {
  681. FogVolumeGameObject.layer = LayerMask.NameToLayer("FogVolumeUniform");
  682. // FogMaterial.DisableKeyword("ExternalDepth");
  683. }
  684. }
  685. }
  686. }
  687. }
  688. public void AssignCamera()
  689. {
  690. FindFogVolumeData();
  691. if (_FogVolumeDataGO == null) return;//wait til update check
  692. if (_FogVolumeData.GetFogVolumeCamera != null)
  693. GameCameraGO = _FogVolumeData.GetFogVolumeCamera.gameObject;
  694. if (GameCameraGO == null)
  695. {
  696. //Debug.Log("No camera available in "+gameObject.name);
  697. this.enabled = false;
  698. return;
  699. }
  700. else
  701. this.enabled = true;
  702. GameCamera = GameCameraGO.GetComponent<Camera>();
  703. _FogVolumeRenderer = GameCameraGO.GetComponent<FogVolumeRenderer>();
  704. if (_FogVolumeRenderer == null)
  705. {
  706. if (!_FogVolumeData.ForceNoRenderer)
  707. {
  708. _FogVolumeRenderer = GameCameraGO.AddComponent<FogVolumeRenderer>();
  709. _FogVolumeRenderer.enabled = true;
  710. }
  711. }
  712. else
  713. if (_FogVolumeData.ForceNoRenderer == false)//3.1.8 Lets preserve that option
  714. _FogVolumeRenderer.enabled = true;
  715. }
  716. void SetIcon()
  717. {
  718. #if UNITY_EDITOR
  719. Texture Icon = Resources.Load("FogVolumeIcon") as Texture;
  720. //Icon.hideFlags = HideFlags.HideAndDontSave;
  721. var editorGUI = typeof(EditorGUIUtility);
  722. var bindingFlags = BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic;
  723. var args = new object[] { gameObject, Icon };
  724. editorGUI.InvokeMember("SetIconForObject", bindingFlags, null, null, args);
  725. #endif
  726. }
  727. int MessageDelay;
  728. void OnEnable()
  729. {
  730. m_lightManager = null;
  731. m_primitiveManager = null;
  732. #if UNITY_EDITOR
  733. m_prevFVName = gameObject.name;
  734. fogMaterial = null;
  735. #endif
  736. SetIcon();
  737. //Low resolution renderer setup
  738. AssignCamera();
  739. SurrogateMaterial = Resources.Load("Fog Volume Surrogate", typeof(Material)) as Material;
  740. FindDirectionalLight();
  741. _BoxCollider = GetComponent<BoxCollider>();
  742. if (_BoxCollider == null)
  743. _BoxCollider = gameObject.AddComponent<BoxCollider>();
  744. _BoxCollider.hideFlags = HideFlags.HideAndDontSave;
  745. _BoxCollider.isTrigger = true;
  746. FogVolumeGameObject = this.gameObject;
  747. #if UNITY_EDITOR
  748. CreateLayer("FogVolumeShadowCaster");
  749. CreateLayer("FogVolume");
  750. CreateLayer("FogVolumeSurrogate");
  751. CreateLayer("FogVolumeUniform");
  752. #endif
  753. FogRenderer = FogVolumeGameObject.GetComponent<MeshRenderer>();
  754. if (FogRenderer == null)
  755. FogRenderer = FogVolumeGameObject.AddComponent<MeshRenderer>();
  756. FogRenderer.sharedMaterial = FogMaterial;
  757. ToggleKeyword();
  758. // FogRenderer.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off;
  759. //Shadow cam setup (GO, camera, components)
  760. if (FogRenderer.shadowCastingMode == UnityEngine.Rendering.ShadowCastingMode.On)
  761. {
  762. string ShadowCameraName = FogVolumeGameObject.name + " Shadow Camera";
  763. ShadowCameraGO = GameObject.Find(ShadowCameraName);
  764. if (ShadowCameraGO == null)
  765. {
  766. ShadowCameraGO = new GameObject(ShadowCameraName);
  767. ShadowCameraGO.transform.parent = FogVolumeGameObject.transform;
  768. ShadowCameraGO.AddComponent<Camera>();
  769. Camera ShadowCamera = ShadowCameraGO.GetComponent<Camera>();
  770. ShadowCamera.orthographic = true;
  771. ShadowCamera.depth = -6;
  772. ShadowCamera.clearFlags = CameraClearFlags.Color;
  773. ShadowCamera.backgroundColor = new Color(0, 0, 0, 0);
  774. ShadowCamera.allowHDR = false;
  775. ShadowCamera.allowMSAA = false;
  776. _ShadowCamera = ShadowCameraGO.AddComponent<ShadowCamera>();
  777. }
  778. //ShadowCameraGO.hideFlags = HideFlags.None;
  779. ShadowCameraGO.hideFlags = HideFlags.HideInHierarchy;
  780. _ShadowCamera = ShadowCameraGO.GetComponent<ShadowCamera>();
  781. ShadowMapSetup();
  782. //-----------------------------
  783. }
  784. if (filter == null)
  785. {
  786. filter = gameObject.GetComponent<MeshFilter>();
  787. CreateBoxMesh(transform.localScale);
  788. transform.localScale = Vector3.one;
  789. }
  790. filter.hideFlags = HideFlags.HideInInspector;
  791. UpdateBoxMesh();
  792. _PerformanceLUT = Resources.Load("PerformanceLUT") as Texture2D;
  793. //first check
  794. GetShadowMap();
  795. _FogVolumeData.FindFogVolumes();//3.2
  796. #region LoadBackgroundImages
  797. #if UNITY_EDITOR
  798. // string BackgroundImagesPath = Application.dataPath + "/FogVolume/Scripts/Themes/png";
  799. #endif
  800. #endregion
  801. if (FrustumPlanes == null) { FrustumPlanes = new Plane[6]; }
  802. _InitializeLightManagerIfNeccessary();
  803. _InitializePrimitiveManagerIfNeccessary();
  804. }
  805. public float PointLightCPUMaxDistance = 1;
  806. GameObject PointLightsCameraGO = null;
  807. Camera PointLightsCamera = null;
  808. float GetPointLightDistance2Camera(Vector3 lightPosition)
  809. {
  810. PointLightsCameraGO = Camera.current.gameObject;//so it works in scene view too
  811. float Distance = (lightPosition - PointLightsCameraGO.transform.position).magnitude;
  812. // print(Distance);
  813. return Distance;
  814. }
  815. public float PointLightScreenMargin = 1f;
  816. //bool PointLightRangeVisible(PointLight p)
  817. //{
  818. // Collider pCol = p.GetComponent<SphereCollider>();
  819. // bool visible = true;
  820. // if (Application.isPlaying)
  821. // {
  822. // if (GeometryUtility.TestPlanesAABB(FrustumPlanes, pCol.bounds))
  823. // visible = true;
  824. // else
  825. // visible = false;
  826. // }
  827. // else
  828. // visible = PointIsVisible(p.transform.position);
  829. // // print(visible);
  830. // return visible;
  831. //}
  832. bool PointIsVisible(Vector3 point)
  833. {
  834. PointLightsCamera = PointLightsCameraGO.GetComponent<Camera>();//for scene view!
  835. //possible TODO: attenuate light when it is outside view
  836. float marginNeg = 0 - PointLightScreenMargin;
  837. float marginPos = 1 + PointLightScreenMargin;
  838. bool visible = true;
  839. Vector3 screenPoint = PointLightsCamera.WorldToViewportPoint(point);
  840. if (screenPoint.z > marginNeg && screenPoint.x > marginNeg && screenPoint.x < marginPos
  841. && screenPoint.y > marginNeg && screenPoint.y < marginPos)
  842. {
  843. // print("visible");
  844. visible = true;
  845. }
  846. else
  847. {
  848. //print("no visible");
  849. visible = false;
  850. }
  851. return visible;
  852. }
  853. //bool isPointLightInVisibleRange(PointLight light)
  854. //{
  855. // Vector3 position = light.gameObject.transform.position;
  856. // float Distance = GetPointLightDistance2Camera(position);
  857. // if (Distance > PointLightingDistance2Camera)
  858. // return false;
  859. // else
  860. // {
  861. // return PointLightRangeVisible(light);
  862. // }
  863. //}
  864. public bool PointLightsRealTimeUpdate = true;
  865. public bool PointLightBoxCheck = true;
  866. public bool PointIsInsideVolume(Vector3 PointPosition)
  867. {
  868. //todo: rotation!
  869. bool result = false;
  870. float FogVolumeXmax = gameObject.transform.position.x + fogVolumeScale.x / 2;
  871. float FogVolumeXmin = gameObject.transform.position.x - fogVolumeScale.x / 2;
  872. float FogVolumeYmax = gameObject.transform.position.y + fogVolumeScale.y / 2;
  873. float FogVolumeYmin = gameObject.transform.position.y - fogVolumeScale.y / 2;
  874. float FogVolumeZmax = gameObject.transform.position.z + fogVolumeScale.z / 2;
  875. float FogVolumeZmin = gameObject.transform.position.z - fogVolumeScale.z / 2;
  876. if (FogVolumeXmax > PointPosition.x && FogVolumeXmin < PointPosition.x)
  877. {
  878. // print("x dentro");
  879. if (FogVolumeYmax > PointPosition.y && FogVolumeYmin < PointPosition.y)
  880. {
  881. // print("y dentro");
  882. if (FogVolumeZmax > PointPosition.z && FogVolumeZmin < PointPosition.z)
  883. {
  884. // print("dentro");
  885. result = true;
  886. }
  887. }
  888. }
  889. // else
  890. // print("fuera");
  891. // print("nombre luz: " + FogLights.name);
  892. // print("x maximo: " + FogVolumeXmax + " x minimo: " + FogVolumeXmin);
  893. return result;
  894. }
  895. /*
  896. Vector4[] PrimitivePositions = new Vector4[20];
  897. Transform[] PrimitivePositionsTransform = new Transform[20];
  898. public Vector4[] GetPrimitivesPositions()
  899. {
  900. int index = 0;
  901. foreach (FogVolumePrimitive guy in PrimitivesList)
  902. {
  903. index = Mathf.Min(16, index);
  904. PrimitivePositionsTransform[index] = guy.GetTransform;
  905. PrimitivePositions[index] = this.gameObject.transform.
  906. InverseTransformPoint(PrimitivePositionsTransform[index].position);
  907. index++;
  908. }
  909. return PrimitivePositions;
  910. }
  911. Matrix4x4[] PrimitivesMatrixTransform = new Matrix4x4[20];
  912. Transform[] PrimitivesTransform = new Transform[20];
  913. public Matrix4x4[] GetPrimitivesTransform()
  914. {
  915. int index = 0;
  916. foreach (FogVolumePrimitive guy in PrimitivesList)
  917. {
  918. PrimitivesTransform[index] = guy.GetTransform;
  919. PrimitivesMatrixTransform[index].SetTRS(
  920. PrimitivesTransform[index].position,
  921. Quaternion.Inverse(PrimitivesTransform[index].rotation) * (gameObject.transform.rotation),
  922. Vector3.one
  923. )
  924. ;
  925. // MatrixTransform[index] = MatrixTransform[index].inverse;
  926. index++;
  927. }
  928. return PrimitivesMatrixTransform;
  929. }
  930. Vector4[] Scales = new Vector4[20];
  931. public Vector4[] GetPrimitivesScale()
  932. {
  933. int index = 0;
  934. foreach (FogVolumePrimitive guy in PrimitivesList)
  935. {
  936. Scales[index] = guy.GetPrimitiveScale;
  937. index++;
  938. }
  939. return Scales;
  940. }
  941. */
  942. // Vector4[] PointlightPositions = new Vector4[256];
  943. // Transform[] PointlightPositionsTransform = new Transform[256];
  944. //public Vector4[] GetPointLightPositions()
  945. //{
  946. // int index = 0;
  947. // if (PointLightsList.Count > 0)
  948. // foreach (PointLight guy in PointLightsList)
  949. // {
  950. // index = Mathf.Min(255, index);
  951. // // Positions[index] = guy.GetPointLightPosition;
  952. // if (guy != null)
  953. // {
  954. // PointlightPositionsTransform[index] = guy.GetTransform;
  955. // PointlightPositions[index] = this.gameObject.transform.
  956. // InverseTransformPoint(PointlightPositionsTransform[index].position);
  957. // }
  958. // index++;
  959. // }
  960. // return PointlightPositions;
  961. //}
  962. Vector3 LocalDirectionalSunLight(Light Sun)
  963. {
  964. return transform.InverseTransformVector(-Sun.transform.forward);
  965. }
  966. // Color[] PointlightColors = new Color[256];
  967. //public Color[] GetPointLightColors()
  968. //{
  969. // int index = 0;
  970. // if (PointLightsList.Count > 0)
  971. // foreach (PointLight guy in PointLightsList)
  972. // {
  973. // index = Mathf.Min(255, index);
  974. // if (guy != null)
  975. // PointlightColors[index] = guy.GetPointLightColor;
  976. // index++;
  977. // }
  978. // return PointlightColors;
  979. //}
  980. // float[] PointLightIntensity = new float[256];
  981. //public float[] GetPointLightIntensity()
  982. //{
  983. // int index = 0;
  984. // if (PointLightsList.Count > 0)
  985. // foreach (PointLight guy in PointLightsList)
  986. // {
  987. // index = Mathf.Min(255, index);
  988. // if (guy != null)
  989. // {
  990. // PointLightIntensity[index] = guy.GetPointLightIntensity * PointLightsIntensity
  991. // //distance fade
  992. // * (1 - Mathf.Clamp01(GetPointLightDistance2Camera(guy.gameObject.transform.position) / PointLightingDistance2Camera));
  993. // }
  994. // index++;
  995. // }
  996. // return PointLightIntensity;
  997. //}
  998. // float[] PointlightRange = new float[256];
  999. //public float[] GetPointLightRanges()
  1000. //{
  1001. // int index = 0;
  1002. // if (PointLightsList.Count > 0)
  1003. // foreach (PointLight guy in PointLightsList)
  1004. // {
  1005. // index = Mathf.Min(256, index);
  1006. // if (guy != null)
  1007. // PointlightRange[index] = guy.GetPointLightRange;
  1008. // index++;
  1009. // }
  1010. // return PointlightRange;
  1011. //}
  1012. /*
  1013. void PrimitivesVisible()
  1014. {
  1015. int index = 0;
  1016. foreach (FogVolumePrimitive guy in PrimitivesList)
  1017. {
  1018. if (guy == null)
  1019. {
  1020. PrimitivesList.Remove(guy);
  1021. break;
  1022. }
  1023. if (guy)
  1024. {
  1025. if (ShowPrimitives)
  1026. guy.GetComponent<Renderer>().enabled = true;
  1027. else
  1028. guy.GetComponent<Renderer>().enabled = false;
  1029. }
  1030. index++;
  1031. }
  1032. }
  1033. */
  1034. public bool PrimitivesRealTimeUpdate = true;
  1035. /*
  1036. public FogVolumePrimitive[] Primitives;
  1037. void ClearPrimitiveList()
  1038. {
  1039. if (PrimitivesList != null && PrimitivesRealTimeUpdate)
  1040. PrimitivesList.Clear();
  1041. if (PrimitivesList == null)
  1042. PrimitivesList = new List<FogVolumePrimitive>();
  1043. }
  1044. void CreatePrimitiveList()
  1045. {
  1046. if (PrimitivesRealTimeUpdate)
  1047. Primitives = FindObjectsOfType(typeof(FogVolumePrimitive)) as FogVolumePrimitive[];
  1048. ClearPrimitiveList();
  1049. for (int i = 0; i < Primitives.Length; i++)
  1050. {
  1051. if (Primitives[i] != null &&
  1052. Primitives[i].GetComponent<FogVolumePrimitive>().enabled &&
  1053. PointIsInsideVolume(Primitives[i].transform.position))
  1054. {
  1055. if (PrimitivesRealTimeUpdate)
  1056. PrimitivesList.Add(Primitives[i]);
  1057. }
  1058. }
  1059. PrimitivesVisible();
  1060. }
  1061. */
  1062. void OnDisable()
  1063. {
  1064. m_lightManager = null;
  1065. m_primitiveManager = null;
  1066. }
  1067. static public void Wireframe(GameObject obj, bool Enable)
  1068. {
  1069. #if UNITY_EDITOR
  1070. //not valid in 5.5
  1071. // EditorUtility.SetSelectedWireframeHidden(obj.GetComponent<Renderer>(), Enable);
  1072. if (Enable)
  1073. EditorUtility.SetSelectedRenderState(obj.GetComponent<Renderer>(), EditorSelectedRenderState.Wireframe);
  1074. else
  1075. EditorUtility.SetSelectedRenderState(obj.GetComponent<Renderer>(), EditorSelectedRenderState.Highlight);
  1076. #endif
  1077. }
  1078. void OnBecameVisible()
  1079. { }
  1080. public bool IsVisible;
  1081. void GetShadowMap()
  1082. {
  1083. if (!FogRenderer)
  1084. FogRenderer = FogVolumeGameObject.GetComponent<MeshRenderer>();
  1085. //if (FogRenderer.isVisible){//Visible by ANY camera '-_-
  1086. if (IsVisible)
  1087. {
  1088. if (FogRenderer != null && FogRenderer.shadowCastingMode == UnityEngine.Rendering.ShadowCastingMode.Off)
  1089. {
  1090. CastShadows = false;
  1091. }
  1092. if (FogRenderer.shadowCastingMode == UnityEngine.Rendering.ShadowCastingMode.On)
  1093. {
  1094. if (_FogType == FogType.Textured)
  1095. CastShadows = true;
  1096. else
  1097. FogRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;//revert if fog is uniform
  1098. }
  1099. //allow self shadows? not for now, since the result will be incorrect
  1100. //if (FogRenderer.receiveShadows)
  1101. // CastShadows = false;
  1102. if (CastShadows && _ShadowCamera == null)
  1103. {
  1104. ShadowMapSetup();
  1105. RT_OpacityBlur = _ShadowCamera.GetOpacityBlurRT();
  1106. }
  1107. if (_ShadowCamera)
  1108. {
  1109. //_ShadowCamera.enabled = CastShadows;
  1110. ShadowCameraGO.SetActive(CastShadows);
  1111. }
  1112. if (CastShadows)
  1113. {
  1114. RT_Opacity = _ShadowCamera.GetOpacityRT();
  1115. // Debug.Log(RT_Opacity);
  1116. }
  1117. else if (ShadowCaster && FogRenderer.receiveShadows)
  1118. {
  1119. RT_Opacity = ShadowCaster.RT_Opacity;
  1120. RT_OpacityBlur = ShadowCaster.RT_OpacityBlur;
  1121. //same dimensions than caster
  1122. fogVolumeScale.x = ShadowCaster.fogVolumeScale.x;
  1123. fogVolumeScale.z = fogVolumeScale.x;
  1124. }
  1125. if (CastShadows)
  1126. {
  1127. FogVolumeGameObject.layer = LayerMask.NameToLayer("FogVolumeShadowCaster");
  1128. }
  1129. // else
  1130. // FogVolumeGameObject.layer = LayerMask.NameToLayer("FogVolume");
  1131. //if (!CastShadows && !RT_Opacity)
  1132. // FogMaterial.SetTexture("LightshaftTex", null);
  1133. if (CastShadows && ShadowCaster)
  1134. FogMaterial.DisableKeyword("VOLUME_SHADOWS");
  1135. if (ShadowCaster && ShadowCaster.CastShadows || FogRenderer.receiveShadows)
  1136. FogMaterial.EnableKeyword("VOLUME_SHADOWS");
  1137. if (ShadowCaster && !ShadowCaster.CastShadows || !FogRenderer.receiveShadows)
  1138. FogMaterial.DisableKeyword("VOLUME_SHADOWS");
  1139. }
  1140. }
  1141. public bool CreateSurrogate = true;
  1142. // private float m_cameraNearClipPlane = 0.0f;
  1143. // private float m_cameraFarClipPlane = 0.0f;
  1144. public bool InjectCustomDepthBuffer = false;
  1145. void Update()
  1146. {
  1147. #if UNITY_EDITOR
  1148. if (MessageDelay < 101)
  1149. MessageDelay++;
  1150. if(MessageDelay>100)
  1151. if (GameCamera.depthTextureMode == DepthTextureMode.None)
  1152. Debug.LogWarning("............ATTENTION, this camera is not generating the required Depth for Fog Volume. " +
  1153. "Add -EnableDepthInForwardCamera.cs- to this camera");
  1154. if (RequestSavingMaterials)
  1155. {
  1156. CreateMaterial();
  1157. RequestSavingMaterials = false;
  1158. }
  1159. if (FogVolumeGameObject.name != m_prevFVName)
  1160. {
  1161. if (SaveMaterials)
  1162. {
  1163. RemoveMaterial();
  1164. m_prevFVName = FogVolumeGameObject.name;
  1165. CreateMaterial();
  1166. }
  1167. }
  1168. #endif
  1169. //External depth:
  1170. if (InjectCustomDepthBuffer && FogMaterial.IsKeywordEnabled("ExternalDepth") == false && ExcludeFromLowRes)
  1171. {
  1172. FogMaterial.EnableKeyword("ExternalDepth");
  1173. // Debug.Log("Enabled keyword ExternalDepth");
  1174. }
  1175. if (FogMaterial.IsKeywordEnabled("ExternalDepth") == true && ExcludeFromLowRes && !InjectCustomDepthBuffer)
  1176. {
  1177. FogMaterial.DisableKeyword("ExternalDepth");
  1178. // Debug.Log("Disabled keyword ExternalDepth");
  1179. }
  1180. //Debug.Log("Rendering " + gameObject.name + "\n Layer: " + LayerMask.LayerToName(gameObject.layer) + "\n External depth keyword: " + FogMaterial.IsKeywordEnabled("ExternalDepth"));
  1181. //#if UNITY_EDITOR
  1182. if (GameCamera == null)
  1183. AssignCamera();
  1184. //#endif
  1185. if (PointLightCullSizeMultiplier < 1.0f) { PointLightCullSizeMultiplier = 1.0f; }
  1186. if (m_lightManager != null)
  1187. {
  1188. m_lightManager.DrawDebugData = ShowDebugGizmos;
  1189. m_lightManager.SetPointLightCullSizeMultiplier(PointLightCullSizeMultiplier);
  1190. }
  1191. if (m_primitiveManager != null) { m_primitiveManager.SetVisibility(ShowPrimitives); }
  1192. if (GameCamera != null)
  1193. {
  1194. //if ((GameCamera.nearClipPlane != m_cameraNearClipPlane) ||
  1195. // (GameCamera.farClipPlane != m_cameraFarClipPlane))
  1196. //{
  1197. // m_cameraNearClipPlane = GameCamera.nearClipPlane;
  1198. // m_cameraFarClipPlane = GameCamera.farClipPlane;
  1199. FrustumPlanes = GeometryUtility.CalculateFrustumPlanes(GameCamera);
  1200. // }
  1201. if (Application.isPlaying)
  1202. {
  1203. if (GeometryUtility.TestPlanesAABB(FrustumPlanes, _BoxCollider.bounds))
  1204. {
  1205. IsVisible = true;
  1206. // Debug.Log(gameObject.name + " Visible by "+ GameCamera.name);
  1207. }
  1208. else
  1209. {
  1210. IsVisible = false;
  1211. // Debug.Log(gameObject.name + " Not visible by " + GameCamera.name);
  1212. }
  1213. }
  1214. else
  1215. IsVisible = true;
  1216. }
  1217. // print(IsVisible);
  1218. if (EnableNoise || EnableGradient)
  1219. _FogType = FogType.Textured;
  1220. else
  1221. _FogType = FogType.Uniform;
  1222. #if UNITY_EDITOR
  1223. UpdateBoxMesh();
  1224. ShadowProjectorLock();
  1225. Visibility = Mathf.Max(1, Visibility);
  1226. IterationStep = Mathf.Max(1, IterationStep);
  1227. //InscatteringIntensity = Mathf.Max(0, InscatteringIntensity);
  1228. //NoiseIntensity = Mathf.Max(0, NoiseIntensity);
  1229. InscatteringTransitionWideness = Mathf.Max(1, InscatteringTransitionWideness);
  1230. InscatteringStartDistance = Mathf.Max(0, InscatteringStartDistance);
  1231. if (_NoiseVolume == null)
  1232. EnableNoise = false;
  1233. fogVolumeScale.x = Mathf.Max(fogVolumeScale.x, .001f);
  1234. fogVolumeScale.y = Mathf.Max(fogVolumeScale.y, .001f);
  1235. fogVolumeScale.z = Mathf.Max(fogVolumeScale.z, .001f);
  1236. if (ShadowProjector == null && CastShadows)
  1237. {
  1238. // print("ShadowMapSetup()");
  1239. ShadowMapSetup();
  1240. }
  1241. SetShadowProyectorLayer();
  1242. if (!Sun) FindDirectionalLight();
  1243. MoveToLayer();
  1244. StaticEditorFlags flags;
  1245. flags = GameObjectUtility.GetStaticEditorFlags(gameObject);
  1246. if (_VisibleByReflectionProbeStatic && GameObjectUtility.GetStaticEditorFlags(gameObject) != StaticEditorFlags.ReflectionProbeStatic)
  1247. {
  1248. //print("Fog Volume visible for Static reflection probes");
  1249. GameObjectUtility.SetStaticEditorFlags(gameObject, StaticEditorFlags.ReflectionProbeStatic);
  1250. }
  1251. if (!_VisibleByReflectionProbeStatic && flags == StaticEditorFlags.ReflectionProbeStatic)
  1252. {
  1253. // print("Fog Volume not visible for Static reflection probes");
  1254. flags = flags & ~StaticEditorFlags.ReflectionProbeStatic;
  1255. GameObjectUtility.SetStaticEditorFlags(gameObject, flags);
  1256. }
  1257. #endif
  1258. RenderSurrogate();
  1259. if (ShadowProjector != null && CastShadows)
  1260. {
  1261. // ShadowProjectorMaterial.SetTexture("_MainTex", RT_OpacityBlur);
  1262. ShadowProjectorMaterial.SetColor("_ShadowColor", ShadowColor);
  1263. }
  1264. // FogMaterial.SetTexture("LightshaftTex", RT_Opacity);
  1265. //if (Camera.current != null)
  1266. //{
  1267. // Vector3 ForwardCameraVector = Camera.current.transform.forward;
  1268. // FogMaterial.SetVector("_SliceNormal", ForwardCameraVector);
  1269. // print(ForwardCameraVector);
  1270. //}
  1271. //
  1272. if (FogMaterial.GetTexture("_NoiseVolume") == null && _NoiseVolume != null || FogMaterial.GetTexture("_NoiseVolume") != _NoiseVolume)
  1273. {
  1274. FogMaterial.SetTexture("_NoiseVolume", _NoiseVolume);
  1275. // Debug.Log("Updating tex");
  1276. }
  1277. if (FogMaterial.GetTexture("_NoiseVolume2") == null && _NoiseVolume2 != null || FogMaterial.GetTexture("_NoiseVolume2") != _NoiseVolume2)
  1278. {
  1279. FogMaterial.SetTexture("_NoiseVolume2", _NoiseVolume2);
  1280. }
  1281. if (FogMaterial.GetTexture("CoverageTex") == null && CoverageTex != null || FogMaterial.GetTexture("CoverageTex") != CoverageTex)
  1282. {
  1283. FogMaterial.SetTexture("CoverageTex", CoverageTex);
  1284. }
  1285. //GetComponent<LightProbeProxyVolume>().Update();
  1286. }
  1287. public void RenderSurrogate()
  1288. {
  1289. if (IsVisible)
  1290. {
  1291. if (GameCameraGO == null) AssignCamera();
  1292. var renderer = GameCameraGO.GetComponent<FogVolumeRenderer>();
  1293. if (renderer == null)
  1294. {
  1295. if (!_FogVolumeData.ForceNoRenderer)
  1296. {
  1297. renderer = GameCameraGO.AddComponent<FogVolumeRenderer>();
  1298. renderer.enabled = true;
  1299. }
  1300. }
  1301. if (!_FogVolumeData.ForceNoRenderer && renderer._Downsample > 0 && CreateSurrogate && mesh != null &&
  1302. _FogType == FogVolume.FogType.Textured)
  1303. {
  1304. Graphics.DrawMesh(mesh, transform.position, transform.rotation, SurrogateMaterial,
  1305. LayerMask.NameToLayer("FogVolumeSurrogate"),
  1306. //GameCamera,//it blinks
  1307. null,
  1308. 0, null, false, false, false);
  1309. // if(EnableNoise)
  1310. // FogMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
  1311. }
  1312. }
  1313. }
  1314. void UpdateParams()
  1315. {
  1316. if (IsVisible)
  1317. {
  1318. if (_PerformanceLUT && _DebugMode == DebugMode.Iterations)
  1319. FogMaterial.SetTexture("_PerformanceLUT", _PerformanceLUT);
  1320. if (_DebugMode != DebugMode.Lit)
  1321. FogMaterial.SetInt("_DebugMode", (int)_DebugMode);
  1322. if (FogType.Textured == _FogType)
  1323. {
  1324. FogMaterial.SetInt("_SrcBlend", (int)_BlendMode);
  1325. // print((int)_BlendMode);
  1326. }
  1327. else
  1328. //set it as standard alpha blend for uniform fog
  1329. FogMaterial.SetInt("_SrcBlend", (int)FogVolumeRenderer.BlendMode.TraditionalTransparency);
  1330. FogMaterial.SetInt("_ztest", (int)_ztest);
  1331. Profiler.BeginSample("FogVolume Pointlights update");
  1332. if (m_lightManager != null)
  1333. {
  1334. if (m_lightManager.CurrentLightCount > 0 &&
  1335. PointLightsActive &&
  1336. SystemInfo.graphicsShaderLevel > 30)
  1337. {
  1338. FogMaterial.SetVectorArray("_LightPositions",
  1339. m_lightManager.GetLightPositionArray());
  1340. FogMaterial.SetVectorArray("_LightRotations", m_lightManager.GetLightRotationArray());
  1341. FogMaterial.SetColorArray("_LightColors", m_lightManager.GetLightColorArray());
  1342. FogMaterial.SetVectorArray("_LightData", m_lightManager.GetLightData());
  1343. FogMaterial.SetFloat("PointLightingDistance", 1.0f / PointLightingDistance);//spherical range clamp
  1344. FogMaterial.SetFloat("PointLightingDistance2Camera",
  1345. 1.0f / PointLightingDistance2Camera);//draw distance
  1346. }
  1347. }
  1348. Profiler.EndSample();
  1349. Profiler.BeginSample("FogVolume Primitives update");
  1350. if (m_primitiveManager != null)
  1351. if (m_primitiveManager.CurrentPrimitiveCount > 0 && EnableDistanceFields)
  1352. {
  1353. FogMaterial.SetFloat("Constrain", Constrain);
  1354. FogMaterial.SetVectorArray("_PrimitivePosition", m_primitiveManager.GetPrimitivePositionArray());
  1355. FogMaterial.SetVectorArray("_PrimitiveScale", m_primitiveManager.GetPrimitiveScaleArray());
  1356. FogMaterial.SetInt("_PrimitiveCount", m_primitiveManager.VisiblePrimitiveCount);
  1357. FogMaterial.SetMatrixArray("_PrimitivesTransform", m_primitiveManager.GetPrimitiveTransformArray());
  1358. FogMaterial.SetFloat("_PrimitiveEdgeSoftener", 1 / _PrimitiveEdgeSoftener);
  1359. FogMaterial.SetFloat("_PrimitiveCutout", _PrimitiveCutout);
  1360. FogMaterial.SetVectorArray("_PrimitiveData", m_primitiveManager.GetPrimitiveDataArray());
  1361. }
  1362. Profiler.EndSample();
  1363. Profiler.BeginSample("FogVolume PARAMETERS");
  1364. // FogMaterial.SetVector("_CameraForward", Camera.current.transform.forward);
  1365. if (Sun && Sun.enabled)
  1366. {
  1367. FogMaterial.SetFloat("_LightExposure", _LightExposure);
  1368. if (LightHalo && _LightHaloTexture)
  1369. {
  1370. FogMaterial.SetTexture("_LightHaloTexture", _LightHaloTexture);
  1371. FogMaterial.SetFloat("_HaloOpticalDispersion", _HaloOpticalDispersion);
  1372. FogMaterial.SetFloat("_HaloWidth", _HaloWidth.Remap(0, 1, 10, 1));
  1373. FogMaterial.SetFloat("_HaloIntensity", _HaloIntensity * 2000);
  1374. FogMaterial.SetFloat("_HaloRadius", _HaloRadius.Remap(0, 1, 2, .1f));
  1375. FogMaterial.SetFloat("_HaloAbsorption", _HaloAbsorption.Remap(0, 1, 0, 16));
  1376. }
  1377. FogMaterial.SetVector("L", -Sun.transform.forward);
  1378. Shader.SetGlobalVector("L", -Sun.transform.forward);
  1379. FogMaterial.SetVector("_LightLocalDirection", LocalDirectionalSunLight(Sun));
  1380. if (EnableInscattering)
  1381. {
  1382. FogMaterial.SetFloat("_InscatteringIntensity", InscatteringIntensity * 50);
  1383. FogMaterial.SetFloat("InscatteringShape", InscatteringShape);
  1384. FogMaterial.SetFloat("InscatteringTransitionWideness", InscatteringTransitionWideness);
  1385. FogMaterial.SetColor("_InscatteringColor", InscatteringColor);
  1386. }
  1387. if (VolumeFogInscattering)
  1388. {
  1389. FogMaterial.SetFloat("VolumeFogInscatteringIntensity", VolumeFogInscatteringIntensity * 50);
  1390. FogMaterial.SetFloat("VolumeFogInscatteringAnisotropy", VolumeFogInscatteringAnisotropy);
  1391. FogMaterial.SetColor("VolumeFogInscatteringColor", VolumeFogInscatteringColor);
  1392. VolumeFogInscatteringStartDistance = Mathf.Max(0, VolumeFogInscatteringStartDistance);
  1393. FogMaterial.SetFloat("VolumeFogInscatteringStartDistance", VolumeFogInscatteringStartDistance);
  1394. VolumeFogInscatteringTransitionWideness = Mathf.Max(.01f, VolumeFogInscatteringTransitionWideness);
  1395. FogMaterial.SetFloat("VolumeFogInscatteringTransitionWideness", VolumeFogInscatteringTransitionWideness);
  1396. }
  1397. FogMaterial.SetColor("_LightColor", Sun.color * Sun.intensity);
  1398. if (EnableNoise && _NoiseVolume != null)
  1399. {
  1400. FogMaterial.SetFloat("_NoiseDetailRange", _NoiseDetailRange * 1f);
  1401. FogMaterial.SetFloat("_Curl", _Curl);
  1402. if (_DirectionalLighting)
  1403. {
  1404. FogMaterial.SetFloat("_DirectionalLightingDistance", _DirectionalLightingDistance);
  1405. //FogMaterial.SetFloat("DirectionalLightingClamp", DirectionalLightingClamp);
  1406. FogMaterial.SetInt("DirectLightingShadowSteps", DirectLightingShadowSteps);
  1407. FogMaterial.SetFloat("DirectLightingShadowDensity", DirectLightingShadowDensity);
  1408. }
  1409. }
  1410. }
  1411. FogMaterial.SetFloat("_Cutoff", ShadowCutoff);
  1412. FogMaterial.SetFloat("Absorption", Absorption);
  1413. LightExtinctionColor.r = Mathf.Max(.1f, LightExtinctionColor.r);
  1414. LightExtinctionColor.g = Mathf.Max(.1f, LightExtinctionColor.g);
  1415. LightExtinctionColor.b = Mathf.Max(.1f, LightExtinctionColor.b);
  1416. FogMaterial.SetColor("LightExtinctionColor", LightExtinctionColor);
  1417. //if (Procedural)
  1418. // FogMaterial.EnableKeyword("USE_PROCEDURAL");
  1419. //else
  1420. // FogMaterial.DisableKeyword("USE_PROCEDURAL");
  1421. //if (EnableNoise && _NoiseVolume)
  1422. //{
  1423. if (Vortex > 0)
  1424. {
  1425. FogMaterial.SetFloat("_Vortex", Vortex);
  1426. FogMaterial.SetFloat("_Rotation", Mathf.Deg2Rad * rotation);
  1427. FogMaterial.SetFloat("_RotationSpeed", -RotationSpeed);
  1428. }
  1429. DetailDistance = Mathf.Max(1, DetailDistance);
  1430. FogMaterial.SetFloat("DetailDistance", DetailDistance);
  1431. FogMaterial.SetFloat("Octaves", Octaves);
  1432. FogMaterial.SetFloat("_DetailMaskingThreshold", _DetailMaskingThreshold);
  1433. //FogMaterial.SetFloat("_DetailSamplingBaseOpacityLimit", DetailSamplingBaseOpacityLimit);
  1434. // FogMaterial.SetTexture("_NoiseVolume", _NoiseVolume);
  1435. //FogMaterial.SetTexture("noise2D", noise2D);
  1436. FogMaterial.SetVector("_VolumePosition", gameObject.transform.position);
  1437. FogMaterial.SetFloat("gain", NoiseIntensity);
  1438. FogMaterial.SetFloat("threshold", NoiseContrast * 0.5f - 5);
  1439. FogMaterial.SetFloat("_3DNoiseScale", _3DNoiseScale * .001f);
  1440. FadeDistance = Mathf.Max(1, FadeDistance);
  1441. FogMaterial.SetFloat("FadeDistance", FadeDistance);
  1442. FogMaterial.SetFloat("STEP_COUNT", Iterations);
  1443. FogMaterial.SetFloat("DetailTiling", DetailTiling);
  1444. FogMaterial.SetFloat("BaseTiling", BaseTiling * .1f);
  1445. FogMaterial.SetFloat("Coverage", Coverage);
  1446. FogMaterial.SetFloat("NoiseDensity", NoiseDensity);
  1447. FogMaterial.SetVector("Speed", Speed * .1f);
  1448. FogMaterial.SetVector("Stretch", new Vector4(1, 1, 1, 1) + Stretch * .01f);
  1449. if (useHeightGradient)
  1450. {
  1451. //FogMaterial.SetFloat("GradMin", GradMin);
  1452. // FogMaterial.SetFloat("GradMax", GradMax);
  1453. FogMaterial.SetVector("_VerticalGradientParams", new Vector4(GradMin, GradMax, GradMin2, GradMax2));
  1454. }
  1455. FogMaterial.SetColor("_AmbientColor", _AmbientColor);
  1456. if (FogRenderer.lightProbeUsage == UnityEngine.Rendering.LightProbeUsage.UseProxyVolume)
  1457. _ProxyVolume = true;
  1458. else _ProxyVolume = false;
  1459. FogMaterial.SetFloat("_ProxyVolume", _ProxyVolume == false ? 0 : 1);
  1460. //FogMaterial.SetFloat("Shade", Shade);
  1461. FogMaterial.SetFloat("ShadowBrightness", ShadowBrightness);
  1462. FogMaterial.SetFloat("_DetailRelativeSpeed", _DetailRelativeSpeed);
  1463. FogMaterial.SetFloat("_BaseRelativeSpeed", _BaseRelativeSpeed);
  1464. if (bSphericalFade)
  1465. {
  1466. SphericalFadeDistance = Mathf.Max(1, SphericalFadeDistance);
  1467. FogMaterial.SetFloat("SphericalFadeDistance", SphericalFadeDistance);
  1468. }
  1469. FogMaterial.SetVector("VolumeSize", new Vector4(fogVolumeScale.x, fogVolumeScale.y, fogVolumeScale.z, 0));
  1470. // }
  1471. FogMaterial.SetFloat("Exposure", Mathf.Max(0, Exposure));
  1472. FogMaterial.SetFloat("Offset", Offset);
  1473. FogMaterial.SetFloat("Gamma", Gamma);
  1474. if (Gradient != null)
  1475. FogMaterial.SetTexture("_Gradient", Gradient);
  1476. FogMaterial.SetFloat("InscatteringStartDistance", InscatteringStartDistance);
  1477. Vector3 VolumeSize = currentFogVolume;
  1478. FogMaterial.SetVector("_BoxMin", VolumeSize * -.5f);
  1479. FogMaterial.SetVector("_BoxMax", VolumeSize * .5f);
  1480. FogMaterial.SetColor("_Color", FogMainColor);
  1481. FogMaterial.SetColor("_FogColor", _FogColor);
  1482. FogMaterial.SetInt("_AmbientAffectsFogColor", _AmbientAffectsFogColor ? 1 : 0);
  1483. //FogMaterial.SetFloat("_SceneIntersectionThreshold", _SceneIntersectionThreshold);
  1484. FogMaterial.SetFloat("_SceneIntersectionSoftness", _SceneIntersectionSoftness);
  1485. // FogMaterial.SetFloat("_RayStep", IterationStep * .001f);
  1486. FogMaterial.SetFloat("_RayStep", IterationStep * .001f);
  1487. FogMaterial.SetFloat("_OptimizationFactor", _OptimizationFactor);
  1488. FogMaterial.SetFloat("_Visibility", bVolumeFog && EnableNoise &&
  1489. _NoiseVolume || EnableGradient ? Visibility * 100 : Visibility);
  1490. FogRenderer.sortingOrder = DrawOrder;
  1491. FogMaterial.SetInt("VolumeFogInscatterColorAffectedWithFogColor", VolumeFogInscatterColorAffectedWithFogColor ? 1 : 0);
  1492. FogMaterial.SetFloat("_FOV", GameCamera.fieldOfView);
  1493. FogMaterial.SetFloat("HeightAbsorption", HeightAbsorption);
  1494. FogMaterial.SetVector("_AmbientHeightAbsorption", new Vector4(HeightAbsorptionMin, HeightAbsorptionMax, HeightAbsorption, 0));
  1495. FogMaterial.SetFloat("NormalDistance", NormalDistance);
  1496. FogMaterial.SetFloat("DirectLightingAmount", DirectLightingAmount);
  1497. DirectLightingDistance = Mathf.Max(1, DirectLightingDistance);
  1498. FogMaterial.SetFloat("DirectLightingDistance", DirectLightingDistance);
  1499. FogMaterial.SetFloat("LambertianBias", LambertianBias);
  1500. //if (SceneCollision)
  1501. FogMaterial.SetFloat("_jitter", _jitter);
  1502. FogMaterial.SetInt("SamplingMethod", (int)_SamplingMethod);
  1503. //if (_FogVolumeRenderer)
  1504. FogMaterial.SetFloat("_PushAlpha", _PushAlpha);
  1505. if (_ShadeNoise && EnableNoise)
  1506. {
  1507. FogMaterial.SetColor("_SelfShadowColor", _SelfShadowColor);
  1508. FogMaterial.SetInt("_SelfShadowSteps", _SelfShadowSteps);
  1509. FogMaterial.SetFloat("ShadowShift", ShadowShift);
  1510. }
  1511. Profiler.EndSample();
  1512. }
  1513. }
  1514. void LateUpdate()
  1515. {
  1516. }
  1517. public bool UseConvolvedLightshafts = false;
  1518. void OnWillRenderObject()
  1519. {
  1520. GetShadowMap();
  1521. #if UNITY_EDITOR
  1522. ToggleKeyword();
  1523. //since I can not set a Camera in DrawMesh (It blinks all the time), I have to make the surrogate not visible in Scene view
  1524. if(Camera.current.name == "SceneCamera")
  1525. SurrogateMaterial.EnableKeyword("_EDITOR_WINDOW");
  1526. else
  1527. SurrogateMaterial.DisableKeyword("_EDITOR_WINDOW");
  1528. Wireframe(FogVolumeGameObject, HideWireframe);
  1529. if (ShadowProjector != null)
  1530. ShadowProjector.SetActive(CastShadows);
  1531. //3.1.8 added && !ShadowCaster
  1532. if (ShadowCameraGO != null && !ShadowCaster)
  1533. ShadowCameraGO.SetActive(CastShadows);
  1534. // FogMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
  1535. #endif
  1536. // if (SystemInfo.graphicsShaderLevel < 40) PointLightsActive = false;
  1537. if (PointLightsActive && SystemInfo.graphicsShaderLevel > 30)
  1538. {
  1539. _InitializeLightManagerIfNeccessary();
  1540. if (m_lightManager != null)
  1541. {
  1542. if (PointLightsRealTimeUpdate)
  1543. {
  1544. m_lightManager.Deinitialize();
  1545. if (PointLightBoxCheck) { m_lightManager.FindLightsInFogVolume(); }
  1546. else { m_lightManager.FindLightsInScene(); }
  1547. }
  1548. if (m_lightManager.AlreadyUsesTransformForPoI == false)
  1549. {
  1550. m_lightManager.SetPointOfInterest(_FogVolumeData.GameCamera.transform);
  1551. }
  1552. m_lightManager.ManualUpdate(ref FrustumPlanes);
  1553. }
  1554. FogMaterial.SetInt("_LightsCount", GetVisibleLightCount());
  1555. }
  1556. else { _DeinitializeLightManagerIfNeccessary(); }
  1557. // else
  1558. // FogMaterial.SetInt("_LightsCount", 0);
  1559. if (EnableDistanceFields)
  1560. {
  1561. _InitializePrimitiveManagerIfNeccessary();
  1562. if (m_primitiveManager != null)
  1563. {
  1564. if (PrimitivesRealTimeUpdate)
  1565. {
  1566. m_primitiveManager.Deinitialize();
  1567. m_primitiveManager.FindPrimitivesInFogVolume();
  1568. }
  1569. if (m_primitiveManager.AlreadyUsesTransformForPoI == false)
  1570. {
  1571. m_primitiveManager.SetPointOfInterest(_FogVolumeData.GameCamera.transform);
  1572. }
  1573. m_primitiveManager.ManualUpdate(ref FrustumPlanes);
  1574. }
  1575. FogMaterial.SetInt("_PrimitivesCount", GetVisiblePrimitiveCount());
  1576. }
  1577. else { _DeinitializePrimitiveManagerIfNeccessary(); }
  1578. //CreatePrimitiveList();
  1579. //3.1.7 maybe not!
  1580. //else
  1581. //if (PrimitivesList != null)
  1582. // if (PrimitivesList.Count > 0)
  1583. // PrimitivesList.Clear();
  1584. if (RT_Opacity != null)
  1585. {
  1586. Shader.SetGlobalTexture("RT_Opacity", RT_Opacity);
  1587. if (UseConvolvedLightshafts)
  1588. {
  1589. FogMaterial.SetTexture("LightshaftTex", RT_OpacityBlur);
  1590. }
  1591. else
  1592. {
  1593. FogMaterial.SetTexture("LightshaftTex", RT_Opacity);
  1594. }
  1595. }
  1596. UpdateParams();
  1597. if (!RenderableInSceneView && (Camera.current.name == "SceneCamera"))
  1598. {
  1599. // FogMaterial.EnableKeyword("RENDER_SCENE_VIEW");
  1600. FogMaterial.SetVector("_BoxMin", new Vector3(0, 0, 0));
  1601. FogMaterial.SetVector("_BoxMax", new Vector3(0, 0, 0));
  1602. }
  1603. else
  1604. {
  1605. // FogMaterial.DisableKeyword("RENDER_SCENE_VIEW");
  1606. FogMaterial.SetVector("_BoxMin", currentFogVolume * -.5f);
  1607. FogMaterial.SetVector("_BoxMax", currentFogVolume * .5f);
  1608. }
  1609. //FogMaterial.DisableKeyword("RENDER_SCENE_VIEW");
  1610. }
  1611. void ToggleKeyword()
  1612. {
  1613. if (IsVisible)
  1614. {
  1615. Profiler.BeginSample("FogVolume KEYWORDS");
  1616. if (_jitter > 0)
  1617. FogMaterial.EnableKeyword("JITTER");
  1618. else
  1619. FogMaterial.DisableKeyword("JITTER");
  1620. if (_DebugMode != DebugMode.Lit)
  1621. FogMaterial.EnableKeyword("DEBUG");
  1622. else
  1623. FogMaterial.DisableKeyword("DEBUG");
  1624. switch (_SamplingMethod)
  1625. {
  1626. case SamplingMethod.Eye2Box:
  1627. FogMaterial.DisableKeyword("SAMPLING_METHOD_ViewAligned");
  1628. FogMaterial.EnableKeyword("SAMPLING_METHOD_Eye2Box");
  1629. break;
  1630. case SamplingMethod.ViewAligned:
  1631. FogMaterial.EnableKeyword("SAMPLING_METHOD_ViewAligned");
  1632. FogMaterial.DisableKeyword("SAMPLING_METHOD_Eye2Box");
  1633. break;
  1634. }
  1635. if (LightHalo && _LightHaloTexture)
  1636. FogMaterial.EnableKeyword("HALO");
  1637. else
  1638. FogMaterial.DisableKeyword("HALO");
  1639. if (ShadowCaster != null)
  1640. {
  1641. if (ShadowCaster.SunAttached == true)
  1642. {
  1643. FogMaterial.EnableKeyword("LIGHT_ATTACHED");
  1644. }
  1645. if (ShadowCaster.SunAttached == false)
  1646. {
  1647. FogMaterial.DisableKeyword("LIGHT_ATTACHED");
  1648. }
  1649. }
  1650. if (Vortex > 0)
  1651. {
  1652. FogMaterial.EnableKeyword("Twirl");
  1653. //print((int)_VortexAxis);
  1654. switch (_VortexAxis)
  1655. {
  1656. case VortexAxis.X:
  1657. FogMaterial.EnableKeyword("Twirl_X");
  1658. FogMaterial.DisableKeyword("Twirl_Y");
  1659. FogMaterial.DisableKeyword("Twirl_Z");
  1660. break;
  1661. case VortexAxis.Y:
  1662. FogMaterial.DisableKeyword("Twirl_X");
  1663. FogMaterial.EnableKeyword("Twirl_Y");
  1664. FogMaterial.DisableKeyword("Twirl_Z");
  1665. break;
  1666. case VortexAxis.Z:
  1667. FogMaterial.DisableKeyword("Twirl_X");
  1668. FogMaterial.DisableKeyword("Twirl_Y");
  1669. FogMaterial.EnableKeyword("Twirl_Z");
  1670. break;
  1671. }
  1672. }
  1673. else
  1674. {
  1675. FogMaterial.DisableKeyword("Twirl_X");
  1676. FogMaterial.DisableKeyword("Twirl_Y");
  1677. FogMaterial.DisableKeyword("Twirl_Z");
  1678. }
  1679. if (Lambert && Sun && EnableNoise)
  1680. FogMaterial.EnableKeyword("_LAMBERT_SHADING");
  1681. else
  1682. FogMaterial.DisableKeyword("_LAMBERT_SHADING");
  1683. //POINTLIGHTS
  1684. if (/*PointLightsList != null && PointLightsList.Count > 0 &&*/
  1685. PointLightsActive && SystemInfo.graphicsShaderLevel > 30)
  1686. {
  1687. // FogMaterial.EnableKeyword("POINTLIGHTS");//not in use anymore, not needed
  1688. switch (_LightScatterMethod)
  1689. {
  1690. case LightScatterMethod.BeersLaw:
  1691. FogMaterial.EnableKeyword("ATTEN_METHOD_1");
  1692. FogMaterial.DisableKeyword("ATTEN_METHOD_2");
  1693. FogMaterial.DisableKeyword("ATTEN_METHOD_3");
  1694. // FogMaterial.DisableKeyword("ATTEN_METHOD_4");
  1695. break;
  1696. case LightScatterMethod.InverseSquare:
  1697. FogMaterial.DisableKeyword("ATTEN_METHOD_1");
  1698. FogMaterial.EnableKeyword("ATTEN_METHOD_2");
  1699. FogMaterial.DisableKeyword("ATTEN_METHOD_3");
  1700. // FogMaterial.DisableKeyword("ATTEN_METHOD_4");
  1701. break;
  1702. //case LightScatterMethod.Gaussian:
  1703. // FogMaterial.DisableKeyword("ATTEN_METHOD_1");
  1704. // FogMaterial.DisableKeyword("ATTEN_METHOD_2");
  1705. // FogMaterial.EnableKeyword("ATTEN_METHOD_3");
  1706. // FogMaterial.DisableKeyword("ATTEN_METHOD_4");
  1707. // break;
  1708. case LightScatterMethod.Linear:
  1709. FogMaterial.DisableKeyword("ATTEN_METHOD_1");
  1710. FogMaterial.DisableKeyword("ATTEN_METHOD_2");
  1711. FogMaterial.EnableKeyword("ATTEN_METHOD_3");
  1712. // FogMaterial.EnableKeyword("ATTEN_METHOD_4");
  1713. break;
  1714. }
  1715. }
  1716. else
  1717. {
  1718. FogMaterial.DisableKeyword("ATTEN_METHOD_1");
  1719. FogMaterial.DisableKeyword("ATTEN_METHOD_2");
  1720. FogMaterial.DisableKeyword("ATTEN_METHOD_3");
  1721. }
  1722. //////////////////
  1723. if (EnableNoise && _NoiseVolume && useHeightGradient)
  1724. FogMaterial.EnableKeyword("HEIGHT_GRAD");
  1725. else
  1726. FogMaterial.DisableKeyword("HEIGHT_GRAD");
  1727. if (ColorAdjust)
  1728. FogMaterial.EnableKeyword("ColorAdjust");
  1729. else
  1730. FogMaterial.DisableKeyword("ColorAdjust");
  1731. if (bVolumeFog)
  1732. FogMaterial.EnableKeyword("VOLUME_FOG");
  1733. else
  1734. FogMaterial.DisableKeyword("VOLUME_FOG");
  1735. if (FogMaterial)
  1736. {
  1737. if (EnableGradient && Gradient != null)
  1738. FogMaterial.EnableKeyword("_FOG_GRADIENT");
  1739. else
  1740. FogMaterial.DisableKeyword("_FOG_GRADIENT");
  1741. // if (EnableNoise && !SystemInfo.supports3DTextures)
  1742. // Debug.Log("Noise not supported. SM level found: " + SystemInfo.graphicsShaderLevel / 10);
  1743. if (EnableNoise/* && SystemInfo.supports3DTextures*/)
  1744. FogMaterial.EnableKeyword("_FOG_VOLUME_NOISE");
  1745. else
  1746. {
  1747. FogMaterial.DisableKeyword("_FOG_VOLUME_NOISE");
  1748. }
  1749. if (EnableInscattering && Sun && Sun.enabled && Sun.isActiveAndEnabled)
  1750. FogMaterial.EnableKeyword("_INSCATTERING");
  1751. else
  1752. FogMaterial.DisableKeyword("_INSCATTERING");
  1753. if (VolumeFogInscattering && Sun && Sun.enabled && bVolumeFog)
  1754. FogMaterial.EnableKeyword("_VOLUME_FOG_INSCATTERING");
  1755. else
  1756. FogMaterial.DisableKeyword("_VOLUME_FOG_INSCATTERING");
  1757. //if (SceneCollision)
  1758. FogMaterial.SetFloat("Collisions", SceneCollision ? 1 : 0);
  1759. // FogMaterial.EnableKeyword("_COLLISION");
  1760. // else
  1761. // FogMaterial.DisableKeyword("_COLLISION");
  1762. if (ShadowShift > 0 && EnableNoise && Sun && _ShadeNoise)
  1763. FogMaterial.EnableKeyword("_SHADE");
  1764. else
  1765. FogMaterial.DisableKeyword("_SHADE");
  1766. //if (EnableNoise && DoubleLayer && SystemInfo.supports3DTextures)
  1767. // FogMaterial.EnableKeyword("_DOUBLE_LAYER");
  1768. //else
  1769. // FogMaterial.DisableKeyword("_DOUBLE_LAYER");
  1770. if (Tonemap)
  1771. FogMaterial.EnableKeyword("_TONEMAP");
  1772. else
  1773. FogMaterial.DisableKeyword("_TONEMAP");
  1774. if (bSphericalFade)
  1775. FogMaterial.EnableKeyword("SPHERICAL_FADE");
  1776. else
  1777. FogMaterial.DisableKeyword("SPHERICAL_FADE");
  1778. if (/*m_primitiveManager != null && m_primitiveManager.VisiblePrimitiveCount > 0 &&*/ EnableDistanceFields)
  1779. FogMaterial.EnableKeyword("DF");
  1780. else
  1781. FogMaterial.DisableKeyword("DF");
  1782. if (bAbsorption)
  1783. FogMaterial.EnableKeyword("ABSORPTION");
  1784. else
  1785. FogMaterial.DisableKeyword("ABSORPTION");
  1786. if (_DirectionalLighting && EnableNoise && _NoiseVolume != null && _DirectionalLightingDistance > 0 && DirectLightingShadowDensity > 0)
  1787. FogMaterial.EnableKeyword("DIRECTIONAL_LIGHTING");
  1788. else
  1789. FogMaterial.DisableKeyword("DIRECTIONAL_LIGHTING");
  1790. }
  1791. Profiler.EndSample();
  1792. }
  1793. }
  1794. public void UpdateBoxMesh()
  1795. {
  1796. if (currentFogVolume != fogVolumeScale || filter == null)
  1797. {
  1798. CreateBoxMesh(fogVolumeScale);
  1799. //update shadow camera too
  1800. ShadowMapSetup();
  1801. //update collider bounds
  1802. _BoxCollider.size = fogVolumeScale;
  1803. m_hasUpdatedBoxMesh = true;
  1804. }
  1805. transform.localScale = Vector3.one;//otherwise, it won't work correctly
  1806. }
  1807. public bool HasUpdatedBoxMesh
  1808. {
  1809. get
  1810. {
  1811. bool ret = m_hasUpdatedBoxMesh;
  1812. m_hasUpdatedBoxMesh = false;
  1813. return ret;
  1814. }
  1815. }
  1816. private bool m_hasUpdatedBoxMesh = false;
  1817. void CreateBoxMesh(Vector3 scale)
  1818. {
  1819. currentFogVolume = scale;
  1820. // You can change that line to provide another MeshFilter
  1821. if (filter == null)
  1822. filter = gameObject.AddComponent<MeshFilter>();
  1823. if (mesh == null)
  1824. {
  1825. mesh = new Mesh();
  1826. mesh.name = gameObject.name;
  1827. filter.sharedMesh = mesh;
  1828. }
  1829. mesh.Clear();
  1830. float width = scale.y;
  1831. float height = scale.z;
  1832. float length = scale.x;
  1833. #region Vertices
  1834. Vector3 p0 = new Vector3(-length * .5f, -width * .5f, height * .5f);
  1835. Vector3 p1 = new Vector3(length * .5f, -width * .5f, height * .5f);
  1836. Vector3 p2 = new Vector3(length * .5f, -width * .5f, -height * .5f);
  1837. Vector3 p3 = new Vector3(-length * .5f, -width * .5f, -height * .5f);
  1838. Vector3 p4 = new Vector3(-length * .5f, width * .5f, height * .5f);
  1839. Vector3 p5 = new Vector3(length * .5f, width * .5f, height * .5f);
  1840. Vector3 p6 = new Vector3(length * .5f, width * .5f, -height * .5f);
  1841. Vector3 p7 = new Vector3(-length * .5f, width * .5f, -height * .5f);
  1842. Vector3[] vertices = new Vector3[]
  1843. {
  1844. // Bottom
  1845. p0, p1, p2, p3,
  1846. // Left
  1847. p7, p4, p0, p3,
  1848. // Front
  1849. p4, p5, p1, p0,
  1850. // Back
  1851. p6, p7, p3, p2,
  1852. // Right
  1853. p5, p6, p2, p1,
  1854. // Top
  1855. p7, p6, p5, p4
  1856. };
  1857. #endregion
  1858. #region Normales
  1859. Vector3 up = Vector3.up;
  1860. Vector3 down = Vector3.down;
  1861. Vector3 front = Vector3.forward;
  1862. Vector3 back = Vector3.back;
  1863. Vector3 left = Vector3.left;
  1864. Vector3 right = Vector3.right;
  1865. Vector3[] normales = new Vector3[]
  1866. {
  1867. // Bottom
  1868. down, down, down, down,
  1869. // Left
  1870. left, left, left, left,
  1871. // Front
  1872. front, front, front, front,
  1873. // Back
  1874. back, back, back, back,
  1875. // Right
  1876. right, right, right, right,
  1877. // Top
  1878. up, up, up, up
  1879. };
  1880. #endregion
  1881. #region UVs
  1882. Vector2 _00 = new Vector2(0f, 0f);
  1883. Vector2 _10 = new Vector2(1f, 0f);
  1884. Vector2 _01 = new Vector2(0f, 1f);
  1885. Vector2 _11 = new Vector2(1f, 1f);
  1886. Vector2[] uvs = new Vector2[]
  1887. {
  1888. // Bottom
  1889. _11, _01, _00, _10,
  1890. // Left
  1891. _11, _01, _00, _10,
  1892. // Front
  1893. _11, _01, _00, _10,
  1894. // Back
  1895. _11, _01, _00, _10,
  1896. // Right
  1897. _11, _01, _00, _10,
  1898. // Top
  1899. _11, _01, _00, _10,
  1900. };
  1901. #endregion
  1902. #region Triangles
  1903. int[] triangles = new int[]
  1904. {
  1905. // Bottom
  1906. 3, 1, 0,
  1907. 3, 2, 1,
  1908. // Left
  1909. 3 + 4 * 1, 1 + 4 * 1, 0 + 4 * 1,
  1910. 3 + 4 * 1, 2 + 4 * 1, 1 + 4 * 1,
  1911. // Front
  1912. 3 + 4 * 2, 1 + 4 * 2, 0 + 4 * 2,
  1913. 3 + 4 * 2, 2 + 4 * 2, 1 + 4 * 2,
  1914. // Back
  1915. 3 + 4 * 3, 1 + 4 * 3, 0 + 4 * 3,
  1916. 3 + 4 * 3, 2 + 4 * 3, 1 + 4 * 3,
  1917. // Right
  1918. 3 + 4 * 4, 1 + 4 * 4, 0 + 4 * 4,
  1919. 3 + 4 * 4, 2 + 4 * 4, 1 + 4 * 4,
  1920. // Top
  1921. 3 + 4 * 5, 1 + 4 * 5, 0 + 4 * 5,
  1922. 3 + 4 * 5, 2 + 4 * 5, 1 + 4 * 5,
  1923. };
  1924. #endregion
  1925. mesh.vertices = vertices;
  1926. mesh.triangles = triangles;
  1927. mesh.normals = normales;
  1928. mesh.uv = uvs;
  1929. mesh.RecalculateBounds();
  1930. ;
  1931. }
  1932. //won't work if the icon is not in Assets/Gizmos
  1933. //void OnDrawGizmosSelected()
  1934. //{
  1935. // Gizmos.DrawIcon(transform.position, "FogVolume/Gizmos/FogVolumeIcon.png", true);
  1936. //}
  1937. private FogVolumeLightManager m_lightManager = null;
  1938. private void _InitializeLightManagerIfNeccessary()
  1939. {
  1940. if (m_lightManager == null)
  1941. {
  1942. m_lightManager = GetComponent<FogVolumeLightManager>();
  1943. if (m_lightManager == null)
  1944. {
  1945. m_lightManager = gameObject.AddComponent<FogVolumeLightManager>();
  1946. }
  1947. m_lightManager.Initialize();
  1948. if (PointLightBoxCheck)
  1949. {
  1950. m_lightManager.FindLightsInFogVolume();
  1951. }
  1952. else
  1953. {
  1954. m_lightManager.FindLightsInScene();
  1955. }
  1956. }
  1957. }
  1958. private void _DeinitializeLightManagerIfNeccessary()
  1959. {
  1960. if (m_lightManager != null)
  1961. {
  1962. m_lightManager.Deinitialize();
  1963. }
  1964. }
  1965. public int GetVisibleLightCount()
  1966. {
  1967. if (m_lightManager != null) { return m_lightManager.VisibleLightCount; }
  1968. return 0;
  1969. }
  1970. public int GetTotalLightCount()
  1971. {
  1972. if (m_lightManager != null) { return m_lightManager.CurrentLightCount; }
  1973. return 0;
  1974. }
  1975. private FogVolumePrimitiveManager m_primitiveManager;
  1976. private void _InitializePrimitiveManagerIfNeccessary()
  1977. {
  1978. if (m_primitiveManager == null)
  1979. {
  1980. m_primitiveManager = GetComponent<FogVolumePrimitiveManager>();
  1981. if (m_primitiveManager == null)
  1982. {
  1983. m_primitiveManager = gameObject.AddComponent<FogVolumePrimitiveManager>();
  1984. }
  1985. m_primitiveManager.Initialize();
  1986. m_primitiveManager.FindPrimitivesInFogVolume();
  1987. }
  1988. }
  1989. private void _DeinitializePrimitiveManagerIfNeccessary()
  1990. {
  1991. if (m_primitiveManager != null) { m_primitiveManager.Deinitialize(); }
  1992. }
  1993. public int GetVisiblePrimitiveCount()
  1994. {
  1995. if (m_primitiveManager != null) { return m_primitiveManager.VisiblePrimitiveCount; }
  1996. return 0;
  1997. }
  1998. public int GetTotalPrimitiveCount()
  1999. {
  2000. if (m_primitiveManager != null) { return m_primitiveManager.CurrentPrimitiveCount; }
  2001. return 0;
  2002. }
  2003. }