VolumetricFog.FoW.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. //------------------------------------------------------------------------------------------------------------------
  2. // Volumetric Fog & Mist 2
  3. // Created by Kronnect
  4. //------------------------------------------------------------------------------------------------------------------
  5. using UnityEngine;
  6. using System.Collections.Generic;
  7. namespace VolumetricFogAndMist2 {
  8. public enum MASK_TEXTURE_BRUSH_MODE {
  9. AddFog = 0,
  10. RemoveFog = 1,
  11. ColorFog = 2
  12. }
  13. public partial class VolumetricFog : MonoBehaviour {
  14. public bool enableFogOfWar;
  15. public Vector3 fogOfWarCenter;
  16. public bool fogOfWarIsLocal;
  17. public Vector3 fogOfWarSize = new Vector3(1024, 0, 1024);
  18. public bool fogOfWarShowCoverage;
  19. [Range(32, 2048)] public int fogOfWarTextureSize = 256;
  20. [Tooltip("Delay before the fog alpha is restored. A value of 0 keeps the fog cleared forever.")]
  21. [Range(0, 100)] public float fogOfWarRestoreDelay;
  22. [Range(0, 25)] public float fogOfWarRestoreDuration = 2f;
  23. [Range(0, 1)] public float fogOfWarSmoothness = 1f;
  24. public bool fogOfWarBlur;
  25. const int MAX_SIMULTANEOUS_TRANSITIONS = 10000;
  26. bool canDestroyFOWTexture;
  27. #region In-Editor fog of war painter
  28. public bool maskEditorEnabled;
  29. public MASK_TEXTURE_BRUSH_MODE maskBrushMode = MASK_TEXTURE_BRUSH_MODE.RemoveFog;
  30. public Color maskBrushColor = Color.white;
  31. [Range(1, 128)] public int maskBrushWidth = 20;
  32. [Range(0, 1)] public float maskBrushFuzziness = 0.5f;
  33. [Range(0, 1)] public float maskBrushOpacity = 0.15f;
  34. #endregion
  35. [SerializeField]
  36. Texture2D _fogOfWarTexture;
  37. public Vector3 anchoredFogOfWarCenter => fogOfWarIsLocal ? transform.position + fogOfWarCenter : fogOfWarCenter;
  38. public Texture2D fogOfWarTexture {
  39. get { return _fogOfWarTexture; }
  40. set {
  41. if (_fogOfWarTexture != value) {
  42. if (value != null) {
  43. if (value.width != value.height) {
  44. Debug.LogError("Fog of war texture must be square.");
  45. } else {
  46. _fogOfWarTexture = value;
  47. canDestroyFOWTexture = false;
  48. ReloadFogOfWarTexture();
  49. }
  50. } else {
  51. if (canDestroyFOWTexture && _fogOfWarTexture != null) {
  52. DestroyImmediate(_fogOfWarTexture);
  53. }
  54. _fogOfWarTexture = null;
  55. canDestroyFOWTexture = false;
  56. }
  57. if (fogMat != null) {
  58. fogMat.SetTexture(ShaderParams.FogOfWarTexture, _fogOfWarTexture);
  59. }
  60. }
  61. }
  62. }
  63. Color32[] fogOfWarColorBuffer;
  64. struct FogOfWarTransition {
  65. public bool enabled;
  66. public int x, y;
  67. public float startTime, startDelay;
  68. public float duration;
  69. public int initialAlpha;
  70. public int targetAlpha;
  71. public int restoreToAlpha;
  72. public float restoreDelay;
  73. public float restoreDuration;
  74. }
  75. FogOfWarTransition[] fowTransitionList;
  76. int lastTransitionPos;
  77. Dictionary<int, int> fowTransitionIndices;
  78. bool requiresTextureUpload;
  79. Material fowBlur;
  80. RenderTexture fowBlur1, fowBlur2;
  81. void FogOfWarInit() {
  82. if (fowTransitionList == null || fowTransitionList.Length != MAX_SIMULTANEOUS_TRANSITIONS) {
  83. fowTransitionList = new FogOfWarTransition[MAX_SIMULTANEOUS_TRANSITIONS];
  84. }
  85. if (fowTransitionIndices == null) {
  86. fowTransitionIndices = new Dictionary<int, int>(MAX_SIMULTANEOUS_TRANSITIONS);
  87. } else {
  88. fowTransitionIndices.Clear();
  89. }
  90. lastTransitionPos = -1;
  91. if (_fogOfWarTexture == null) {
  92. FogOfWarUpdateTexture();
  93. } else if (enableFogOfWar && (fogOfWarColorBuffer == null || fogOfWarColorBuffer.Length == 0)) {
  94. ReloadFogOfWarTexture();
  95. }
  96. }
  97. void FogOfWarDestroy() {
  98. if (canDestroyFOWTexture) {
  99. DestroyImmediate(_fogOfWarTexture);
  100. }
  101. if (fowBlur1 != null) {
  102. fowBlur1.Release();
  103. }
  104. if (fowBlur2 != null) {
  105. fowBlur2.Release();
  106. }
  107. }
  108. /// <summary>
  109. /// Reloads the current contents of the fog of war texture
  110. /// </summary>
  111. public void ReloadFogOfWarTexture() {
  112. if (_fogOfWarTexture == null || profile == null) return;
  113. fogOfWarTextureSize = _fogOfWarTexture.width;
  114. EnsureTextureIsReadable(_fogOfWarTexture);
  115. fogOfWarColorBuffer = _fogOfWarTexture.GetPixels32();
  116. lastTransitionPos = -1;
  117. fowTransitionIndices.Clear();
  118. if (!enableFogOfWar) {
  119. enableFogOfWar = true;
  120. UpdateMaterialPropertiesNow();
  121. }
  122. }
  123. void EnsureTextureIsReadable(Texture2D tex) {
  124. #if UNITY_EDITOR
  125. string path = UnityEditor.AssetDatabase.GetAssetPath(tex);
  126. if (string.IsNullOrEmpty(path))
  127. return;
  128. UnityEditor.TextureImporter imp = UnityEditor.AssetImporter.GetAtPath(path) as UnityEditor.TextureImporter;
  129. if (imp != null && !imp.isReadable) {
  130. imp.isReadable = true;
  131. imp.SaveAndReimport();
  132. }
  133. #endif
  134. }
  135. void FogOfWarUpdateTexture() {
  136. if (!enableFogOfWar || !Application.isPlaying)
  137. return;
  138. int size = GetScaledSize(fogOfWarTextureSize, 1.0f);
  139. if (_fogOfWarTexture == null || _fogOfWarTexture.width != size || _fogOfWarTexture.height != size) {
  140. _fogOfWarTexture = new Texture2D(size, size, TextureFormat.RGBA32, false, true);
  141. _fogOfWarTexture.hideFlags = HideFlags.DontSave;
  142. _fogOfWarTexture.filterMode = FilterMode.Bilinear;
  143. _fogOfWarTexture.wrapMode = TextureWrapMode.Clamp;
  144. canDestroyFOWTexture = true;
  145. ResetFogOfWar();
  146. }
  147. }
  148. int GetScaledSize(int size, float factor) {
  149. size = (int)(size / factor);
  150. size /= 4;
  151. if (size < 1)
  152. size = 1;
  153. return size * 4;
  154. }
  155. /// <summary>
  156. /// Updates fog of war transitions and uploads texture changes to GPU if required
  157. /// </summary>
  158. public void UpdateFogOfWar(bool forceUpload = false) {
  159. if (!enableFogOfWar || _fogOfWarTexture == null)
  160. return;
  161. if (forceUpload) {
  162. requiresTextureUpload = true;
  163. }
  164. int tw = _fogOfWarTexture.width;
  165. float now = Time.time;
  166. for (int k = 0; k <= lastTransitionPos; k++) {
  167. FogOfWarTransition fw = fowTransitionList[k];
  168. if (!fw.enabled)
  169. continue;
  170. float elapsed = now - fw.startTime - fw.startDelay;
  171. if (elapsed > 0) {
  172. float t = fw.duration <= 0 ? 1 : elapsed / fw.duration;
  173. if (t < 0) t = 0; else if (t > 1f) t = 1f;
  174. int alpha = (int)(fw.initialAlpha + (fw.targetAlpha - fw.initialAlpha) * t);
  175. int colorPos = fw.y * tw + fw.x;
  176. fogOfWarColorBuffer[colorPos].a = (byte)alpha;
  177. requiresTextureUpload = true;
  178. if (t >= 1f) {
  179. fowTransitionList[k].enabled = false;
  180. // Add refill slot if needed
  181. if (fw.targetAlpha != fw.restoreToAlpha && fw.restoreDelay > 0) {
  182. AddFogOfWarTransitionSlot(fw.x, fw.y, (byte)fw.targetAlpha, (byte)fw.restoreToAlpha, fw.restoreDelay, fw.restoreDuration, (byte)fw.restoreToAlpha, 0, 0);
  183. }
  184. }
  185. }
  186. }
  187. if (requiresTextureUpload) {
  188. requiresTextureUpload = false;
  189. _fogOfWarTexture.SetPixels32(fogOfWarColorBuffer);
  190. _fogOfWarTexture.Apply();
  191. // Smooth texture
  192. if (fogOfWarBlur) {
  193. SetFowBlurTexture();
  194. }
  195. #if UNITY_EDITOR
  196. if (!Application.isPlaying) {
  197. UnityEditor.EditorUtility.SetDirty(_fogOfWarTexture);
  198. }
  199. #endif
  200. }
  201. if (fogOfWarIsLocal) {
  202. UpdateFogOfWarMaterialBoundsProperties();
  203. }
  204. }
  205. void SetFowBlurTexture() {
  206. if (fowBlur == null) {
  207. fowBlur = new Material(Shader.Find("Hidden/VolumetricFog2/FoWBlur"));
  208. fowBlur.hideFlags = HideFlags.DontSave;
  209. }
  210. if (fowBlur == null)
  211. return;
  212. if (fowBlur1 == null || fowBlur1.width != _fogOfWarTexture.width || fowBlur2 == null || fowBlur2.width != _fogOfWarTexture.width) {
  213. CreateFoWBlurRTs();
  214. }
  215. fowBlur1.DiscardContents();
  216. Graphics.Blit(_fogOfWarTexture, fowBlur1, fowBlur, 0);
  217. fowBlur2.DiscardContents();
  218. Graphics.Blit(fowBlur1, fowBlur2, fowBlur, 1);
  219. fogMat.SetTexture(ShaderParams.FogOfWarTexture, fowBlur2);
  220. }
  221. void CreateFoWBlurRTs() {
  222. if (fowBlur1 != null) {
  223. fowBlur1.Release();
  224. }
  225. if (fowBlur2 != null) {
  226. fowBlur2.Release();
  227. }
  228. RenderTextureDescriptor desc = new RenderTextureDescriptor(_fogOfWarTexture.width, _fogOfWarTexture.height, RenderTextureFormat.ARGB32, 0);
  229. fowBlur1 = new RenderTexture(desc);
  230. fowBlur2 = new RenderTexture(desc);
  231. }
  232. /// <summary>
  233. /// Instantly changes the alpha value of the fog of war at world position. It takes into account FogOfWarCenter and FogOfWarSize.
  234. /// Note that only x and z coordinates are used. Y (vertical) coordinate is ignored.
  235. /// </summary>
  236. /// <param name="worldPosition">in world space coordinates.</param>
  237. /// <param name="radius">radius of application in world units.</param>
  238. /// <param name="fogNewAlpha">target alpha value.</param>
  239. public void SetFogOfWarAlpha(Vector3 worldPosition, float radius, float fogNewAlpha) {
  240. SetFogOfWarAlpha(worldPosition, radius, fogNewAlpha, 1f);
  241. }
  242. /// <summary>
  243. /// Changes the alpha value of the fog of war at world position creating a transition from current alpha value to specified target alpha. It takes into account FogOfWarCenter and FogOfWarSize.
  244. /// Note that only x and z coordinates are used. Y (vertical) coordinate is ignored.
  245. /// </summary>
  246. /// <param name="worldPosition">in world space coordinates.</param>
  247. /// <param name="radius">radius of application in world units.</param>
  248. /// <param name="fogNewAlpha">target alpha value.</param>
  249. /// <param name="duration">duration of transition in seconds (0 = apply fogNewAlpha instantly).</param>
  250. public void SetFogOfWarAlpha(Vector3 worldPosition, float radius, float fogNewAlpha, float duration) {
  251. SetFogOfWarAlpha(worldPosition, radius, fogNewAlpha, true, duration, fogOfWarSmoothness, fogOfWarRestoreDelay, fogOfWarRestoreDuration);
  252. }
  253. /// <summary>
  254. /// Changes the alpha value of the fog of war at world position creating a transition from current alpha value to specified target alpha. It takes into account FogOfWarCenter and FogOfWarSize.
  255. /// Note that only x and z coordinates are used. Y (vertical) coordinate is ignored.
  256. /// </summary>
  257. /// <param name="worldPosition">in world space coordinates.</param>
  258. /// <param name="radius">radius of application in world units.</param>
  259. /// <param name="fogNewAlpha">target alpha value.</param>
  260. /// <param name="duration">duration of transition in seconds (0 = apply fogNewAlpha instantly).</param>
  261. /// <param name="smoothness">border smoothness (0 = sharp borders, 1 = smooth transition)</param>
  262. public void SetFogOfWarAlpha(Vector3 worldPosition, float radius, float fogNewAlpha, float duration, float smoothness) {
  263. SetFogOfWarAlpha(worldPosition, radius, fogNewAlpha, true, duration, smoothness, fogOfWarRestoreDelay, fogOfWarRestoreDuration);
  264. }
  265. /// <summary>
  266. /// Changes the alpha value of the fog of war at world position creating a transition from current alpha value to specified target alpha. It takes into account FogOfWarCenter and FogOfWarSize.
  267. /// Note that only x and z coordinates are used. Y (vertical) coordinate is ignored.
  268. /// </summary>
  269. /// <param name="worldPosition">in world space coordinates.</param>
  270. /// <param name="radius">radius of application in world units.</param>
  271. /// <param name="fogNewAlpha">target alpha value.</param>
  272. /// <param name="blendAlpha">if new alpha is combined with preexisting alpha value or replaced.</param>
  273. /// <param name="duration">duration of transition in seconds (0 = apply fogNewAlpha instantly).</param>
  274. /// <param name="smoothness">border smoothness.</param>
  275. /// <param name="restoreDelay">delay before the fog alpha is restored. Pass 0 to keep change forever.</param>
  276. /// <param name="restoreDuration">restore duration in seconds.</param>
  277. /// <param name="restoreToAlphaValue">final alpha value when fog restores.</param>
  278. public void SetFogOfWarAlpha(Vector3 worldPosition, float radius, float fogNewAlpha, bool blendAlpha, float duration, float smoothness, float restoreDelay, float restoreDuration, float restoreToAlphaValue = 1f) {
  279. if (_fogOfWarTexture == null || fogOfWarColorBuffer == null || fogOfWarColorBuffer.Length == 0)
  280. return;
  281. Vector3 fogOfWarCenter = anchoredFogOfWarCenter;
  282. float tx = (worldPosition.x - fogOfWarCenter.x) / fogOfWarSize.x + 0.5f;
  283. if (tx < 0 || tx > 1f)
  284. return;
  285. float tz = (worldPosition.z - fogOfWarCenter.z) / fogOfWarSize.z + 0.5f;
  286. if (tz < 0 || tz > 1f)
  287. return;
  288. int tw = _fogOfWarTexture.width;
  289. int th = _fogOfWarTexture.height;
  290. int px = (int)(tx * tw);
  291. int pz = (int)(tz * th);
  292. float sm = 0.0001f + smoothness;
  293. byte newAlpha8 = (byte)(fogNewAlpha * 255);
  294. float tr = radius / fogOfWarSize.z;
  295. int delta = (int)(th * tr);
  296. int deltaSqr = delta * delta;
  297. byte restoreAlpha = (byte)(255 * restoreToAlphaValue);
  298. for (int r = pz - delta; r <= pz + delta; r++) {
  299. if (r > 0 && r < th - 1) {
  300. for (int c = px - delta; c <= px + delta; c++) {
  301. if (c > 0 && c < tw - 1) {
  302. int distanceSqr = (pz - r) * (pz - r) + (px - c) * (px - c);
  303. if (distanceSqr <= deltaSqr) {
  304. int colorBufferPos = r * tw + c;
  305. Color32 colorBuffer = fogOfWarColorBuffer[colorBufferPos];
  306. if (!blendAlpha) {
  307. colorBuffer.a = 255;
  308. }
  309. distanceSqr = deltaSqr - distanceSqr;
  310. float t = (float)distanceSqr / (deltaSqr * sm);
  311. t = 1f - t;
  312. if (t < 0) {
  313. t = 0;
  314. } else if (t > 1f) {
  315. t = 1f;
  316. }
  317. byte targetAlpha = (byte)(newAlpha8 + (colorBuffer.a - newAlpha8) * t);
  318. if (targetAlpha < 255 && (colorBuffer.a != targetAlpha || restoreDelay > 0)) {
  319. if (duration > 0) {
  320. AddFogOfWarTransitionSlot(c, r, colorBuffer.a, targetAlpha, 0, duration, restoreAlpha, restoreDelay, restoreDuration);
  321. } else {
  322. colorBuffer.a = targetAlpha;
  323. fogOfWarColorBuffer[colorBufferPos] = colorBuffer;
  324. requiresTextureUpload = true;
  325. if (restoreDelay > 0) {
  326. AddFogOfWarTransitionSlot(c, r, targetAlpha, restoreAlpha, restoreDelay, restoreDuration, targetAlpha, 0, 0);
  327. }
  328. }
  329. }
  330. }
  331. }
  332. }
  333. }
  334. }
  335. }
  336. /// <summary>
  337. /// Changes the alpha value of the fog of war within bounds creating a transition from current alpha value to specified target alpha. It takes into account FogOfWarCenter and FogOfWarSize.
  338. /// Note that only x and z coordinates are used. Y (vertical) coordinate is ignored.
  339. /// </summary>
  340. /// <param name="bounds">in world space coordinates.</param>
  341. /// <param name="fogNewAlpha">target alpha value.</param>
  342. /// <param name="duration">duration of transition in seconds (0 = apply fogNewAlpha instantly).</param>
  343. public void SetFogOfWarAlpha(Bounds bounds, float fogNewAlpha, float duration) {
  344. SetFogOfWarAlpha(bounds, fogNewAlpha, true, duration, fogOfWarSmoothness, fogOfWarRestoreDelay, fogOfWarRestoreDuration);
  345. }
  346. /// <summary>
  347. /// Changes the alpha value of the fog of war within bounds creating a transition from current alpha value to specified target alpha. It takes into account FogOfWarCenter and FogOfWarSize.
  348. /// Note that only x and z coordinates are used. Y (vertical) coordinate is ignored.
  349. /// </summary>
  350. /// <param name="bounds">in world space coordinates.</param>
  351. /// <param name="fogNewAlpha">target alpha value.</param>
  352. /// <param name="duration">duration of transition in seconds (0 = apply fogNewAlpha instantly).</param>
  353. /// <param name="smoothness">border smoothness.</param>
  354. public void SetFogOfWarAlpha(Bounds bounds, float fogNewAlpha, float duration, float smoothness) {
  355. SetFogOfWarAlpha(bounds, fogNewAlpha, true, duration, smoothness, fogOfWarRestoreDelay, fogOfWarRestoreDuration);
  356. }
  357. /// <summary>
  358. /// Changes the alpha value of the fog of war within bounds creating a transition from current alpha value to specified target alpha. It takes into account FogOfWarCenter and FogOfWarSize.
  359. /// Note that only x and z coordinates are used. Y (vertical) coordinate is ignored.
  360. /// </summary>
  361. /// <param name="bounds">in world space coordinates.</param>
  362. /// <param name="fogNewAlpha">target alpha value (0-1).</param>
  363. /// <param name="blendAlpha">if new alpha is combined with preexisting alpha value or replaced.</param>
  364. /// <param name="duration">duration of transition in seconds (0 = apply fogNewAlpha instantly).</param>
  365. /// <param name="smoothness">border smoothness.</param>
  366. /// <param name="fuzzyness">randomization of border noise.</param>
  367. /// <param name="restoreDelay">delay before the fog alpha is restored. Pass 0 to keep change forever.</param>
  368. /// <param name="restoreDuration">restore duration in seconds.</param>
  369. /// <param name="restoreToAlpha">alpha value (0-1) for the fog when restore is completed.</param>
  370. public void SetFogOfWarAlpha(Bounds bounds, float fogNewAlpha, bool blendAlpha, float duration, float smoothness, float restoreDelay, float restoreDuration, float restoreToAlpha = 1f) {
  371. if (_fogOfWarTexture == null || fogOfWarColorBuffer == null || fogOfWarColorBuffer.Length == 0)
  372. return;
  373. Vector3 fogOfWarCenter = anchoredFogOfWarCenter;
  374. Vector3 worldPosition = bounds.center;
  375. float tx = (worldPosition.x - fogOfWarCenter.x) / fogOfWarSize.x + 0.5f;
  376. if (tx < 0 || tx > 1f)
  377. return;
  378. float tz = (worldPosition.z - fogOfWarCenter.z) / fogOfWarSize.z + 0.5f;
  379. if (tz < 0 || tz > 1f)
  380. return;
  381. int tw = _fogOfWarTexture.width;
  382. int th = _fogOfWarTexture.height;
  383. int px = (int)(tx * tw);
  384. int pz = (int)(tz * th);
  385. byte newAlpha8 = (byte)(fogNewAlpha * 255);
  386. float trz = bounds.extents.z / fogOfWarSize.z;
  387. float trx = bounds.extents.x / fogOfWarSize.x;
  388. float aspect1 = trx > trz ? 1f : trz / trx;
  389. float aspect2 = trx > trz ? trx / trz : 1f;
  390. int deltaz = (int)(th * trz);
  391. int deltazSqr = deltaz * deltaz;
  392. int deltax = (int)(tw * trx);
  393. int deltaxSqr = deltax * deltax;
  394. float sm = 0.0001f + smoothness;
  395. byte restoreAlpha = (byte)(restoreToAlpha * 255);
  396. for (int r = pz - deltaz; r <= pz + deltaz; r++) {
  397. if (r > 0 && r < th - 1) {
  398. int distancezSqr = (pz - r) * (pz - r);
  399. distancezSqr = deltazSqr - distancezSqr;
  400. float t1 = (float)distancezSqr * aspect1 / (deltazSqr * sm);
  401. for (int c = px - deltax; c <= px + deltax; c++) {
  402. if (c > 0 && c < tw - 1) {
  403. int distancexSqr = (px - c) * (px - c);
  404. int colorBufferPos = r * tw + c;
  405. Color32 colorBuffer = fogOfWarColorBuffer[colorBufferPos];
  406. if (!blendAlpha) colorBuffer.a = 255;
  407. distancexSqr = deltaxSqr - distancexSqr;
  408. float t2 = (float)distancexSqr * aspect2 / (deltaxSqr * sm);
  409. float t = t1 < t2 ? t1 : t2;
  410. t = 1f - t;
  411. if (t < 0) t = 0; else if (t > 1f) t = 1f;
  412. byte targetAlpha = (byte)(newAlpha8 + (colorBuffer.a - newAlpha8) * t); // Mathf.Lerp(newAlpha8, colorBuffer.a, t);
  413. if (targetAlpha < 255 && (colorBuffer.a != targetAlpha || restoreDelay > 0)) {
  414. if (duration > 0) {
  415. AddFogOfWarTransitionSlot(c, r, colorBuffer.a, targetAlpha, 0, duration, restoreAlpha, restoreDelay, restoreDuration);
  416. } else {
  417. colorBuffer.a = targetAlpha;
  418. fogOfWarColorBuffer[colorBufferPos] = colorBuffer;
  419. requiresTextureUpload = true;
  420. if (restoreDelay > 0) {
  421. AddFogOfWarTransitionSlot(c, r, targetAlpha, restoreAlpha, restoreDelay, restoreDuration, restoreAlpha, 0, 0);
  422. }
  423. }
  424. }
  425. }
  426. }
  427. }
  428. }
  429. }
  430. /// <summary>
  431. /// Changes the alpha value of the fog of war within collider creating a transition from current alpha value to specified target alpha. It takes into account FogOfWarCenter and FogOfWarSize.
  432. /// Note that only x and z coordinates are used. Y (vertical) coordinate is ignored.
  433. /// </summary>
  434. /// <param name="collider">collider used to define the shape of the area where fog of war alpha will be set. Collider must be convex.</param>
  435. /// <param name="fogNewAlpha">target alpha value (0-1).</param>
  436. /// <param name="blendAlpha">if new alpha is combined with preexisting alpha value or replaced.</param>
  437. /// <param name="duration">duration of transition in seconds (0 = apply fogNewAlpha instantly).</param>
  438. /// <param name="smoothness">border smoothness.</param>
  439. /// <param name="fuzzyness">randomization of border noise.</param>
  440. /// <param name="restoreDelay">delay before the fog alpha is restored. Pass 0 to keep change forever.</param>
  441. /// <param name="restoreDuration">restore duration in seconds.</param>
  442. /// <param name="restoreToAlpha">alpha value (0-1) for the fog when restore is completed.</param>
  443. public void SetFogOfWarAlpha(Collider collider, float fogNewAlpha, bool blendAlpha, float duration, float smoothness, float restoreDelay, float restoreDuration, float restoreToAlpha = 1f) {
  444. if (_fogOfWarTexture == null || fogOfWarColorBuffer == null || fogOfWarColorBuffer.Length == 0)
  445. return;
  446. Vector3 fogOfWarCenter = anchoredFogOfWarCenter;
  447. Bounds bounds = collider.bounds;
  448. Vector3 worldPosition = bounds.center;
  449. float tx = (worldPosition.x - fogOfWarCenter.x) / fogOfWarSize.x + 0.5f;
  450. if (tx < 0 || tx > 1f)
  451. return;
  452. float tz = (worldPosition.z - fogOfWarCenter.z) / fogOfWarSize.z + 0.5f;
  453. if (tz < 0 || tz > 1f)
  454. return;
  455. int tw = _fogOfWarTexture.width;
  456. int th = _fogOfWarTexture.height;
  457. int px = (int)(tx * tw);
  458. int pz = (int)(tz * th);
  459. byte newAlpha8 = (byte)(fogNewAlpha * 255);
  460. float trz = bounds.extents.z / fogOfWarSize.z;
  461. float trx = bounds.extents.x / fogOfWarSize.x;
  462. float aspect1 = trx > trz ? 1f : trz / trx;
  463. float aspect2 = trx > trz ? trx / trz : 1f;
  464. int deltaz = (int)(th * trz);
  465. int deltazSqr = deltaz * deltaz;
  466. int deltax = (int)(tw * trx);
  467. int deltaxSqr = deltax * deltax;
  468. float sm = 0.0001f + smoothness;
  469. byte restoreAlpha = (byte)(restoreToAlpha * 255);
  470. Vector3 wpos = bounds.min;
  471. for (int rr = 0; rr <= deltaz * 2; rr++) {
  472. int r = pz - deltaz + rr;
  473. if (r > 0 && r < th - 1) {
  474. int distancezSqr = (pz - r) * (pz - r);
  475. distancezSqr = deltazSqr - distancezSqr;
  476. float t1 = (float)distancezSqr * aspect1 / (deltazSqr * sm);
  477. wpos.z = bounds.min.z + bounds.size.z * rr / (deltaz * 2f);
  478. for (int cc = 0; cc <= deltax * 2; cc++) {
  479. int c = px - deltax + cc;
  480. if (c > 0 && c < tw - 1) {
  481. wpos.x = bounds.min.x + bounds.size.x * cc / (deltax * 2f);
  482. if (collider.ClosestPoint(wpos) != wpos) continue; // point is outside collider
  483. int distancexSqr = (px - c) * (px - c);
  484. int colorBufferPos = r * tw + c;
  485. Color32 colorBuffer = fogOfWarColorBuffer[colorBufferPos];
  486. if (!blendAlpha) colorBuffer.a = 255;
  487. distancexSqr = deltaxSqr - distancexSqr;
  488. float t2 = (float)distancexSqr * aspect2 / (deltaxSqr * sm);
  489. float t = t1 < t2 ? t1 : t2;
  490. t = 1f - t;
  491. if (t < 0) t = 0; else if (t > 1f) t = 1f;
  492. byte targetAlpha = (byte)(newAlpha8 + (colorBuffer.a - newAlpha8) * t); // Mathf.Lerp(newAlpha8, colorBuffer.a, t);
  493. if (targetAlpha < 255 && (colorBuffer.a != targetAlpha || restoreDelay > 0)) {
  494. if (duration > 0) {
  495. AddFogOfWarTransitionSlot(c, r, colorBuffer.a, targetAlpha, 0, duration, restoreAlpha, restoreDelay, restoreDuration);
  496. } else {
  497. colorBuffer.a = targetAlpha;
  498. fogOfWarColorBuffer[colorBufferPos] = colorBuffer;
  499. requiresTextureUpload = true;
  500. if (restoreDelay > 0) {
  501. AddFogOfWarTransitionSlot(c, r, targetAlpha, restoreAlpha, restoreDelay, restoreDuration, restoreAlpha, 0, 0);
  502. }
  503. }
  504. }
  505. }
  506. }
  507. }
  508. }
  509. }
  510. /// <summary>
  511. /// Restores fog of war to full opacity
  512. /// </summary>
  513. /// <param name="worldPosition">World position.</param>
  514. /// <param name="radius">Radius.</param>
  515. /// <param name="alpha">Alpha value (1f = fully opaque)</param>
  516. public void ResetFogOfWarAlpha(Vector3 worldPosition, float radius, float alpha = 1f) {
  517. if (_fogOfWarTexture == null || fogOfWarColorBuffer == null || fogOfWarColorBuffer.Length == 0)
  518. return;
  519. Vector3 fogOfWarCenter = anchoredFogOfWarCenter;
  520. float tx = (worldPosition.x - fogOfWarCenter.x) / fogOfWarSize.x + 0.5f;
  521. if (tx < 0 || tx > 1f)
  522. return;
  523. float tz = (worldPosition.z - fogOfWarCenter.z) / fogOfWarSize.z + 0.5f;
  524. if (tz < 0 || tz > 1f)
  525. return;
  526. int tw = _fogOfWarTexture.width;
  527. int th = _fogOfWarTexture.height;
  528. int px = (int)(tx * tw);
  529. int pz = (int)(tz * th);
  530. float tr = radius / fogOfWarSize.z;
  531. int delta = (int)(th * tr);
  532. int deltaSqr = delta * delta;
  533. byte fogAlpha = (byte)(alpha * 255);
  534. for (int r = pz - delta; r <= pz + delta; r++) {
  535. if (r > 0 && r < th - 1) {
  536. for (int c = px - delta; c <= px + delta; c++) {
  537. if (c > 0 && c < tw - 1) {
  538. int distanceSqr = (pz - r) * (pz - r) + (px - c) * (px - c);
  539. if (distanceSqr <= deltaSqr) {
  540. int colorBufferPos = r * tw + c;
  541. Color32 colorBuffer = fogOfWarColorBuffer[colorBufferPos];
  542. colorBuffer.a = fogAlpha;
  543. fogOfWarColorBuffer[colorBufferPos] = colorBuffer;
  544. requiresTextureUpload = true;
  545. }
  546. }
  547. }
  548. }
  549. }
  550. }
  551. /// <summary>
  552. /// Restores fog of war to full opacity
  553. /// </summary>
  554. public void ResetFogOfWarAlpha(Bounds bounds, float alpha = 1f) {
  555. ResetFogOfWarAlpha(bounds.center, bounds.extents.x, bounds.extents.z, alpha);
  556. }
  557. /// <summary>
  558. /// Restores fog of war to full opacity
  559. /// </summary>
  560. public void ResetFogOfWarAlpha(Vector3 position, Vector3 size, float alpha = 1f) {
  561. ResetFogOfWarAlpha(position, size.x * 0.5f, size.z * 0.5f, alpha);
  562. }
  563. /// <summary>
  564. /// Restores fog of war to full opacity
  565. /// </summary>
  566. /// <param name="position">Position in world space.</param>
  567. /// <param name="extentsX">Half of the length of the rectangle in X-Axis.</param>
  568. /// <param name="extentsZ">Half of the length of the rectangle in Z-Axis.</param>
  569. /// <param name="alpha">Alpha value (1f = fully opaque)</param>
  570. public void ResetFogOfWarAlpha(Vector3 position, float extentsX, float extentsZ, float alpha = 1f) {
  571. if (_fogOfWarTexture == null || fogOfWarColorBuffer == null || fogOfWarColorBuffer.Length == 0)
  572. return;
  573. Vector3 fogOfWarCenter = anchoredFogOfWarCenter;
  574. float tx = (position.x - fogOfWarCenter.x) / fogOfWarSize.x + 0.5f;
  575. if (tx < 0 || tx > 1f)
  576. return;
  577. float tz = (position.z - fogOfWarCenter.z) / fogOfWarSize.z + 0.5f;
  578. if (tz < 0 || tz > 1f)
  579. return;
  580. int tw = _fogOfWarTexture.width;
  581. int th = _fogOfWarTexture.height;
  582. int px = (int)(tx * tw);
  583. int pz = (int)(tz * th);
  584. float trz = extentsZ / fogOfWarSize.z;
  585. float trx = extentsX / fogOfWarSize.x;
  586. int deltaz = (int)(th * trz);
  587. int deltax = (int)(tw * trx);
  588. byte fogAlpha = (byte)(alpha * 255);
  589. for (int r = pz - deltaz; r <= pz + deltaz; r++) {
  590. if (r > 0 && r < th - 1) {
  591. for (int c = px - deltax; c <= px + deltax; c++) {
  592. if (c > 0 && c < tw - 1) {
  593. int colorBufferPos = r * tw + c;
  594. Color32 colorBuffer = fogOfWarColorBuffer[colorBufferPos];
  595. colorBuffer.a = fogAlpha;
  596. fogOfWarColorBuffer[colorBufferPos] = colorBuffer;
  597. requiresTextureUpload = true;
  598. }
  599. }
  600. }
  601. }
  602. }
  603. public void ResetFogOfWar(float alpha = 1f) {
  604. if (_fogOfWarTexture == null)
  605. return;
  606. int h = _fogOfWarTexture.height;
  607. int w = _fogOfWarTexture.width;
  608. int newLength = h * w;
  609. if (fogOfWarColorBuffer == null || fogOfWarColorBuffer.Length != newLength) {
  610. fogOfWarColorBuffer = new Color32[newLength];
  611. }
  612. Color32 opaque = new Color32(255, 255, 255, (byte)(alpha * 255));
  613. for (int k = 0; k < newLength; k++) {
  614. fogOfWarColorBuffer[k] = opaque;
  615. }
  616. _fogOfWarTexture.SetPixels32(fogOfWarColorBuffer);
  617. _fogOfWarTexture.Apply();
  618. lastTransitionPos = -1;
  619. fowTransitionIndices.Clear();
  620. }
  621. /// <summary>
  622. /// Gets or set fog of war state as a Color32 buffer. The alpha channel stores the transparency of the fog at that position (0 = no fog, 1 = opaque).
  623. /// </summary>
  624. public Color32[] fogOfWarTextureData {
  625. get {
  626. return fogOfWarColorBuffer;
  627. }
  628. set {
  629. enableFogOfWar = true;
  630. fogOfWarColorBuffer = value;
  631. if (value == null || _fogOfWarTexture == null)
  632. return;
  633. if (value.Length != _fogOfWarTexture.width * _fogOfWarTexture.height)
  634. return;
  635. _fogOfWarTexture.SetPixels32(fogOfWarColorBuffer);
  636. _fogOfWarTexture.Apply();
  637. }
  638. }
  639. void AddFogOfWarTransitionSlot(int x, int y, byte initialAlpha, byte targetAlpha, float delay, float duration, byte restoreToAlpha, float restoreDelay, float restoreDuration) {
  640. // Check if this slot exists
  641. int index;
  642. int key = y * 64000 + x;
  643. if (!fowTransitionIndices.TryGetValue(key, out index)) {
  644. index = -1;
  645. for (int k = 0; k <= lastTransitionPos; k++) {
  646. if (!fowTransitionList[k].enabled) {
  647. index = k;
  648. fowTransitionIndices[key] = index;
  649. break;
  650. }
  651. }
  652. }
  653. if (index >= 0) {
  654. if (fowTransitionList[index].enabled) {
  655. if (fowTransitionList[index].x != x || fowTransitionList[index].y != y) {
  656. index = -1;
  657. } else {
  658. if (fowTransitionList[index].targetAlpha == targetAlpha && fowTransitionList[index].restoreToAlpha == restoreToAlpha && fowTransitionList[index].restoreDelay == restoreDelay && fowTransitionList[index].restoreDuration == restoreDuration) {
  659. // transition running already to target alpha
  660. return;
  661. }
  662. }
  663. }
  664. }
  665. if (index < 0) {
  666. if (lastTransitionPos >= MAX_SIMULTANEOUS_TRANSITIONS - 1)
  667. return;
  668. index = ++lastTransitionPos;
  669. fowTransitionIndices[key] = index;
  670. }
  671. fowTransitionList[index].x = x;
  672. fowTransitionList[index].y = y;
  673. fowTransitionList[index].duration = duration;
  674. fowTransitionList[index].startTime = Time.time;
  675. fowTransitionList[index].startDelay = delay;
  676. fowTransitionList[index].initialAlpha = initialAlpha;
  677. fowTransitionList[index].targetAlpha = targetAlpha;
  678. fowTransitionList[index].restoreToAlpha = restoreToAlpha;
  679. fowTransitionList[index].restoreDelay = restoreDelay;
  680. fowTransitionList[index].restoreDuration = restoreDuration;
  681. fowTransitionList[index].enabled = true;
  682. }
  683. /// <summary>
  684. /// Gets the current alpha value of the Fog of War at a given world position
  685. /// </summary>
  686. /// <returns>The fog of war alpha.</returns>
  687. /// <param name="worldPosition">World position.</param>
  688. public float GetFogOfWarAlpha(Vector3 worldPosition) {
  689. if (fogOfWarColorBuffer == null || fogOfWarColorBuffer.Length == 0 || _fogOfWarTexture == null)
  690. return 1f;
  691. float tx = (worldPosition.x - fogOfWarCenter.x) / fogOfWarSize.x + 0.5f;
  692. if (tx < 0 || tx > 1f)
  693. return 1f;
  694. float tz = (worldPosition.z - fogOfWarCenter.z) / fogOfWarSize.z + 0.5f;
  695. if (tz < 0 || tz > 1f)
  696. return 1f;
  697. int tw = _fogOfWarTexture.width;
  698. int th = _fogOfWarTexture.height;
  699. int px = (int)(tx * tw);
  700. int pz = (int)(tz * th);
  701. int colorBufferPos = pz * tw + px;
  702. if (colorBufferPos < 0 || colorBufferPos >= fogOfWarColorBuffer.Length)
  703. return 1f;
  704. return fogOfWarColorBuffer[colorBufferPos].a / 255f;
  705. }
  706. }
  707. }