VFXExpressionGraph.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. using UnityEngine.VFX;
  6. using UnityEngine.Profiling;
  7. using Object = UnityEngine.Object;
  8. using UnityEditor.Graphs;
  9. using System.Collections.ObjectModel;
  10. namespace UnityEditor.VFX
  11. {
  12. enum VFXDeviceTarget
  13. {
  14. CPU,
  15. GPU,
  16. }
  17. class VFXExpressionGraph
  18. {
  19. private struct ExpressionData
  20. {
  21. public int depth;
  22. public int index;
  23. }
  24. public VFXExpressionGraph()
  25. { }
  26. private void AddExpressionDataRecursively(Dictionary<VFXExpression, ExpressionData> dst, VFXExpression exp, int depth = 0)
  27. {
  28. ExpressionData data;
  29. if (!dst.TryGetValue(exp, out data) || data.depth < depth)
  30. {
  31. data.index = -1; // Will be overridden later on
  32. data.depth = depth;
  33. dst[exp] = data;
  34. foreach (var parent in exp.parents)
  35. AddExpressionDataRecursively(dst, parent, depth + 1);
  36. }
  37. }
  38. private void CompileExpressionContext(IEnumerable<VFXContext> contexts,
  39. VFXExpressionContextOption options,
  40. VFXDeviceTarget target,
  41. VFXExpression.Flags forbiddenFlags = VFXExpression.Flags.None)
  42. {
  43. var expressionContext = new VFXExpression.Context(options, m_GlobalEventAttributes);
  44. var contextsToExpressions = target == VFXDeviceTarget.GPU ? m_ContextsToGPUExpressions : m_ContextsToCPUExpressions;
  45. var expressionsToReduced = target == VFXDeviceTarget.GPU ? m_GPUExpressionsToReduced : m_CPUExpressionsToReduced;
  46. foreach (var context in contexts)
  47. {
  48. var mapper = context.GetExpressionMapper(target);
  49. if (mapper != null)
  50. {
  51. foreach (var exp in mapper.expressions)
  52. expressionContext.RegisterExpression(exp);
  53. contextsToExpressions.Add(context, mapper);
  54. }
  55. }
  56. expressionContext.Compile();
  57. foreach (var exp in expressionContext.RegisteredExpressions)
  58. {
  59. var reduced = expressionContext.GetReduced(exp);
  60. if (expressionsToReduced.ContainsKey(exp))
  61. {
  62. if (reduced != expressionsToReduced[exp])
  63. throw new InvalidOperationException("Unexpected diverging expression reduction");
  64. continue;
  65. }
  66. expressionsToReduced.Add(exp, reduced);
  67. }
  68. var allReduced = expressionContext.BuildAllReduced();
  69. m_Expressions.UnionWith(allReduced);
  70. foreach (var exp in expressionsToReduced.Values)
  71. AddExpressionDataRecursively(m_ExpressionsData, exp);
  72. var graphicsBufferUsageType = m_GraphicsBufferUsageType
  73. .Concat(expressionContext.GraphicsBufferUsageType)
  74. .GroupBy(o => o.Key).ToArray();
  75. m_GraphicsBufferUsageType.Clear();
  76. foreach (var expression in graphicsBufferUsageType)
  77. {
  78. var types = expression.Select(o => o.Value);
  79. if (types.Count() != 1)
  80. throw new InvalidOperationException("Diverging type usage for GraphicsBuffer : " + types.Select(o => o.ToString()).Aggregate((a, b) => a + b));
  81. m_GraphicsBufferUsageType.Add(expression.Key, types.First());
  82. }
  83. }
  84. public void CompileExpressions(VFXGraph graph, VFXExpressionContextOption options, bool filterOutInvalidContexts = false)
  85. {
  86. var models = new HashSet<ScriptableObject>();
  87. graph.CollectDependencies(models, false);
  88. var contexts = models.OfType<VFXContext>();
  89. if (filterOutInvalidContexts)
  90. contexts = contexts.Where(c => c.CanBeCompiled());
  91. CompileExpressions(contexts, options);
  92. }
  93. private static void ComputeEventAttributeDescs(List<VFXLayoutElementDesc> globalEventAttributes, IEnumerable<VFXContext> contexts)
  94. {
  95. globalEventAttributes.Clear();
  96. //SpawnCount should always be added first : spawnCount is an implicit parameter from eventAttribute
  97. globalEventAttributes.Add(new VFXLayoutElementDesc()
  98. {
  99. name = VFXAttribute.SpawnCount.name,
  100. type = VFXAttribute.SpawnCount.type
  101. });
  102. IEnumerable<VFXLayoutElementDesc> globalAttribute = Enumerable.Empty<VFXLayoutElementDesc>();
  103. foreach (var context in contexts.Where(o => o.contextType == VFXContextType.Spawner || o.contextType == VFXContextType.Event))
  104. {
  105. var attributesToStoreFromOutputContext = context.outputContexts.Select(o => o.GetData()).Where(o => o != null)
  106. .SelectMany(o => o.GetAttributes().Where(a => (a.mode & VFXAttributeMode.ReadSource) != 0));
  107. var attributesReadInSpawnContext = context.GetData().GetAttributes().Where(a => (a.mode & VFXAttributeMode.Read) != 0);
  108. var attributesInGlobal = attributesToStoreFromOutputContext.Concat(attributesReadInSpawnContext).GroupBy(o => o.attrib.name);
  109. foreach (var attribute in attributesInGlobal.Select(o => o.First()))
  110. {
  111. if (!globalEventAttributes.Any(o => o.name == attribute.attrib.name))
  112. {
  113. globalEventAttributes.Add(new VFXLayoutElementDesc()
  114. {
  115. name = attribute.attrib.name,
  116. type = attribute.attrib.type
  117. });
  118. }
  119. }
  120. }
  121. var structureLayoutTotalSize = (uint)globalEventAttributes.Sum(e => (long)VFXExpression.TypeToSize(e.type));
  122. var currentLayoutSize = 0u;
  123. var listWithOffset = new List<VFXLayoutElementDesc>();
  124. globalEventAttributes.ForEach(e =>
  125. {
  126. e.offset.element = currentLayoutSize;
  127. e.offset.structure = structureLayoutTotalSize;
  128. currentLayoutSize += (uint)VFXExpression.TypeToSize(e.type);
  129. listWithOffset.Add(e);
  130. });
  131. globalEventAttributes.Clear();
  132. globalEventAttributes.AddRange(listWithOffset);
  133. }
  134. public void CompileExpressions(IEnumerable<VFXContext> contexts, VFXExpressionContextOption options)
  135. {
  136. Profiler.BeginSample("VFXEditor.CompileExpressionGraph");
  137. try
  138. {
  139. ComputeEventAttributeDescs(m_GlobalEventAttributes, contexts);
  140. m_Expressions.Clear();
  141. m_FlattenedExpressions.Clear();
  142. m_CommonExpressionCount = 0u;
  143. m_ExpressionsData.Clear();
  144. m_ContextsToGPUExpressions.Clear();
  145. m_ContextsToCPUExpressions.Clear();
  146. m_GPUExpressionsToReduced.Clear();
  147. m_CPUExpressionsToReduced.Clear();
  148. var spawnerContexts = contexts.Where(o => o.contextType == VFXContextType.Spawner);
  149. var otherContexts = contexts.Where(o => o.contextType != VFXContextType.Spawner);
  150. CompileExpressionContext(spawnerContexts,
  151. options | VFXExpressionContextOption.PatchReadToEventAttribute,
  152. VFXDeviceTarget.CPU,
  153. VFXExpression.Flags.NotCompilableOnCPU);
  154. CompileExpressionContext(otherContexts,
  155. options,
  156. VFXDeviceTarget.CPU,
  157. VFXExpression.Flags.NotCompilableOnCPU | VFXExpression.Flags.PerSpawn);
  158. CompileExpressionContext(contexts,
  159. options | VFXExpressionContextOption.GPUDataTransformation,
  160. VFXDeviceTarget.GPU,
  161. VFXExpression.Flags.PerSpawn);
  162. var sortedList = m_ExpressionsData.Where(kvp =>
  163. {
  164. var exp = kvp.Key;
  165. return !exp.IsAny(VFXExpression.Flags.NotCompilableOnCPU); // remove per element expression from flattened data // TODO Remove uniform constants too
  166. });
  167. var expressionPerSpawn = sortedList.Where(o => o.Key.Is(VFXExpression.Flags.PerSpawn));
  168. var expressionNotPerSpawn = sortedList.Where(o => !o.Key.Is(VFXExpression.Flags.PerSpawn));
  169. //m_FlattenedExpressions is a concatenation of [sorted all expression !PerSpawn] & [sorted all expression Per Spawn]
  170. //It's more convenient for two reasons :
  171. // - Reduces process chunk for ComputePreProcessExpressionForSpawn
  172. // - Allows to determine the maximum index of expression while processing main expression evaluation
  173. sortedList = expressionNotPerSpawn.OrderByDescending(o => o.Value.depth);
  174. sortedList = sortedList.Concat(expressionPerSpawn.OrderByDescending(o => o.Value.depth));
  175. m_FlattenedExpressions = sortedList.Select(o => o.Key).ToList();
  176. m_CommonExpressionCount = (uint)expressionNotPerSpawn.Count();
  177. // update index in expression data
  178. for (int i = 0; i < m_FlattenedExpressions.Count; ++i)
  179. {
  180. var data = m_ExpressionsData[m_FlattenedExpressions[i]];
  181. data.index = i;
  182. m_ExpressionsData[m_FlattenedExpressions[i]] = data;
  183. }
  184. if (VFXViewPreference.advancedLogs)
  185. Debug.Log(string.Format("RECOMPILE EXPRESSION GRAPH - NB EXPRESSIONS: {0} - NB CPU END EXPRESSIONS: {1} - NB GPU END EXPRESSIONS: {2}", m_Expressions.Count, m_CPUExpressionsToReduced.Count, m_GPUExpressionsToReduced.Count));
  186. }
  187. finally
  188. {
  189. Profiler.EndSample();
  190. }
  191. }
  192. public int GetFlattenedIndex(VFXExpression exp)
  193. {
  194. if (m_ExpressionsData.ContainsKey(exp))
  195. return m_ExpressionsData[exp].index;
  196. return -1;
  197. }
  198. public VFXExpression GetReduced(VFXExpression exp, VFXDeviceTarget target)
  199. {
  200. VFXExpression reduced;
  201. var expressionToReduced = target == VFXDeviceTarget.GPU ? m_GPUExpressionsToReduced : m_CPUExpressionsToReduced;
  202. expressionToReduced.TryGetValue(exp, out reduced);
  203. return reduced;
  204. }
  205. public VFXExpressionMapper BuildCPUMapper(VFXContext context)
  206. {
  207. return BuildMapper(context, m_ContextsToCPUExpressions, VFXDeviceTarget.CPU);
  208. }
  209. public VFXExpressionMapper BuildGPUMapper(VFXContext context)
  210. {
  211. return BuildMapper(context, m_ContextsToGPUExpressions, VFXDeviceTarget.GPU);
  212. }
  213. public List<string> GetAllNames(VFXExpression exp)
  214. {
  215. List<string> names = new List<string>();
  216. foreach (var mapper in m_ContextsToCPUExpressions.Values.Concat(m_ContextsToGPUExpressions.Values))
  217. {
  218. names.AddRange(mapper.GetData(exp).Select(o => o.fullName));
  219. }
  220. return names;
  221. }
  222. private VFXExpressionMapper BuildMapper(VFXContext context, Dictionary<VFXContext, VFXExpressionMapper> dictionnary, VFXDeviceTarget target)
  223. {
  224. VFXExpression.Flags check = target == VFXDeviceTarget.GPU ? VFXExpression.Flags.InvalidOnGPU | VFXExpression.Flags.PerElement : VFXExpression.Flags.InvalidOnCPU;
  225. VFXExpressionMapper outMapper = new VFXExpressionMapper();
  226. VFXExpressionMapper inMapper;
  227. dictionnary.TryGetValue(context, out inMapper);
  228. if (inMapper != null)
  229. {
  230. foreach (var exp in inMapper.expressions)
  231. {
  232. var reduced = GetReduced(exp, target);
  233. if (reduced.Is(check))
  234. throw new InvalidOperationException(string.Format("The expression {0} is not valid as it have the invalid flag: {1}", reduced, check));
  235. var mappedDataList = inMapper.GetData(exp);
  236. foreach (var mappedData in mappedDataList)
  237. outMapper.AddExpression(reduced, mappedData);
  238. }
  239. }
  240. return outMapper;
  241. }
  242. public HashSet<VFXExpression> Expressions
  243. {
  244. get
  245. {
  246. return m_Expressions;
  247. }
  248. }
  249. public List<VFXExpression> FlattenedExpressions
  250. {
  251. get
  252. {
  253. return m_FlattenedExpressions;
  254. }
  255. }
  256. public uint CommonExpressionCount
  257. {
  258. get
  259. {
  260. return m_CommonExpressionCount;
  261. }
  262. }
  263. public Dictionary<VFXExpression, VFXExpression> GPUExpressionsToReduced
  264. {
  265. get
  266. {
  267. return m_GPUExpressionsToReduced;
  268. }
  269. }
  270. public Dictionary<VFXExpression, VFXExpression> CPUExpressionsToReduced
  271. {
  272. get
  273. {
  274. return m_CPUExpressionsToReduced;
  275. }
  276. }
  277. public IEnumerable<VFXLayoutElementDesc> GlobalEventAttributes
  278. {
  279. get
  280. {
  281. return m_GlobalEventAttributes;
  282. }
  283. }
  284. public ReadOnlyDictionary<VFXExpression, Type> GraphicsBufferTypeUsage
  285. {
  286. get
  287. {
  288. return new ReadOnlyDictionary<VFXExpression, Type>(m_GraphicsBufferUsageType);
  289. }
  290. }
  291. private Dictionary<VFXExpression, Type> m_GraphicsBufferUsageType = new Dictionary<VFXExpression, Type>();
  292. private HashSet<VFXExpression> m_Expressions = new HashSet<VFXExpression>();
  293. private Dictionary<VFXExpression, VFXExpression> m_CPUExpressionsToReduced = new Dictionary<VFXExpression, VFXExpression>();
  294. private Dictionary<VFXExpression, VFXExpression> m_GPUExpressionsToReduced = new Dictionary<VFXExpression, VFXExpression>();
  295. private List<VFXExpression> m_FlattenedExpressions = new List<VFXExpression>();
  296. private uint m_CommonExpressionCount;
  297. private Dictionary<VFXExpression, ExpressionData> m_ExpressionsData = new Dictionary<VFXExpression, ExpressionData>();
  298. private Dictionary<VFXContext, VFXExpressionMapper> m_ContextsToCPUExpressions = new Dictionary<VFXContext, VFXExpressionMapper>();
  299. private Dictionary<VFXContext, VFXExpressionMapper> m_ContextsToGPUExpressions = new Dictionary<VFXContext, VFXExpressionMapper>();
  300. private List<VFXLayoutElementDesc> m_GlobalEventAttributes = new List<VFXLayoutElementDesc>();
  301. }
  302. }