PreviewManager.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using UnityEngine;
  7. using UnityEditor.Graphing;
  8. using UnityEditor.Graphing.Util;
  9. using UnityEngine.Assertions;
  10. using UnityEngine.Rendering;
  11. using Debug = UnityEngine.Debug;
  12. using Object = UnityEngine.Object;
  13. namespace UnityEditor.ShaderGraph.Drawing
  14. {
  15. delegate void OnPrimaryMasterChanged();
  16. class PreviewManager : IDisposable
  17. {
  18. GraphData m_Graph;
  19. MessageManager m_Messenger;
  20. List<PreviewRenderData> m_RenderDatas = new List<PreviewRenderData>();
  21. PreviewRenderData m_MasterRenderData;
  22. List<Identifier> m_Identifiers = new List<Identifier>();
  23. HashSet<AbstractMaterialNode> m_NodesToUpdate = new HashSet<AbstractMaterialNode>();
  24. HashSet<AbstractMaterialNode> m_NodesToDraw = new HashSet<AbstractMaterialNode>();
  25. HashSet<AbstractMaterialNode> m_TimedNodes = new HashSet<AbstractMaterialNode>();
  26. bool m_RefreshTimedNodes;
  27. PreviewSceneResources m_SceneResources;
  28. Texture2D m_ErrorTexture;
  29. Vector2? m_NewMasterPreviewSize;
  30. public PreviewRenderData masterRenderData
  31. {
  32. get { return m_MasterRenderData; }
  33. }
  34. public PreviewManager(GraphData graph, MessageManager messenger)
  35. {
  36. m_Graph = graph;
  37. m_Messenger = messenger;
  38. m_ErrorTexture = GenerateFourSquare(Color.magenta, Color.black);
  39. m_SceneResources = new PreviewSceneResources();
  40. foreach (var node in m_Graph.GetNodes<AbstractMaterialNode>())
  41. AddPreview(node);
  42. }
  43. public OnPrimaryMasterChanged onPrimaryMasterChanged;
  44. static Texture2D GenerateFourSquare(Color c1, Color c2)
  45. {
  46. var tex = new Texture2D(2, 2);
  47. tex.SetPixel(0, 0, c1);
  48. tex.SetPixel(0, 1, c2);
  49. tex.SetPixel(1, 0, c2);
  50. tex.SetPixel(1, 1, c1);
  51. tex.filterMode = FilterMode.Point;
  52. tex.Apply();
  53. return tex;
  54. }
  55. public void ResizeMasterPreview(Vector2 newSize)
  56. {
  57. m_NewMasterPreviewSize = newSize;
  58. }
  59. public PreviewRenderData GetPreview(AbstractMaterialNode node)
  60. {
  61. return m_RenderDatas[node.tempId.index];
  62. }
  63. void AddPreview(AbstractMaterialNode node)
  64. {
  65. var isMaster = false;
  66. if (node is IMasterNode || node is SubGraphOutputNode)
  67. {
  68. if (masterRenderData != null || (node is IMasterNode && node.guid != node.owner.activeOutputNodeGuid))
  69. {
  70. return;
  71. }
  72. isMaster = true;
  73. }
  74. var renderData = new PreviewRenderData
  75. {
  76. renderTexture =
  77. new RenderTexture(200, 200, 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default)
  78. {
  79. hideFlags = HideFlags.HideAndDontSave
  80. }
  81. };
  82. if (isMaster)
  83. {
  84. m_MasterRenderData = renderData;
  85. renderData.renderTexture.width = renderData.renderTexture.height = 400;
  86. }
  87. renderData.renderTexture.Create();
  88. var shaderData = new PreviewShaderData
  89. {
  90. node = node,
  91. isCompiling = false,
  92. hasError = false,
  93. shader = ShaderUtil.CreateShaderAsset(k_EmptyShader, false)
  94. };
  95. shaderData.shader.hideFlags = HideFlags.HideAndDontSave;
  96. shaderData.mat = new Material(shaderData.shader) {hideFlags = HideFlags.HideAndDontSave};
  97. renderData.shaderData = shaderData;
  98. Set(m_Identifiers, node.tempId, node.tempId);
  99. Set(m_RenderDatas, node.tempId, renderData);
  100. node.RegisterCallback(OnNodeModified);
  101. if (node.RequiresTime())
  102. {
  103. m_RefreshTimedNodes = true;
  104. }
  105. if (m_MasterRenderData == renderData && onPrimaryMasterChanged != null)
  106. {
  107. onPrimaryMasterChanged();
  108. }
  109. m_NodesToUpdate.Add(node);
  110. }
  111. void OnNodeModified(AbstractMaterialNode node, ModificationScope scope)
  112. {
  113. if (scope == ModificationScope.Topological ||
  114. scope == ModificationScope.Graph)
  115. {
  116. m_NodesToUpdate.Add(node);
  117. m_RefreshTimedNodes = true;
  118. }
  119. else if (scope == ModificationScope.Node)
  120. {
  121. m_NodesToDraw.Add(node);
  122. }
  123. }
  124. Stack<AbstractMaterialNode> m_NodeWave = new Stack<AbstractMaterialNode>();
  125. List<IEdge> m_Edges = new List<IEdge>();
  126. List<MaterialSlot> m_Slots = new List<MaterialSlot>();
  127. List<AbstractMaterialNode> m_NextLevelNodes = new List<AbstractMaterialNode>();
  128. enum PropagationDirection
  129. {
  130. Upstream,
  131. Downstream
  132. }
  133. void PropagateNodeList<T>(T nodes, PropagationDirection dir) where T : ICollection<AbstractMaterialNode>
  134. {
  135. m_NodeWave.Clear();
  136. foreach (var node in nodes)
  137. m_NodeWave.Push(node);
  138. while (m_NodeWave.Count > 0)
  139. {
  140. var node = m_NodeWave.Pop();
  141. if (node == null)
  142. continue;
  143. m_NextLevelNodes.Clear();
  144. GetConnectedNodes(node, dir, m_NextLevelNodes);
  145. foreach (var nextNode in m_NextLevelNodes)
  146. {
  147. nodes.Add(nextNode);
  148. m_NodeWave.Push(nextNode);
  149. }
  150. }
  151. }
  152. void GetConnectedNodes<T>(AbstractMaterialNode node, PropagationDirection dir, T connections) where T : ICollection<AbstractMaterialNode>
  153. {
  154. // Loop through all nodes that the node feeds into.
  155. m_Slots.Clear();
  156. if (dir == PropagationDirection.Downstream)
  157. node.GetOutputSlots(m_Slots);
  158. else
  159. node.GetInputSlots(m_Slots);
  160. foreach (var slot in m_Slots)
  161. {
  162. m_Edges.Clear();
  163. m_Graph.GetEdges(slot.slotReference, m_Edges);
  164. foreach (var edge in m_Edges)
  165. {
  166. // We look at each node we feed into.
  167. var connectedSlot = (dir == PropagationDirection.Downstream) ? edge.inputSlot : edge.outputSlot;
  168. var connectedNodeGuid = connectedSlot.nodeGuid;
  169. var connectedNode = m_Graph.GetNodeFromGuid(connectedNodeGuid);
  170. // If the input node is already in the set, we don't need to process it.
  171. if (connections.Contains(connectedNode))
  172. continue;
  173. // Add the node to the set, and to the wavefront such that we can process the nodes that it feeds into.
  174. connections.Add(connectedNode);
  175. }
  176. }
  177. }
  178. public bool HandleGraphChanges()
  179. {
  180. if (m_Graph.didActiveOutputNodeChange)
  181. {
  182. DestroyPreview(masterRenderData.shaderData.node.tempId);
  183. }
  184. foreach (var node in m_Graph.removedNodes)
  185. {
  186. DestroyPreview(node.tempId);
  187. m_NodesToUpdate.Remove(node);
  188. m_NodesToDraw.Remove(node);
  189. m_RefreshTimedNodes = true;
  190. }
  191. m_Messenger.ClearNodesFromProvider(this, m_Graph.removedNodes);
  192. foreach (var node in m_Graph.addedNodes)
  193. {
  194. AddPreview(node);
  195. m_RefreshTimedNodes = true;
  196. }
  197. foreach (var edge in m_Graph.removedEdges)
  198. {
  199. var node = m_Graph.GetNodeFromGuid(edge.inputSlot.nodeGuid);
  200. if (node != null)
  201. {
  202. m_NodesToUpdate.Add(node);
  203. m_RefreshTimedNodes = true;
  204. }
  205. }
  206. foreach (var edge in m_Graph.addedEdges)
  207. {
  208. var node = m_Graph.GetNodeFromGuid(edge.inputSlot.nodeGuid);
  209. if(node != null)
  210. {
  211. m_NodesToUpdate.Add(node);
  212. m_RefreshTimedNodes = true;
  213. }
  214. }
  215. return m_NodesToUpdate.Count > 0;
  216. }
  217. List<PreviewProperty> m_PreviewProperties = new List<PreviewProperty>();
  218. List<AbstractMaterialNode> m_PropertyNodes = new List<AbstractMaterialNode>();
  219. void CollectShaderProperties(AbstractMaterialNode node, PreviewRenderData renderData)
  220. {
  221. m_PreviewProperties.Clear();
  222. m_PropertyNodes.Clear();
  223. m_PropertyNodes.Add(node);
  224. PropagateNodeList(m_PropertyNodes, PropagationDirection.Upstream);
  225. foreach (var propNode in m_PropertyNodes)
  226. {
  227. propNode.CollectPreviewMaterialProperties(m_PreviewProperties);
  228. }
  229. foreach (var prop in m_Graph.properties)
  230. m_PreviewProperties.Add(prop.GetPreviewMaterialProperty());
  231. foreach (var previewProperty in m_PreviewProperties)
  232. renderData.shaderData.mat.SetPreviewProperty(previewProperty);
  233. }
  234. List<PreviewRenderData> m_RenderList2D = new List<PreviewRenderData>();
  235. List<PreviewRenderData> m_RenderList3D = new List<PreviewRenderData>();
  236. public void RenderPreviews()
  237. {
  238. UpdateShaders();
  239. UpdateTimedNodeList();
  240. PropagateNodeList(m_NodesToDraw, PropagationDirection.Downstream);
  241. m_NodesToDraw.UnionWith(m_TimedNodes);
  242. var time = Time.realtimeSinceStartup;
  243. var timeParameters = new Vector4(time, Mathf.Sin(time), Mathf.Cos(time), 0.0f);
  244. foreach (var node in m_NodesToDraw)
  245. {
  246. if(node == null || !node.hasPreview || !node.previewExpanded)
  247. continue;
  248. var renderData = GetRenderData(node.tempId);
  249. CollectShaderProperties(node, renderData);
  250. renderData.shaderData.mat.SetVector("_TimeParameters", timeParameters);
  251. if (renderData.shaderData.shader == null)
  252. {
  253. renderData.texture = null;
  254. renderData.NotifyPreviewChanged();
  255. continue;
  256. }
  257. if (renderData.shaderData.hasError)
  258. {
  259. renderData.texture = m_ErrorTexture;
  260. renderData.NotifyPreviewChanged();
  261. continue;
  262. }
  263. if (renderData.previewMode == PreviewMode.Preview2D)
  264. m_RenderList2D.Add(renderData);
  265. else
  266. m_RenderList3D.Add(renderData);
  267. }
  268. EditorUtility.SetCameraAnimateMaterialsTime(m_SceneResources.camera, time);
  269. m_SceneResources.light0.enabled = true;
  270. m_SceneResources.light0.intensity = 1.0f;
  271. m_SceneResources.light0.transform.rotation = Quaternion.Euler(50f, 50f, 0);
  272. m_SceneResources.light1.enabled = true;
  273. m_SceneResources.light1.intensity = 1.0f;
  274. m_SceneResources.camera.clearFlags = CameraClearFlags.Color;
  275. // Render 2D previews
  276. m_SceneResources.camera.transform.position = -Vector3.forward * 2;
  277. m_SceneResources.camera.transform.rotation = Quaternion.identity;
  278. m_SceneResources.camera.orthographicSize = 0.5f;
  279. m_SceneResources.camera.orthographic = true;
  280. foreach (var renderData in m_RenderList2D)
  281. RenderPreview(renderData, m_SceneResources.quad, Matrix4x4.identity);
  282. // Render 3D previews
  283. m_SceneResources.camera.transform.position = -Vector3.forward * 5;
  284. m_SceneResources.camera.transform.rotation = Quaternion.identity;
  285. m_SceneResources.camera.orthographic = false;
  286. foreach (var renderData in m_RenderList3D)
  287. RenderPreview(renderData, m_SceneResources.sphere, Matrix4x4.identity);
  288. var renderMasterPreview = masterRenderData != null && m_NodesToDraw.Contains(masterRenderData.shaderData.node);
  289. if (renderMasterPreview)
  290. {
  291. CollectShaderProperties(masterRenderData.shaderData.node, masterRenderData);
  292. if (m_NewMasterPreviewSize.HasValue)
  293. {
  294. if (masterRenderData.renderTexture != null)
  295. Object.DestroyImmediate(masterRenderData.renderTexture, true);
  296. masterRenderData.renderTexture = new RenderTexture((int)m_NewMasterPreviewSize.Value.x, (int)m_NewMasterPreviewSize.Value.y, 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default) { hideFlags = HideFlags.HideAndDontSave };
  297. masterRenderData.renderTexture.Create();
  298. masterRenderData.texture = masterRenderData.renderTexture;
  299. m_NewMasterPreviewSize = null;
  300. }
  301. var mesh = m_Graph.previewData.serializedMesh.mesh ? m_Graph.previewData.serializedMesh.mesh : m_SceneResources.sphere;
  302. var previewTransform = Matrix4x4.Rotate(m_Graph.previewData.rotation);
  303. var scale = m_Graph.previewData.scale;
  304. previewTransform *= Matrix4x4.Scale(scale * Vector3.one * (Vector3.one).magnitude / mesh.bounds.size.magnitude);
  305. previewTransform *= Matrix4x4.Translate(-mesh.bounds.center);
  306. RenderPreview(masterRenderData, mesh, previewTransform);
  307. }
  308. m_SceneResources.light0.enabled = false;
  309. m_SceneResources.light1.enabled = false;
  310. foreach (var renderData in m_RenderList2D)
  311. renderData.NotifyPreviewChanged();
  312. foreach (var renderData in m_RenderList3D)
  313. renderData.NotifyPreviewChanged();
  314. if (renderMasterPreview)
  315. masterRenderData.NotifyPreviewChanged();
  316. m_RenderList2D.Clear();
  317. m_RenderList3D.Clear();
  318. m_NodesToDraw.Clear();
  319. }
  320. public void ForceShaderUpdate()
  321. {
  322. foreach (var data in m_RenderDatas)
  323. {
  324. if (data != null)
  325. {
  326. m_NodesToUpdate.Add(data.shaderData.node);
  327. }
  328. }
  329. }
  330. void UpdateShaders()
  331. {
  332. // Check for shaders that finished compiling and set them to redraw
  333. foreach (var renderData in m_RenderDatas)
  334. {
  335. if (renderData != null && renderData.shaderData.isCompiling)
  336. {
  337. var isCompiled = true;
  338. for (var i = 0; i < renderData.shaderData.mat.passCount; i++)
  339. {
  340. if (!ShaderUtil.IsPassCompiled(renderData.shaderData.mat, i))
  341. {
  342. isCompiled = false;
  343. break;
  344. }
  345. }
  346. if (!isCompiled)
  347. {
  348. continue;
  349. }
  350. // Force the material to re-generate all it's shader properties.
  351. renderData.shaderData.mat.shader = renderData.shaderData.shader;
  352. renderData.shaderData.isCompiling = false;
  353. CheckForErrors(renderData.shaderData);
  354. m_NodesToDraw.Add(renderData.shaderData.node);
  355. var masterNode = renderData.shaderData.node as IMasterNode;
  356. masterNode?.ProcessPreviewMaterial(renderData.shaderData.mat);
  357. }
  358. }
  359. if (m_NodesToUpdate.Count == 0)
  360. return;
  361. PropagateNodeList(m_NodesToUpdate, PropagationDirection.Downstream);
  362. // Reset error states for the UI, the shader, and all render data for nodes we're updating
  363. m_Messenger.ClearNodesFromProvider(this, m_NodesToUpdate);
  364. var wasAsyncAllowed = ShaderUtil.allowAsyncCompilation;
  365. ShaderUtil.allowAsyncCompilation = true;
  366. foreach (var node in m_NodesToUpdate)
  367. {
  368. if (node is IMasterNode && node == masterRenderData.shaderData.node && !(node is VfxMasterNode))
  369. {
  370. UpdateMasterNodeShader();
  371. continue;
  372. }
  373. if (!node.hasPreview && !(node is SubGraphOutputNode || node is VfxMasterNode))
  374. continue;
  375. var results = m_Graph.GetPreviewShader(node);
  376. var renderData = GetRenderData(node.tempId);
  377. if (renderData == null)
  378. {
  379. continue;
  380. }
  381. ShaderUtil.ClearCachedData(renderData.shaderData.shader);
  382. BeginCompile(renderData, results.shader);
  383. //get the preview mode from generated results
  384. renderData.previewMode = results.previewMode;
  385. }
  386. ShaderUtil.allowAsyncCompilation = wasAsyncAllowed;
  387. m_NodesToUpdate.Clear();
  388. }
  389. void BeginCompile(PreviewRenderData renderData, string shaderStr)
  390. {
  391. var shaderData = renderData.shaderData;
  392. ShaderUtil.ClearCachedData(shaderData.shader);
  393. ShaderUtil.UpdateShaderAsset(shaderData.shader, shaderStr, false);
  394. for (var i = 0; i < shaderData.mat.passCount; i++)
  395. {
  396. ShaderUtil.CompilePass(shaderData.mat, i);
  397. }
  398. shaderData.isCompiling = true;
  399. renderData.NotifyPreviewChanged();
  400. }
  401. void UpdateTimedNodeList()
  402. {
  403. if (!m_RefreshTimedNodes)
  404. return;
  405. m_TimedNodes.Clear();
  406. foreach (var timeNode in m_Graph.GetNodes<AbstractMaterialNode>().Where(node => node.RequiresTime()))
  407. {
  408. m_TimedNodes.Add(timeNode);
  409. }
  410. PropagateNodeList(m_TimedNodes, PropagationDirection.Downstream);
  411. m_RefreshTimedNodes = false;
  412. }
  413. void RenderPreview(PreviewRenderData renderData, Mesh mesh, Matrix4x4 transform)
  414. {
  415. var node = renderData.shaderData.node;
  416. Assert.IsTrue((node != null && node.hasPreview && node.previewExpanded) || node == masterRenderData?.shaderData?.node);
  417. if (renderData.shaderData.hasError)
  418. {
  419. renderData.texture = m_ErrorTexture;
  420. return;
  421. }
  422. var previousRenderTexture = RenderTexture.active;
  423. //Temp workaround for alpha previews...
  424. var temp = RenderTexture.GetTemporary(renderData.renderTexture.descriptor);
  425. RenderTexture.active = temp;
  426. Graphics.Blit(Texture2D.whiteTexture, temp, m_SceneResources.checkerboardMaterial);
  427. m_SceneResources.camera.targetTexture = temp;
  428. Graphics.DrawMesh(mesh, transform, renderData.shaderData.mat, 1, m_SceneResources.camera, 0, null, ShadowCastingMode.Off, false, null, false);
  429. var previousUseSRP = Unsupported.useScriptableRenderPipeline;
  430. Unsupported.useScriptableRenderPipeline = renderData.shaderData.node is IMasterNode;
  431. m_SceneResources.camera.Render();
  432. Unsupported.useScriptableRenderPipeline = previousUseSRP;
  433. Graphics.Blit(temp, renderData.renderTexture, m_SceneResources.blitNoAlphaMaterial);
  434. RenderTexture.ReleaseTemporary(temp);
  435. RenderTexture.active = previousRenderTexture;
  436. renderData.texture = renderData.renderTexture;
  437. }
  438. void CheckForErrors(PreviewShaderData shaderData)
  439. {
  440. shaderData.hasError = ShaderUtil.ShaderHasError(shaderData.shader);
  441. if (shaderData.hasError)
  442. {
  443. var messages = ShaderUtil.GetShaderMessages(shaderData.shader);
  444. if (messages.Length > 0)
  445. {
  446. m_Messenger.AddOrAppendError(this, shaderData.node.tempId, messages[0]);
  447. }
  448. }
  449. }
  450. void UpdateMasterNodeShader()
  451. {
  452. var shaderData = masterRenderData?.shaderData;
  453. var masterNode = shaderData?.node as IMasterNode;
  454. if (masterNode == null)
  455. return;
  456. List<PropertyCollector.TextureInfo> configuredTextures;
  457. shaderData.shaderString = masterNode.GetShader(GenerationMode.Preview, shaderData.node.name, out configuredTextures);
  458. if (string.IsNullOrEmpty(shaderData.shaderString))
  459. {
  460. if (shaderData.shader != null)
  461. {
  462. ShaderUtil.ClearShaderMessages(shaderData.shader);
  463. Object.DestroyImmediate(shaderData.shader, true);
  464. shaderData.shader = null;
  465. }
  466. return;
  467. }
  468. if (shaderData.shader == null)
  469. {
  470. shaderData.shader = ShaderUtil.CreateShaderAsset(shaderData.shaderString, false);
  471. shaderData.shader.hideFlags = HideFlags.HideAndDontSave;
  472. }
  473. else
  474. {
  475. ShaderUtil.ClearCachedData(shaderData.shader);
  476. }
  477. BeginCompile(masterRenderData, shaderData.shaderString);
  478. }
  479. void DestroyRenderData(PreviewRenderData renderData)
  480. {
  481. if (renderData.shaderData != null)
  482. {
  483. if (renderData.shaderData.mat != null)
  484. {
  485. Object.DestroyImmediate(renderData.shaderData.mat, true);
  486. }
  487. if (renderData.shaderData.shader != null)
  488. {
  489. Object.DestroyImmediate(renderData.shaderData.shader, true);
  490. }
  491. }
  492. if (renderData.renderTexture != null)
  493. Object.DestroyImmediate(renderData.renderTexture, true);
  494. if (renderData.shaderData != null && renderData.shaderData.node != null)
  495. renderData.shaderData.node.UnregisterCallback(OnNodeModified);
  496. }
  497. void DestroyPreview(Identifier nodeId)
  498. {
  499. var renderData = Get(m_RenderDatas, nodeId);
  500. if (renderData == null)
  501. {
  502. return;
  503. }
  504. DestroyRenderData(renderData);
  505. Set(m_RenderDatas, nodeId, null);
  506. Set(m_Identifiers, nodeId, default(Identifier));
  507. // Check if we're destroying the shader data used by the master preview
  508. if (masterRenderData == renderData)
  509. {
  510. m_MasterRenderData = null;
  511. if (!m_Graph.isSubGraph && renderData.shaderData.node.guid != m_Graph.activeOutputNodeGuid)
  512. {
  513. AddPreview(m_Graph.outputNode);
  514. }
  515. if (onPrimaryMasterChanged != null)
  516. onPrimaryMasterChanged();
  517. }
  518. }
  519. void ReleaseUnmanagedResources()
  520. {
  521. if (m_ErrorTexture != null)
  522. {
  523. Object.DestroyImmediate(m_ErrorTexture);
  524. m_ErrorTexture = null;
  525. }
  526. if (m_SceneResources != null)
  527. {
  528. m_SceneResources.Dispose();
  529. m_SceneResources = null;
  530. }
  531. foreach (var renderData in m_RenderDatas.Where(x => x != null))
  532. DestroyRenderData(renderData);
  533. m_RenderDatas.Clear();
  534. }
  535. public void Dispose()
  536. {
  537. ReleaseUnmanagedResources();
  538. GC.SuppressFinalize(this);
  539. }
  540. ~PreviewManager()
  541. {
  542. throw new Exception("PreviewManager was not disposed of properly.");
  543. }
  544. const string k_EmptyShader = @"
  545. Shader ""hidden/preview""
  546. {
  547. SubShader
  548. {
  549. Tags { ""RenderType""=""Opaque"" }
  550. LOD 100
  551. Pass
  552. {
  553. CGPROGRAM
  554. #pragma vertex vert
  555. #pragma fragment frag
  556. #include ""UnityCG.cginc""
  557. struct appdata
  558. {
  559. float4 vertex : POSITION;
  560. };
  561. struct v2f
  562. {
  563. float4 vertex : SV_POSITION;
  564. };
  565. v2f vert (appdata v)
  566. {
  567. v2f o;
  568. o.vertex = UnityObjectToClipPos(v.vertex);
  569. return o;
  570. }
  571. fixed4 frag (v2f i) : SV_Target
  572. {
  573. return 0;
  574. }
  575. ENDCG
  576. }
  577. }
  578. }";
  579. T Get<T>(List<T> list, Identifier id)
  580. {
  581. var existingId = Get(m_Identifiers, id.index);
  582. if (existingId.valid && existingId.version != id.version)
  583. throw new InvalidOperationException($"Identifier version mismatch at index {id.index}: {id.version} != {existingId.version}");
  584. return Get(list, id.index);
  585. }
  586. static T Get<T>(List<T> list, int index)
  587. {
  588. return index < list.Count ? list[index] : default(T);
  589. }
  590. void Set<T>(List<T> list, Identifier id, T value)
  591. {
  592. var existingId = Get(m_Identifiers, id.index);
  593. if (existingId.valid && existingId.version != id.version)
  594. throw new InvalidOperationException($"Identifier version mismatch at index {id.index}: {id.version} != {existingId.version}");
  595. Set(list, id.index, value);
  596. }
  597. static void Set<T>(List<T> list, int index, T value)
  598. {
  599. // Make sure the list is large enough for the index
  600. for (var i = list.Count; i <= index; i++)
  601. list.Add(default(T));
  602. list[index] = value;
  603. }
  604. PreviewRenderData GetRenderData(Identifier id)
  605. {
  606. var value = Get(m_RenderDatas, id);
  607. if (value != null && value.shaderData.node.tempId.version != id.version)
  608. throw new InvalidOperationException("Trying to access render data of a previous version of a node");
  609. return value;
  610. }
  611. }
  612. delegate void OnPreviewChanged();
  613. class PreviewShaderData
  614. {
  615. public AbstractMaterialNode node { get; set; }
  616. public Shader shader { get; set; }
  617. public Material mat { get; set; }
  618. public string shaderString { get; set; }
  619. public bool isCompiling { get; set; }
  620. public bool hasError { get; set; }
  621. }
  622. class PreviewRenderData
  623. {
  624. public PreviewShaderData shaderData { get; set; }
  625. public RenderTexture renderTexture { get; set; }
  626. public Texture texture { get; set; }
  627. public PreviewMode previewMode { get; set; }
  628. public OnPreviewChanged onPreviewChanged;
  629. public void NotifyPreviewChanged()
  630. {
  631. if (onPreviewChanged != null)
  632. onPreviewChanged();
  633. }
  634. }
  635. }