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.

3211 lines
127 KiB

  1. // Amplify Shader Editor - Visual Shader Editing Tool
  2. // Copyright (c) Amplify Creations, Lda <info@amplify.pt>
  3. using System;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6. using UnityEditor;
  7. using UnityEditorInternal;
  8. namespace AmplifyShaderEditor
  9. {
  10. public enum VertexMode
  11. {
  12. Relative,
  13. Absolute
  14. }
  15. public enum RenderPath
  16. {
  17. All,
  18. ForwardOnly,
  19. DeferredOnly
  20. }
  21. public enum StandardShaderLightModel
  22. {
  23. Standard,
  24. StandardSpecular,
  25. Lambert,
  26. BlinnPhong,
  27. Unlit,
  28. CustomLighting
  29. }
  30. public enum CullMode
  31. {
  32. Back,
  33. Front,
  34. Off
  35. }
  36. public enum AlphaMode
  37. {
  38. Opaque = 0,
  39. Masked = 1,
  40. Transparent = 2, // Transparent (alpha:fade)
  41. Translucent = 3,
  42. Premultiply = 4, // Alpha Premul (alpha:premul)
  43. Custom = 5,
  44. }
  45. public enum RenderType
  46. {
  47. Opaque,
  48. Transparent,
  49. TransparentCutout,
  50. Background,
  51. Overlay,
  52. TreeOpaque,
  53. TreeTransparentCutout,
  54. TreeBillboard,
  55. Grass,
  56. GrassBillboard,
  57. Custom
  58. }
  59. public enum RenderQueue
  60. {
  61. Background,
  62. Geometry,
  63. AlphaTest,
  64. Transparent,
  65. Overlay
  66. }
  67. public enum RenderPlatforms
  68. {
  69. d3d9,
  70. d3d11,
  71. glcore,
  72. gles,
  73. gles3,
  74. metal,
  75. d3d11_9x,
  76. xbox360,
  77. xboxone,
  78. ps4,
  79. psp2,
  80. n3ds,
  81. wiiu
  82. }
  83. [Serializable]
  84. public class NodeCache
  85. {
  86. public int TargetNodeId = -1;
  87. public int TargetPortId = -1;
  88. public NodeCache( int targetNodeId, int targetPortId )
  89. {
  90. SetData( targetNodeId, targetPortId );
  91. }
  92. public void SetData( int targetNodeId, int targetPortId )
  93. {
  94. TargetNodeId = targetNodeId;
  95. TargetPortId = targetPortId;
  96. }
  97. public void Invalidate()
  98. {
  99. TargetNodeId = -1;
  100. TargetPortId = -1;
  101. }
  102. public bool IsValid
  103. {
  104. get { return ( TargetNodeId >= 0 ); }
  105. }
  106. public override string ToString()
  107. {
  108. return "TargetNodeId " + TargetNodeId + " TargetPortId " + TargetPortId;
  109. }
  110. }
  111. [Serializable]
  112. public class CacheNodeConnections
  113. {
  114. public Dictionary<string, List<NodeCache>> NodeCacheArray;
  115. public CacheNodeConnections()
  116. {
  117. NodeCacheArray = new Dictionary<string, List<NodeCache>>();
  118. }
  119. public void Add( string key, NodeCache value )
  120. {
  121. if( NodeCacheArray.ContainsKey( key ) )
  122. {
  123. NodeCacheArray[ key ].Add( value );
  124. }
  125. else
  126. {
  127. NodeCacheArray.Add( key, new List<NodeCache>() );
  128. NodeCacheArray[ key ].Add( value );
  129. }
  130. }
  131. public NodeCache Get( string key, int idx = 0 )
  132. {
  133. if( NodeCacheArray.ContainsKey( key ) )
  134. {
  135. if( idx < NodeCacheArray[ key ].Count )
  136. return NodeCacheArray[ key ][ idx ];
  137. }
  138. return null;
  139. }
  140. public List<NodeCache> GetList( string key )
  141. {
  142. if( NodeCacheArray.ContainsKey( key ) )
  143. {
  144. return NodeCacheArray[ key ];
  145. }
  146. return null;
  147. }
  148. public void Clear()
  149. {
  150. foreach( KeyValuePair<string, List<NodeCache>> kvp in NodeCacheArray )
  151. {
  152. kvp.Value.Clear();
  153. }
  154. NodeCacheArray.Clear();
  155. }
  156. }
  157. [Serializable]
  158. [NodeAttributes( "Standard Surface Output", "Master", "Surface shader generator output", null, KeyCode.None, false )]
  159. public sealed class StandardSurfaceOutputNode : MasterNode, ISerializationCallbackReceiver
  160. {
  161. private readonly static string[] VertexLitFunc = { "\t\tinline half4 LightingUnlit( SurfaceOutput s, half3 lightDir, half atten )",
  162. "\t\t{",
  163. "\t\t\treturn half4 ( 0, 0, 0, s.Alpha );",
  164. "\t\t}\n"};
  165. private readonly static string[] FadeModeOptions = { "Opaque", "Masked", "Transparent", "Translucent", "Alpha Premultipled", "Custom" };
  166. private const string VertexModeStr = "Vertex Output";
  167. private readonly static GUIContent RenderPathContent = new GUIContent( "Render Path", "Selects and generates passes for the supported rendering paths\nDefault: All" );
  168. private const string ShaderModelStr = "Shader Model";
  169. private readonly static GUIContent LightModelContent = new GUIContent( "Light Model", "Surface shader lighting model defines how the surface reflects light\nDefault: Standard" );
  170. private readonly static GUIContent ShaderLODContent = new GUIContent( "Shader LOD", "Shader LOD" );
  171. private readonly static GUIContent CullModeContent = new GUIContent( "Cull Mode", "Polygon culling mode prevents rendering of either back-facing or front-facing polygons to save performance, turn it off if you want to render both sides\nDefault: Back" );
  172. private const string DiscardStr = "Opacity Mask";
  173. private const string VertexDisplacementStr = "Local Vertex Offset";
  174. private const string VertexPositionStr = "Local Vertex Position";
  175. private const string VertexDataStr = "VertexData";
  176. private const string VertexNormalStr = "Local Vertex Normal";
  177. private const string CustomLightingStr = "Custom Lighting";
  178. private const string AlbedoStr = "Albedo";
  179. private const string NormalStr = "Normal";
  180. private const string EmissionStr = "Emission";
  181. private const string MetallicStr = "Metallic";
  182. private const string SmoothnessStr = "Smoothness";
  183. private const string OcclusionDataStr = "Occlusion";
  184. private const string OcclusionLabelStr = "Ambient Occlusion";
  185. private const string TransmissionStr = "Transmission";
  186. private const string TranslucencyStr = "Translucency";
  187. private const string RefractionStr = "Refraction";
  188. private const string AlphaStr = "Opacity";
  189. private const string AlphaDataStr = "Alpha";
  190. private const string DebugStr = "Debug";
  191. private const string SpecularStr = "Specular";
  192. private const string GlossStr = "Gloss";
  193. private const string CustomRenderTypeStr = "Custom Type";
  194. private readonly static GUIContent AlphaModeContent = new GUIContent( " Blend Mode", "Defines how the surface blends with the background\nDefault: Opaque" );
  195. private const string OpacityMaskClipValueStr = "Mask Clip Value";
  196. private readonly static GUIContent OpacityMaskClipValueContent = new GUIContent( "Mask Clip Value", "Default clip value to be compared with opacity alpha ( 0 = fully Opaque, 1 = fully Masked )\nDefault: 0.5" );
  197. private readonly static GUIContent CastShadowsContent = new GUIContent( "Cast Shadows", "Generates a shadow caster pass for vertex modifications and point lights in forward rendering\nDefault: ON" );
  198. private readonly static GUIContent ReceiveShadowsContent = new GUIContent( "Receive Shadows", "Untick it to disable shadow receiving, this includes self-shadowing (only for forward rendering) \nDefault: ON" );
  199. private readonly static GUIContent QueueIndexContent = new GUIContent( "Queue Index", "Value to offset the render queue, accepts both positive values to render later and negative values to render sooner\nDefault: 0" );
  200. private readonly static GUIContent RefractionLayerStr = new GUIContent( "Refraction Layer", "Use it to group or ungroup different refraction shaders into the same or different grabpass (only for forward rendering) \nDefault: 0" );
  201. private readonly static GUIContent AlphaToCoverageStr = new GUIContent( "Alpha To Coverage", "" );
  202. private readonly static GUIContent RenderQueueContent = new GUIContent( "Render Queue", "Base rendering queue index\n(Background = 1000, Geometry = 2000, AlphaTest = 2450, Transparent = 3000, Overlay = 4000)\nDefault: Geometry" );
  203. private readonly static GUIContent RenderTypeContent = new GUIContent( "Render Type", "Categorizes shaders into several predefined groups, usually to be used with screen shader effects\nDefault: Opaque" );
  204. private const string ShaderInputOrderStr = "Shader Input Order";
  205. [SerializeField]
  206. private BlendOpsHelper m_blendOpsHelper = new BlendOpsHelper();
  207. [SerializeField]
  208. private StencilBufferOpHelper m_stencilBufferHelper = new StencilBufferOpHelper();
  209. [SerializeField]
  210. private ZBufferOpHelper m_zBufferHelper = new ZBufferOpHelper();
  211. [SerializeField]
  212. private OutlineOpHelper m_outlineHelper = new OutlineOpHelper();
  213. [SerializeField]
  214. private TessellationOpHelper m_tessOpHelper = new TessellationOpHelper();
  215. [SerializeField]
  216. private ColorMaskHelper m_colorMaskHelper = new ColorMaskHelper();
  217. [SerializeField]
  218. private RenderingPlatformOpHelper m_renderingPlatformOpHelper = new RenderingPlatformOpHelper();
  219. [SerializeField]
  220. private RenderingOptionsOpHelper m_renderingOptionsOpHelper = new RenderingOptionsOpHelper();
  221. [SerializeField]
  222. private BillboardOpHelper m_billboardOpHelper = new BillboardOpHelper();
  223. [SerializeField]
  224. private FallbackPickerHelper m_fallbackHelper = null;
  225. //legacy
  226. [SerializeField]
  227. private AdditionalIncludesHelper m_additionalIncludes = new AdditionalIncludesHelper();
  228. //legacy
  229. [SerializeField]
  230. private AdditionalPragmasHelper m_additionalPragmas = new AdditionalPragmasHelper();
  231. //legacy
  232. [SerializeField]
  233. private AdditionalDefinesHelper m_additionalDefines = new AdditionalDefinesHelper();
  234. [SerializeField]
  235. private TemplateAdditionalDirectivesHelper m_additionalDirectives = new TemplateAdditionalDirectivesHelper(" Additional Directives");
  236. [SerializeField]
  237. private AdditionalSurfaceOptionsHelper m_additionalSurfaceOptions = new AdditionalSurfaceOptionsHelper();
  238. [SerializeField]
  239. private UsePassHelper m_usePass;
  240. [SerializeField]
  241. private CustomTagsHelper m_customTagsHelper = new CustomTagsHelper();
  242. [SerializeField]
  243. private DependenciesHelper m_dependenciesHelper = new DependenciesHelper();
  244. [SerializeField]
  245. private StandardShaderLightModel m_currentLightModel;
  246. [SerializeField]
  247. private StandardShaderLightModel m_lastLightModel;
  248. [SerializeField]
  249. private CullMode m_cullMode = CullMode.Back;
  250. [SerializeField]
  251. private InlineProperty m_inlineCullMode = new InlineProperty();
  252. [SerializeField]
  253. private AlphaMode m_alphaMode = AlphaMode.Opaque;
  254. [SerializeField]
  255. private RenderType m_renderType = RenderType.Opaque;
  256. [SerializeField]
  257. private string m_customRenderType = string.Empty;
  258. [SerializeField]
  259. private RenderQueue m_renderQueue = RenderQueue.Geometry;
  260. [SerializeField]
  261. private RenderPath m_renderPath = RenderPath.All;
  262. [SerializeField]
  263. private VertexMode m_vertexMode = VertexMode.Relative;
  264. [SerializeField]
  265. private bool m_customBlendMode = false;
  266. [SerializeField]
  267. private float m_opacityMaskClipValue = 0.5f;
  268. [SerializeField]
  269. private InlineProperty m_inlineOpacityMaskClipValue = new InlineProperty();
  270. [SerializeField]
  271. private int m_customLightingPortId = -1;
  272. [SerializeField]
  273. private int m_emissionPortId = -1;
  274. [SerializeField]
  275. private int m_discardPortId = -1;
  276. [SerializeField]
  277. private int m_opacityPortId = -1;
  278. [SerializeField]
  279. private int m_vertexPortId = -1;
  280. [SerializeField]
  281. private bool m_keepAlpha = true;
  282. [SerializeField]
  283. private bool m_castShadows = true;
  284. //[SerializeField]
  285. private bool m_customShadowCaster = false;
  286. [SerializeField]
  287. private bool m_receiveShadows = true;
  288. [SerializeField]
  289. private int m_queueOrder = 0;
  290. [SerializeField]
  291. private int m_grabOrder = 0;
  292. [SerializeField]
  293. private bool m_alphaToCoverage = false;
  294. private InputPort m_transmissionPort;
  295. private InputPort m_translucencyPort;
  296. private InputPort m_tessellationPort;
  297. private bool m_previousTranslucencyOn = false;
  298. private bool m_previousRefractionOn = false;
  299. [SerializeField]
  300. private CacheNodeConnections m_cacheNodeConnections = new CacheNodeConnections();
  301. private bool m_usingProSkin = false;
  302. private GUIStyle m_inspectorFoldoutStyle;
  303. private GUIStyle m_inspectorToolbarStyle;
  304. private GUIStyle m_inspectorTooldropdownStyle;
  305. private bool m_customBlendAvailable = false;
  306. private Color m_cachedColor = Color.white;
  307. private float m_titleOpacity = 0.5f;
  308. private float m_boxOpacity = 0.5f;
  309. private InputPort m_refractionPort;
  310. private InputPort m_normalPort;
  311. private GUIStyle m_inspectorDefaultStyle;
  312. [SerializeField]
  313. private ReordenatorNode m_specColorReorder = null;
  314. [SerializeField]
  315. private int m_specColorOrderIndex = -1;
  316. [SerializeField]
  317. private ReordenatorNode m_maskClipReorder = null;
  318. [SerializeField]
  319. private int m_maskClipOrderIndex = -1;
  320. [SerializeField]
  321. private ReordenatorNode m_translucencyReorder = null;
  322. [SerializeField]
  323. private int m_translucencyOrderIndex = -1;
  324. [SerializeField]
  325. private ReordenatorNode m_refractionReorder = null;
  326. [SerializeField]
  327. private int m_refractionOrderIndex = -1;
  328. [SerializeField]
  329. private ReordenatorNode m_tessellationReorder = null;
  330. [SerializeField]
  331. private int m_tessellationOrderIndex = -1;
  332. private bool m_previousTessellationOn = false;
  333. private bool m_initialize = true;
  334. private bool m_checkChanges = true;
  335. private bool m_lightModelChanged = true;
  336. private PropertyNode m_dummyProperty = null;
  337. protected override void CommonInit( int uniqueId )
  338. {
  339. m_currentLightModel = m_lastLightModel = StandardShaderLightModel.Standard;
  340. m_textLabelWidth = 120;
  341. m_autoDrawInternalPortData = false;
  342. base.CommonInit( uniqueId );
  343. m_zBufferHelper.ParentSurface = this;
  344. m_tessOpHelper.ParentSurface = this;
  345. }
  346. public override void OnEnable()
  347. {
  348. base.OnEnable();
  349. if( m_usePass == null )
  350. {
  351. m_usePass = ScriptableObject.CreateInstance<UsePassHelper>();
  352. m_usePass.Init( " Additional Use Passes" );
  353. }
  354. if( m_fallbackHelper == null )
  355. {
  356. m_fallbackHelper = ScriptableObject.CreateInstance<FallbackPickerHelper>();
  357. m_fallbackHelper.Init();
  358. }
  359. }
  360. public override void AddMasterPorts()
  361. {
  362. int vertexCorrection = 2;
  363. int index = vertexCorrection + 2;
  364. base.AddMasterPorts();
  365. switch( m_currentLightModel )
  366. {
  367. case StandardShaderLightModel.Standard:
  368. {
  369. AddInputPort( WirePortDataType.FLOAT3, false, AlbedoStr, vertexCorrection + 1, MasterNodePortCategory.Fragment, 0 );
  370. AddInputPort( WirePortDataType.FLOAT3, false, NormalStr, vertexCorrection + 0, MasterNodePortCategory.Fragment, 1 );
  371. m_normalPort = m_inputPorts[ m_inputPorts.Count - 1 ];
  372. AddInputPort( WirePortDataType.FLOAT3, false, EmissionStr, index++, MasterNodePortCategory.Fragment, 2 );
  373. AddInputPort( WirePortDataType.FLOAT, false, MetallicStr, index++, MasterNodePortCategory.Fragment, 3 );
  374. AddInputPort( WirePortDataType.FLOAT, false, SmoothnessStr, index++, MasterNodePortCategory.Fragment, 4 );
  375. AddInputPort( WirePortDataType.FLOAT, false, OcclusionLabelStr, OcclusionDataStr, index++, MasterNodePortCategory.Fragment, 5 );
  376. }
  377. break;
  378. case StandardShaderLightModel.StandardSpecular:
  379. {
  380. AddInputPort( WirePortDataType.FLOAT3, false, AlbedoStr, vertexCorrection + 1, MasterNodePortCategory.Fragment, 0 );
  381. AddInputPort( WirePortDataType.FLOAT3, false, NormalStr, vertexCorrection + 0, MasterNodePortCategory.Fragment, 1 );
  382. m_normalPort = m_inputPorts[ m_inputPorts.Count - 1 ];
  383. AddInputPort( WirePortDataType.FLOAT3, false, EmissionStr, index++, MasterNodePortCategory.Fragment, 2 );
  384. AddInputPort( WirePortDataType.FLOAT3, false, SpecularStr, index++, MasterNodePortCategory.Fragment, 3 );
  385. AddInputPort( WirePortDataType.FLOAT, false, SmoothnessStr, index++, MasterNodePortCategory.Fragment, 4 );
  386. AddInputPort( WirePortDataType.FLOAT, false, OcclusionLabelStr, OcclusionDataStr, index++, MasterNodePortCategory.Fragment, 5 );
  387. }
  388. break;
  389. case StandardShaderLightModel.CustomLighting:
  390. {
  391. AddInputPort( WirePortDataType.FLOAT3, false, AlbedoStr, vertexCorrection + 1, MasterNodePortCategory.Fragment, 0 );
  392. AddInputPort( WirePortDataType.FLOAT3, false, NormalStr, vertexCorrection + 0, MasterNodePortCategory.Fragment, 1 );
  393. m_normalPort = m_inputPorts[ m_inputPorts.Count - 1 ];
  394. m_inputPorts[ m_inputPorts.Count - 1 ].Locked = true;
  395. AddInputPort( WirePortDataType.FLOAT3, false, EmissionStr, index++, MasterNodePortCategory.Fragment, 2 );
  396. AddInputPort( WirePortDataType.FLOAT, false, SpecularStr, index++, MasterNodePortCategory.Fragment, 3 );
  397. m_inputPorts[ m_inputPorts.Count - 1 ].Locked = true;
  398. AddInputPort( WirePortDataType.FLOAT, false, GlossStr, index++, MasterNodePortCategory.Fragment, 4 );
  399. m_inputPorts[ m_inputPorts.Count - 1 ].Locked = true;
  400. }
  401. break;
  402. case StandardShaderLightModel.Unlit:
  403. {
  404. AddInputPort( WirePortDataType.FLOAT3, false, AlbedoStr, vertexCorrection + 1, MasterNodePortCategory.Fragment, 0 );
  405. m_inputPorts[ m_inputPorts.Count - 1 ].Locked = true;
  406. AddInputPort( WirePortDataType.FLOAT3, false, NormalStr, vertexCorrection + 0, MasterNodePortCategory.Fragment, 1 );
  407. m_normalPort = m_inputPorts[ m_inputPorts.Count - 1 ];
  408. m_inputPorts[ m_inputPorts.Count - 1 ].Locked = true;
  409. AddInputPort( WirePortDataType.FLOAT3, false, EmissionStr, index++, MasterNodePortCategory.Fragment, 2 );
  410. AddInputPort( WirePortDataType.FLOAT, false, SpecularStr, index++, MasterNodePortCategory.Fragment, 3 );
  411. m_inputPorts[ m_inputPorts.Count - 1 ].Locked = true;
  412. AddInputPort( WirePortDataType.FLOAT, false, GlossStr, index++, MasterNodePortCategory.Fragment, 4 );
  413. m_inputPorts[ m_inputPorts.Count - 1 ].Locked = true;
  414. }
  415. break;
  416. case StandardShaderLightModel.Lambert:
  417. {
  418. AddInputPort( WirePortDataType.FLOAT3, false, AlbedoStr, vertexCorrection + 1, MasterNodePortCategory.Fragment, 0 );
  419. AddInputPort( WirePortDataType.FLOAT3, false, NormalStr, vertexCorrection + 0, MasterNodePortCategory.Fragment, 1 );
  420. m_normalPort = m_inputPorts[ m_inputPorts.Count - 1 ];
  421. AddInputPort( WirePortDataType.FLOAT3, false, EmissionStr, index++, MasterNodePortCategory.Fragment, 2 );
  422. AddInputPort( WirePortDataType.FLOAT, false, SpecularStr, index++, MasterNodePortCategory.Fragment, 3 );
  423. AddInputPort( WirePortDataType.FLOAT, false, GlossStr, index++, MasterNodePortCategory.Fragment, 4 );
  424. }
  425. break;
  426. case StandardShaderLightModel.BlinnPhong:
  427. {
  428. AddInputPort( WirePortDataType.FLOAT3, false, AlbedoStr, vertexCorrection + 1, MasterNodePortCategory.Fragment, 0 );
  429. AddInputPort( WirePortDataType.FLOAT3, false, NormalStr, vertexCorrection + 0, MasterNodePortCategory.Fragment, 1 );
  430. m_normalPort = m_inputPorts[ m_inputPorts.Count - 1 ];
  431. AddInputPort( WirePortDataType.FLOAT3, false, EmissionStr, index++, MasterNodePortCategory.Fragment, 2 );
  432. AddInputPort( WirePortDataType.FLOAT, false, SpecularStr, index++, MasterNodePortCategory.Fragment, 3 );
  433. AddInputPort( WirePortDataType.FLOAT, false, GlossStr, index++, MasterNodePortCategory.Fragment, 4 );
  434. }
  435. break;
  436. }
  437. // instead of setting in the switch emission port is always at position 2;
  438. m_emissionPortId = 2;
  439. AddInputPort( WirePortDataType.FLOAT3, false, TransmissionStr, index++, MasterNodePortCategory.Fragment, 6 );
  440. m_transmissionPort = m_inputPorts[ m_inputPorts.Count - 1 ];
  441. m_inputPorts[ m_inputPorts.Count - 1 ].Locked = ( m_currentLightModel == StandardShaderLightModel.Standard ) || ( m_currentLightModel == StandardShaderLightModel.StandardSpecular ) ? false : true;
  442. AddInputPort( WirePortDataType.FLOAT3, false, TranslucencyStr, index++, MasterNodePortCategory.Fragment, 7 );
  443. m_translucencyPort = m_inputPorts[ m_inputPorts.Count - 1 ];
  444. m_inputPorts[ m_inputPorts.Count - 1 ].Locked = ( m_currentLightModel == StandardShaderLightModel.Standard ) || ( m_currentLightModel == StandardShaderLightModel.StandardSpecular ) ? false : true;
  445. AddInputPort( WirePortDataType.FLOAT, false, RefractionStr, index + 2, MasterNodePortCategory.Fragment, 8 );
  446. m_refractionPort = m_inputPorts[ m_inputPorts.Count - 1 ];
  447. m_inputPorts[ m_inputPorts.Count - 1 ].Locked = ( m_alphaMode == AlphaMode.Opaque || m_alphaMode == AlphaMode.Masked || m_currentLightModel == StandardShaderLightModel.Unlit || m_currentLightModel == StandardShaderLightModel.CustomLighting );
  448. AddInputPort( WirePortDataType.FLOAT, false, AlphaStr, index++, MasterNodePortCategory.Fragment, 9 );
  449. m_inputPorts[ m_inputPorts.Count - 1 ].DataName = AlphaDataStr;
  450. m_opacityPortId = m_inputPorts.Count - 1;
  451. m_inputPorts[ m_inputPorts.Count - 1 ].Locked = ( m_alphaMode == AlphaMode.Opaque || m_alphaMode == AlphaMode.Masked );
  452. AddInputPort( WirePortDataType.FLOAT, false, DiscardStr, index++, MasterNodePortCategory.Fragment, 10 );
  453. m_inputPorts[ m_inputPorts.Count - 1 ].Locked = ( m_alphaMode != AlphaMode.Masked && m_alphaMode != AlphaMode.Custom );
  454. m_discardPortId = m_inputPorts.Count - 1;
  455. // This is done to take the index + 2 from refraction port into account and not overlap indexes
  456. index++;
  457. AddInputPort( WirePortDataType.FLOAT3, false, CustomLightingStr, index++, MasterNodePortCategory.Fragment, 13 );
  458. m_inputPorts[ m_inputPorts.Count - 1 ].Locked = ( m_currentLightModel != StandardShaderLightModel.CustomLighting );
  459. m_inputPorts[ m_inputPorts.Count - 1 ].GenType = PortGenType.CustomLighting;
  460. m_customLightingPortId = m_inputPorts.Count - 1;
  461. ////////////////////////////////////////////////////////////////////////////////////////////////
  462. // Vertex functions - Adding ordex index in order to force these to be the last ones
  463. // Well now they have been moved to be the first ones so operations on vertex are to be taken into account
  464. // by dither, screen position and similar nodes
  465. ////////////////////////////////////////////////////////////////////////////////////////////////
  466. m_vertexPortId = m_inputPorts.Count;
  467. m_tessOpHelper.VertexOffsetIndexPort = m_vertexPortId;
  468. AddInputPort( WirePortDataType.FLOAT3, false, ( m_vertexMode == VertexMode.Relative ? VertexDisplacementStr : VertexPositionStr ), VertexDataStr, 0/*index++*/, MasterNodePortCategory.Vertex, 11 );
  469. AddInputPort( WirePortDataType.FLOAT3, false, VertexNormalStr, 1/*index++*/, MasterNodePortCategory.Vertex, 12 );
  470. //AddInputPort( WirePortDataType.FLOAT3, false, CustomLightModelStr, index++, MasterNodePortCategory.Fragment, 13 );
  471. //m_inputPorts[ m_inputPorts.Count - 1 ].Locked = true;// !(m_currentLightModel == StandardShaderLightModel.CustomLighting);
  472. AddInputPort( WirePortDataType.FLOAT4, false, TessellationOpHelper.TessellationPortStr, index++, MasterNodePortCategory.Tessellation, 14 );
  473. m_tessellationPort = m_inputPorts[ m_inputPorts.Count - 1 ];
  474. m_tessOpHelper.MasterNodeIndexPort = m_tessellationPort.PortId;
  475. ////////////////////////////////////////////////////////////////////////////////////
  476. AddInputPort( WirePortDataType.FLOAT3, false, DebugStr, index++, MasterNodePortCategory.Debug, 15 );
  477. for( int i = 0; i < m_inputPorts.Count; i++ )
  478. {
  479. m_inputPorts[ i ].CustomColor = Color.white;
  480. }
  481. m_sizeIsDirty = true;
  482. }
  483. public override void ForcePortType()
  484. {
  485. int portId = 0;
  486. switch( m_currentLightModel )
  487. {
  488. case StandardShaderLightModel.Standard:
  489. {
  490. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  491. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  492. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  493. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT, false );
  494. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT, false );
  495. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT, false );
  496. }
  497. break;
  498. case StandardShaderLightModel.StandardSpecular:
  499. {
  500. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  501. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  502. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  503. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  504. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT, false );
  505. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT, false );
  506. }
  507. break;
  508. case StandardShaderLightModel.CustomLighting:
  509. {
  510. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  511. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  512. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  513. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  514. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT, false );
  515. }
  516. break;
  517. case StandardShaderLightModel.Unlit:
  518. case StandardShaderLightModel.Lambert:
  519. {
  520. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  521. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  522. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  523. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT, false );
  524. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT, false );
  525. }
  526. break;
  527. case StandardShaderLightModel.BlinnPhong:
  528. {
  529. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  530. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  531. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  532. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT, false );
  533. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT, false );
  534. }
  535. break;
  536. }
  537. //Transmission
  538. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  539. //Translucency
  540. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  541. //Refraction
  542. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT, false );
  543. //Alpha
  544. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT, false );
  545. //Discard
  546. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT, false );
  547. //Custom Lighting
  548. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  549. //Vertex Offset
  550. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  551. //Vertex Normal
  552. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  553. //Tessellation
  554. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT4, false );
  555. //Debug
  556. m_inputPorts[ portId++ ].ChangeType( WirePortDataType.FLOAT3, false );
  557. }
  558. public override void SetName( string name )
  559. {
  560. ShaderName = name;
  561. }
  562. public void DrawInspectorProperty()
  563. {
  564. if( m_inspectorDefaultStyle == null )
  565. {
  566. m_inspectorDefaultStyle = UIUtils.GetCustomStyle( CustomStyle.ResetToDefaultInspectorButton );
  567. }
  568. DrawCustomInspector();
  569. }
  570. private void RecursiveLog()
  571. {
  572. List<PropertyNode> nodes = UIUtils.PropertyNodesList();
  573. nodes.Sort( ( x, y ) => { return x.OrderIndex.CompareTo( y.OrderIndex ); } );
  574. for( int i = 0; i < nodes.Count; i++ )
  575. {
  576. if( ( nodes[ i ] is ReordenatorNode ) )
  577. ( nodes[ i ] as ReordenatorNode ).RecursiveLog();
  578. else
  579. Debug.Log( nodes[ i ].OrderIndex + " " + nodes[ i ].PropertyName );
  580. }
  581. }
  582. public void DrawGeneralOptions()
  583. {
  584. DrawShaderName();
  585. DrawCurrentShaderType();
  586. EditorGUI.BeginChangeCheck();
  587. m_currentLightModel = (StandardShaderLightModel)EditorGUILayoutEnumPopup( LightModelContent, m_currentLightModel );
  588. if( EditorGUI.EndChangeCheck() )
  589. {
  590. ContainerGraph.ChangedLightingModel = true;
  591. if( m_currentLightModel == StandardShaderLightModel.CustomLighting )
  592. {
  593. ContainerGraph.ParentWindow.CurrentNodeAvailability = NodeAvailability.CustomLighting;
  594. //ContainerGraph.CurrentCanvasMode = NodeAvailability.CustomLighting;
  595. }
  596. else
  597. {
  598. ContainerGraph.ParentWindow.CurrentNodeAvailability = NodeAvailability.SurfaceShader;
  599. //ContainerGraph.CurrentCanvasMode = NodeAvailability.SurfaceShader;
  600. }
  601. }
  602. m_shaderModelIdx = EditorGUILayoutPopup( ShaderModelStr, m_shaderModelIdx, ShaderModelTypeArr );
  603. EditorGUI.BeginChangeCheck();
  604. DrawPrecisionProperty();
  605. if( EditorGUI.EndChangeCheck() )
  606. ContainerGraph.CurrentPrecision = m_currentPrecisionType;
  607. //m_cullMode = (CullMode)EditorGUILayoutEnumPopup( CullModeContent, m_cullMode );
  608. UndoParentNode inst = this;
  609. m_inlineCullMode.CustomDrawer( ref inst, ( x ) => { m_cullMode = (CullMode)EditorGUILayoutEnumPopup( CullModeContent, m_cullMode ); }, CullModeContent.text );
  610. //m_inlineCullMode.Value = (int)m_cullMode;
  611. //m_inlineCullMode.EnumTypePopup( ref inst, CullModeContent.text, Enum.GetNames( typeof( CullMode ) ) );
  612. //m_cullMode = (CullMode) m_inlineCullMode.Value;
  613. m_renderPath = (RenderPath)EditorGUILayoutEnumPopup( RenderPathContent, m_renderPath );
  614. m_castShadows = EditorGUILayoutToggle( CastShadowsContent, m_castShadows );
  615. m_receiveShadows = EditorGUILayoutToggle( ReceiveShadowsContent, m_receiveShadows );
  616. m_queueOrder = EditorGUILayoutIntField( QueueIndexContent, m_queueOrder );
  617. EditorGUI.BeginChangeCheck();
  618. m_vertexMode = (VertexMode)EditorGUILayoutEnumPopup( VertexModeStr, m_vertexMode );
  619. if( EditorGUI.EndChangeCheck() )
  620. {
  621. m_inputPorts[ m_vertexPortId ].Name = m_vertexMode == VertexMode.Relative ? VertexDisplacementStr : VertexPositionStr;
  622. m_sizeIsDirty = true;
  623. }
  624. m_shaderLOD = Mathf.Clamp( EditorGUILayoutIntField( ShaderLODContent, m_shaderLOD ), 0, Shader.globalMaximumLOD );
  625. ////m_lodCrossfade = EditorGUILayoutToggle( LODCrossfadeContent, m_lodCrossfade );
  626. m_fallbackHelper.Draw( this );
  627. DrawInspectorProperty();
  628. }
  629. public void ShowOpacityMaskValueUI()
  630. {
  631. EditorGUI.BeginChangeCheck();
  632. UndoParentNode inst = this;
  633. m_inlineOpacityMaskClipValue.CustomDrawer( ref inst, ( x ) => { m_opacityMaskClipValue = EditorGUILayoutFloatField( OpacityMaskClipValueContent, m_opacityMaskClipValue ); }, OpacityMaskClipValueContent.text );
  634. if( EditorGUI.EndChangeCheck() )
  635. {
  636. m_checkChanges = true;
  637. if( m_currentMaterial != null && m_currentMaterial.HasProperty( IOUtils.MaskClipValueName ) )
  638. {
  639. m_currentMaterial.SetFloat( IOUtils.MaskClipValueName, m_opacityMaskClipValue );
  640. }
  641. }
  642. }
  643. public override void DrawProperties()
  644. {
  645. if( m_inspectorFoldoutStyle == null || EditorGUIUtility.isProSkin != m_usingProSkin )
  646. m_inspectorFoldoutStyle = new GUIStyle( GUI.skin.GetStyle( "foldout" ) );
  647. if( m_inspectorToolbarStyle == null || EditorGUIUtility.isProSkin != m_usingProSkin )
  648. {
  649. m_inspectorToolbarStyle = new GUIStyle( GUI.skin.GetStyle( "toolbarbutton" ) )
  650. {
  651. fixedHeight = 20
  652. };
  653. }
  654. if( m_inspectorTooldropdownStyle == null || EditorGUIUtility.isProSkin != m_usingProSkin )
  655. {
  656. m_inspectorTooldropdownStyle = new GUIStyle( GUI.skin.GetStyle( "toolbardropdown" ) )
  657. {
  658. fixedHeight = 20
  659. };
  660. m_inspectorTooldropdownStyle.margin.bottom = 2;
  661. }
  662. if( EditorGUIUtility.isProSkin != m_usingProSkin )
  663. m_usingProSkin = EditorGUIUtility.isProSkin;
  664. base.DrawProperties();
  665. EditorGUILayout.BeginVertical();
  666. {
  667. EditorGUILayout.Separator();
  668. m_titleOpacity = 0.5f;
  669. m_boxOpacity = ( EditorGUIUtility.isProSkin ? 0.5f : 0.25f );
  670. m_cachedColor = GUI.color;
  671. // General
  672. bool generalIsVisible = ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedGeneralShaderOptions;
  673. NodeUtils.DrawPropertyGroup( ref generalIsVisible, GeneralFoldoutStr, DrawGeneralOptions );
  674. ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedGeneralShaderOptions = generalIsVisible;
  675. //Blend Mode
  676. GUI.color = new Color( m_cachedColor.r, m_cachedColor.g, m_cachedColor.b, m_titleOpacity );
  677. EditorGUILayout.BeginHorizontal( m_inspectorToolbarStyle );
  678. GUI.color = m_cachedColor;
  679. bool blendOptionsVisible = GUILayout.Toggle( ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedBlendOptions, AlphaModeContent, UIUtils.MenuItemToggleStyle, GUILayout.ExpandWidth( true ) );
  680. if( Event.current.button == Constants.FoldoutMouseId )
  681. {
  682. ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedBlendOptions = blendOptionsVisible;
  683. }
  684. if( !EditorGUIUtility.isProSkin )
  685. GUI.color = new Color( 0.25f, 0.25f, 0.25f, 1f );
  686. float boxSize = 60;
  687. switch( m_alphaMode )
  688. {
  689. case AlphaMode.Transparent:
  690. boxSize = 85;
  691. break;
  692. case AlphaMode.Translucent:
  693. boxSize = 80;
  694. break;
  695. case AlphaMode.Premultiply:
  696. boxSize = 120;
  697. break;
  698. }
  699. EditorGUI.BeginChangeCheck();
  700. m_alphaMode = (AlphaMode)EditorGUILayoutPopup( string.Empty, (int)m_alphaMode, FadeModeOptions, UIUtils.InspectorPopdropdownStyle, GUILayout.Width( boxSize ), GUILayout.Height( 19 ) );
  701. if( EditorGUI.EndChangeCheck() )
  702. {
  703. UpdateFromBlendMode();
  704. }
  705. GUI.color = m_cachedColor;
  706. EditorGUILayout.EndHorizontal();
  707. m_customBlendAvailable = ( m_alphaMode == AlphaMode.Custom || m_alphaMode == AlphaMode.Opaque );
  708. if( ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedBlendOptions )
  709. {
  710. GUI.color = new Color( m_cachedColor.r, m_cachedColor.g, m_cachedColor.b, m_boxOpacity );
  711. EditorGUILayout.BeginVertical( UIUtils.MenuItemBackgroundStyle );
  712. GUI.color = m_cachedColor;
  713. EditorGUI.indentLevel++;
  714. EditorGUILayout.Separator();
  715. EditorGUI.BeginChangeCheck();
  716. m_renderType = (RenderType)EditorGUILayoutEnumPopup( RenderTypeContent, m_renderType );
  717. if( m_renderType == RenderType.Custom )
  718. {
  719. EditorGUI.BeginChangeCheck();
  720. m_customRenderType = EditorGUILayoutTextField( CustomRenderTypeStr, m_customRenderType );
  721. if( EditorGUI.EndChangeCheck() )
  722. {
  723. m_customRenderType = UIUtils.RemoveInvalidCharacters( m_customRenderType );
  724. }
  725. }
  726. m_renderQueue = (RenderQueue)EditorGUILayoutEnumPopup( RenderQueueContent, m_renderQueue );
  727. if( EditorGUI.EndChangeCheck() )
  728. {
  729. if( m_renderType == RenderType.Opaque && m_renderQueue == RenderQueue.Geometry )
  730. m_alphaMode = AlphaMode.Opaque;
  731. else if( m_renderType == RenderType.TransparentCutout && m_renderQueue == RenderQueue.AlphaTest )
  732. m_alphaMode = AlphaMode.Masked;
  733. else if( m_renderType == RenderType.Transparent && m_renderQueue == RenderQueue.Transparent )
  734. m_alphaMode = AlphaMode.Transparent;
  735. else if( m_renderType == RenderType.Opaque && m_renderQueue == RenderQueue.Transparent )
  736. m_alphaMode = AlphaMode.Translucent;
  737. else
  738. m_alphaMode = AlphaMode.Custom;
  739. UpdateFromBlendMode();
  740. }
  741. bool bufferedEnabled = GUI.enabled;
  742. GUI.enabled = ( m_alphaMode == AlphaMode.Masked || m_alphaMode == AlphaMode.Custom );
  743. m_inputPorts[ m_discardPortId ].Locked = !GUI.enabled;
  744. ShowOpacityMaskValueUI();
  745. GUI.enabled = bufferedEnabled;
  746. EditorGUI.BeginDisabledGroup( !( m_alphaMode == AlphaMode.Transparent || m_alphaMode == AlphaMode.Premultiply || m_alphaMode == AlphaMode.Translucent || m_alphaMode == AlphaMode.Custom ) );
  747. m_grabOrder = EditorGUILayoutIntField( RefractionLayerStr, m_grabOrder );
  748. float cachedLabelWidth = EditorGUIUtility.labelWidth;
  749. EditorGUIUtility.labelWidth = 130;
  750. m_alphaToCoverage = EditorGUILayoutToggle( AlphaToCoverageStr, m_alphaToCoverage );
  751. EditorGUIUtility.labelWidth = cachedLabelWidth;
  752. EditorGUI.EndDisabledGroup();
  753. EditorGUILayout.Separator();
  754. if( !m_customBlendAvailable )
  755. {
  756. EditorGUILayout.HelpBox( "Advanced options are only available for Custom blend modes", MessageType.Warning );
  757. }
  758. EditorGUI.BeginDisabledGroup( !m_customBlendAvailable );
  759. m_blendOpsHelper.Draw( this, m_customBlendAvailable );
  760. m_colorMaskHelper.Draw( this );
  761. EditorGUI.EndDisabledGroup();
  762. EditorGUILayout.Separator();
  763. EditorGUI.indentLevel--;
  764. EditorGUILayout.EndVertical();
  765. }
  766. m_stencilBufferHelper.Draw( this );
  767. m_tessOpHelper.Draw( this, m_inspectorToolbarStyle, m_currentMaterial, m_tessellationPort.IsConnected );
  768. m_outlineHelper.Draw( this, m_inspectorToolbarStyle, m_currentMaterial );
  769. m_billboardOpHelper.Draw( this );
  770. m_zBufferHelper.Draw( this, m_inspectorToolbarStyle, m_customBlendAvailable );
  771. m_renderingOptionsOpHelper.Draw( this );
  772. m_renderingPlatformOpHelper.Draw( this );
  773. //m_additionalDefines.Draw( this );
  774. //m_additionalIncludes.Draw( this );
  775. //m_additionalPragmas.Draw( this );
  776. m_additionalSurfaceOptions.Draw( this );
  777. m_usePass.Draw( this );
  778. m_additionalDirectives.Draw( this );
  779. m_customTagsHelper.Draw( this );
  780. m_dependenciesHelper.Draw( this );
  781. DrawMaterialInputs( m_inspectorToolbarStyle );
  782. }
  783. EditorGUILayout.EndVertical();
  784. }
  785. public override void OnNodeLogicUpdate( DrawInfo drawInfo )
  786. {
  787. base.OnNodeLogicUpdate( drawInfo );
  788. if( m_initialize )
  789. {
  790. m_initialize = false;
  791. if( m_dummyProperty == null )
  792. {
  793. m_dummyProperty = ScriptableObject.CreateInstance<PropertyNode>();
  794. m_dummyProperty.ContainerGraph = ContainerGraph;
  795. }
  796. }
  797. if( m_currentLightModel != m_lastLightModel )
  798. m_lightModelChanged = true;
  799. if( m_lightModelChanged )
  800. {
  801. m_lightModelChanged = false;
  802. if( m_currentLightModel == StandardShaderLightModel.BlinnPhong )
  803. {
  804. if( m_specColorReorder == null )
  805. {
  806. m_specColorReorder = ScriptableObject.CreateInstance<ReordenatorNode>();
  807. m_specColorReorder.ContainerGraph = ContainerGraph;
  808. m_specColorReorder.OrderIndex = m_specColorOrderIndex;
  809. m_specColorReorder.Init( "_SpecColor", "Specular Color", null );
  810. }
  811. UIUtils.RegisterPropertyNode( m_specColorReorder );
  812. }
  813. else
  814. {
  815. if( m_specColorReorder != null )
  816. UIUtils.UnregisterPropertyNode( m_specColorReorder );
  817. }
  818. if( m_currentLightModel == StandardShaderLightModel.CustomLighting && m_masterNodeCategory == 0 )
  819. ContainerGraph.CurrentCanvasMode = NodeAvailability.CustomLighting;
  820. else if( m_masterNodeCategory == 0 )
  821. ContainerGraph.CurrentCanvasMode = NodeAvailability.SurfaceShader;
  822. CacheCurrentSettings();
  823. m_lastLightModel = m_currentLightModel;
  824. DeleteAllInputConnections( true, true );
  825. AddMasterPorts();
  826. ConnectFromCache();
  827. }
  828. if( drawInfo.CurrentEventType != EventType.Layout )
  829. return;
  830. if( m_transmissionPort != null && m_transmissionPort.IsConnected && m_renderPath != RenderPath.ForwardOnly )
  831. {
  832. m_renderPath = RenderPath.ForwardOnly;
  833. UIUtils.ShowMessage( "Render Path changed to Forward Only since transmission only works in forward rendering" );
  834. }
  835. if( m_translucencyPort != null && m_translucencyPort.IsConnected && m_renderPath != RenderPath.ForwardOnly )
  836. {
  837. m_renderPath = RenderPath.ForwardOnly;
  838. UIUtils.ShowMessage( "Render Path changed to Forward Only since translucency only works in forward rendering" );
  839. }
  840. if( m_translucencyPort.IsConnected != m_previousTranslucencyOn )
  841. m_checkChanges = true;
  842. if( m_refractionPort.IsConnected != m_previousRefractionOn )
  843. m_checkChanges = true;
  844. if( ( m_tessOpHelper.EnableTesselation && !m_tessellationPort.IsConnected ) != m_previousTessellationOn )
  845. m_checkChanges = true;
  846. m_previousTranslucencyOn = m_translucencyPort.IsConnected;
  847. m_previousRefractionOn = m_refractionPort.IsConnected;
  848. m_previousTessellationOn = ( m_tessOpHelper.EnableTesselation && !m_tessellationPort.IsConnected );
  849. if( m_checkChanges )
  850. {
  851. if( m_translucencyPort.IsConnected )
  852. {
  853. if( m_translucencyReorder == null )
  854. {
  855. List<PropertyNode> translucencyList = new List<PropertyNode>();
  856. for( int i = 0; i < 7; i++ )
  857. {
  858. translucencyList.Add( m_dummyProperty );
  859. }
  860. m_translucencyReorder = ScriptableObject.CreateInstance<ReordenatorNode>();
  861. m_translucencyReorder.ContainerGraph = ContainerGraph;
  862. m_translucencyReorder.OrderIndex = m_translucencyOrderIndex;
  863. m_translucencyReorder.Init( "_TranslucencyGroup", "Translucency", translucencyList );
  864. }
  865. UIUtils.RegisterPropertyNode( m_translucencyReorder );
  866. }
  867. else
  868. {
  869. if( m_translucencyReorder != null )
  870. UIUtils.UnregisterPropertyNode( m_translucencyReorder );
  871. }
  872. if( m_refractionPort.IsConnected )
  873. {
  874. if( m_refractionReorder == null )
  875. {
  876. List<PropertyNode> refractionList = new List<PropertyNode>();
  877. for( int i = 0; i < 2; i++ )
  878. {
  879. refractionList.Add( m_dummyProperty );
  880. }
  881. m_refractionReorder = ScriptableObject.CreateInstance<ReordenatorNode>();
  882. m_refractionReorder.ContainerGraph = ContainerGraph;
  883. m_refractionReorder.OrderIndex = m_refractionOrderIndex;
  884. m_refractionReorder.Init( "_RefractionGroup", "Refraction", refractionList );
  885. }
  886. UIUtils.RegisterPropertyNode( m_refractionReorder );
  887. }
  888. else
  889. {
  890. if( m_refractionReorder != null )
  891. UIUtils.UnregisterPropertyNode( m_refractionReorder );
  892. }
  893. if( m_tessOpHelper.EnableTesselation && !m_tessellationPort.IsConnected )
  894. {
  895. if( m_tessellationReorder == null )
  896. {
  897. List<PropertyNode> tessellationList = new List<PropertyNode>();
  898. for( int i = 0; i < 4; i++ )
  899. {
  900. tessellationList.Add( m_dummyProperty );
  901. }
  902. m_tessellationReorder = ScriptableObject.CreateInstance<ReordenatorNode>();
  903. m_tessellationReorder.ContainerGraph = ContainerGraph;
  904. m_tessellationReorder.OrderIndex = m_tessellationOrderIndex;
  905. m_tessellationReorder.Init( "_TessellationGroup", "Tessellation", tessellationList );
  906. m_tessellationReorder.HeaderTitle = "Tesselation";
  907. }
  908. UIUtils.RegisterPropertyNode( m_tessellationReorder );
  909. }
  910. else
  911. {
  912. if( m_tessellationReorder != null )
  913. UIUtils.UnregisterPropertyNode( m_tessellationReorder );
  914. }
  915. if( m_inputPorts[ m_discardPortId ].Available && !m_inlineOpacityMaskClipValue.IsValid )
  916. {
  917. if( m_maskClipReorder == null )
  918. {
  919. // Create dragable clip material property
  920. m_maskClipReorder = ScriptableObject.CreateInstance<ReordenatorNode>();
  921. m_maskClipReorder.ContainerGraph = ContainerGraph;
  922. m_maskClipReorder.OrderIndex = m_maskClipOrderIndex;
  923. m_maskClipReorder.Init( "_Cutoff", "Mask Clip Value", null );
  924. }
  925. UIUtils.RegisterPropertyNode( m_maskClipReorder );
  926. }
  927. else
  928. {
  929. if( m_maskClipReorder != null )
  930. UIUtils.UnregisterPropertyNode( m_maskClipReorder );
  931. }
  932. m_checkChanges = false;
  933. }
  934. }
  935. public override void OnNodeRepaint( DrawInfo drawInfo )
  936. {
  937. base.OnNodeRepaint( drawInfo );
  938. if( m_containerGraph.IsInstancedShader || m_renderingOptionsOpHelper.ForceEnableInstancing )
  939. {
  940. DrawInstancedIcon( drawInfo );
  941. }
  942. }
  943. private void CacheCurrentSettings()
  944. {
  945. m_cacheNodeConnections.Clear();
  946. for( int portId = 0; portId < m_inputPorts.Count; portId++ )
  947. {
  948. if( m_inputPorts[ portId ].IsConnected )
  949. {
  950. WireReference connection = m_inputPorts[ portId ].GetConnection();
  951. m_cacheNodeConnections.Add( m_inputPorts[ portId ].Name, new NodeCache( connection.NodeId, connection.PortId ) );
  952. }
  953. }
  954. }
  955. private void ConnectFromCache()
  956. {
  957. for( int i = 0; i < m_inputPorts.Count; i++ )
  958. {
  959. NodeCache cache = m_cacheNodeConnections.Get( m_inputPorts[ i ].Name );
  960. if( cache != null )
  961. {
  962. UIUtils.SetConnection( UniqueId, m_inputPorts[ i ].PortId, cache.TargetNodeId, cache.TargetPortId );
  963. }
  964. }
  965. }
  966. public override void UpdateMaterial( Material mat )
  967. {
  968. base.UpdateMaterial( mat );
  969. if( m_alphaMode == AlphaMode.Masked || m_alphaMode == AlphaMode.Custom )
  970. {
  971. if( mat.HasProperty( IOUtils.MaskClipValueName ) )
  972. mat.SetFloat( IOUtils.MaskClipValueName, m_opacityMaskClipValue );
  973. }
  974. }
  975. public override void SetMaterialMode( Material mat, bool fetchMaterialValues )
  976. {
  977. base.SetMaterialMode( mat, fetchMaterialValues );
  978. if( m_alphaMode == AlphaMode.Masked || m_alphaMode == AlphaMode.Custom )
  979. {
  980. if( fetchMaterialValues && m_materialMode && mat.HasProperty( IOUtils.MaskClipValueName ) )
  981. {
  982. m_opacityMaskClipValue = mat.GetFloat( IOUtils.MaskClipValueName );
  983. }
  984. }
  985. }
  986. public override void ForceUpdateFromMaterial( Material material )
  987. {
  988. m_tessOpHelper.UpdateFromMaterial( material );
  989. m_outlineHelper.UpdateFromMaterial( material );
  990. if( m_alphaMode == AlphaMode.Masked || m_alphaMode == AlphaMode.Custom )
  991. {
  992. if( material.HasProperty( IOUtils.MaskClipValueName ) )
  993. m_opacityMaskClipValue = material.GetFloat( IOUtils.MaskClipValueName );
  994. }
  995. }
  996. public override void UpdateMasterNodeMaterial( Material material )
  997. {
  998. m_currentMaterial = material;
  999. UpdateMaterialEditor();
  1000. }
  1001. void UpdateMaterialEditor()
  1002. {
  1003. FireMaterialChangedEvt();
  1004. }
  1005. public string CreateInstructionsForVertexPort( InputPort port )
  1006. {
  1007. //Vertex displacement and per vertex custom data
  1008. WireReference connection = port.GetConnection();
  1009. ParentNode node = UIUtils.GetNode( connection.NodeId );
  1010. string vertexInstructions = node.GetValueFromOutputStr( connection.PortId, port.DataType, ref m_currentDataCollector, false );
  1011. if( m_currentDataCollector.DirtySpecialLocalVariables )
  1012. {
  1013. m_currentDataCollector.AddVertexInstruction( m_currentDataCollector.SpecialLocalVariables, UniqueId, false );
  1014. m_currentDataCollector.ClearSpecialLocalVariables();
  1015. }
  1016. if( m_currentDataCollector.DirtyVertexVariables )
  1017. {
  1018. m_currentDataCollector.AddVertexInstruction( m_currentDataCollector.VertexLocalVariables, UniqueId, false );
  1019. m_currentDataCollector.ClearVertexLocalVariables();
  1020. }
  1021. return vertexInstructions;
  1022. }
  1023. public void CreateInstructionsForPort( InputPort port, string portName, bool addCustomDelimiters = false, string customDelimiterIn = null, string customDelimiterOut = null, bool ignoreLocalVar = false, bool normalIsConnected = false )
  1024. {
  1025. WireReference connection = port.GetConnection();
  1026. ParentNode node = UIUtils.GetNode( connection.NodeId );
  1027. string newInstruction = node.GetValueFromOutputStr( connection.PortId, port.DataType, ref m_currentDataCollector, ignoreLocalVar );
  1028. if( m_currentDataCollector.DirtySpecialLocalVariables )
  1029. {
  1030. m_currentDataCollector.AddInstructions( m_currentDataCollector.SpecialLocalVariables );
  1031. m_currentDataCollector.ClearSpecialLocalVariables();
  1032. }
  1033. if( m_currentDataCollector.DirtyVertexVariables )
  1034. {
  1035. m_currentDataCollector.AddVertexInstruction( m_currentDataCollector.VertexLocalVariables, port.NodeId, false );
  1036. m_currentDataCollector.ClearVertexLocalVariables();
  1037. }
  1038. if( m_currentDataCollector.ForceNormal && !normalIsConnected )
  1039. {
  1040. m_currentDataCollector.AddToStartInstructions( "\t\t\t" + Constants.OutputVarStr + ".Normal = float3(0,0,1);\n" );
  1041. m_currentDataCollector.DirtyNormal = true;
  1042. m_currentDataCollector.ForceNormal = false;
  1043. }
  1044. m_currentDataCollector.AddInstructions( addCustomDelimiters ? customDelimiterIn : ( "\t\t\t" + portName + " = " ) );
  1045. m_currentDataCollector.AddInstructions( newInstruction );
  1046. m_currentDataCollector.AddInstructions( addCustomDelimiters ? customDelimiterOut : ";\n" );
  1047. }
  1048. public string CreateInstructionStringForPort( InputPort port, bool ignoreLocalVar = false )
  1049. {
  1050. WireReference connection = port.GetConnection();
  1051. ParentNode node = UIUtils.GetNode( connection.NodeId );
  1052. string newInstruction = node.GetValueFromOutputStr( connection.PortId, port.DataType, ref m_currentDataCollector, ignoreLocalVar );
  1053. if( m_currentDataCollector.DirtySpecialLocalVariables )
  1054. {
  1055. m_currentDataCollector.AddInstructions( m_currentDataCollector.SpecialLocalVariables );
  1056. m_currentDataCollector.ClearSpecialLocalVariables();
  1057. }
  1058. if( m_currentDataCollector.DirtyVertexVariables )
  1059. {
  1060. m_currentDataCollector.AddVertexInstruction( m_currentDataCollector.VertexLocalVariables, port.NodeId, false );
  1061. m_currentDataCollector.ClearVertexLocalVariables();
  1062. }
  1063. if( m_currentDataCollector.ForceNormal )
  1064. {
  1065. m_currentDataCollector.AddToStartInstructions( "\t\t\t" + Constants.OutputVarStr + ".Normal = float3(0,0,1);\n" );
  1066. m_currentDataCollector.DirtyNormal = true;
  1067. m_currentDataCollector.ForceNormal = false;
  1068. }
  1069. return newInstruction;
  1070. }
  1071. public override Shader Execute( string pathname, bool isFullPath )
  1072. {
  1073. ForcePortType();
  1074. ForceReordering();
  1075. UpdateFromBlendMode();
  1076. base.Execute( pathname, isFullPath );
  1077. RegisterStandaloneFuntions();
  1078. bool isInstancedShader = m_renderingOptionsOpHelper.ForceEnableInstancing || UIUtils.IsInstancedShader();
  1079. bool hasVirtualTexture = UIUtils.HasVirtualTexture();
  1080. bool hasTranslucency = false;
  1081. bool hasTransmission = false;
  1082. bool hasEmission = false;
  1083. bool hasOpacity = false;
  1084. bool hasOpacityMask = false;
  1085. bool hasRefraction = false;
  1086. //bool hasVertexOffset = false;
  1087. //bool hasCustomLightingAlpha = false;
  1088. bool hasCustomLightingMask = false;
  1089. string customLightingCode = string.Empty;
  1090. string customLightingAlphaCode = string.Empty;
  1091. string customLightingMaskCode = string.Empty;
  1092. string customLightingInstructions = string.Empty;
  1093. string refractionCode = string.Empty;
  1094. string refractionInstructions = string.Empty;
  1095. string refractionFix = string.Empty;
  1096. string aboveUsePasses = string.Empty;
  1097. string bellowUsePasses = string.Empty;
  1098. m_usePass.BuildUsePassInfo( ref aboveUsePasses, ref bellowUsePasses, "\t\t" );
  1099. m_currentDataCollector.TesselationActive = m_tessOpHelper.EnableTesselation;
  1100. m_currentDataCollector.CurrentRenderPath = m_renderPath;
  1101. StandardShaderLightModel cachedLightModel = m_currentLightModel;
  1102. NodeAvailability cachedAvailability = ContainerGraph.CurrentCanvasMode;
  1103. bool debugIsUsingCustomLighting = false;
  1104. bool usingDebugPort = false;
  1105. if( m_inputPorts[ m_inputPorts.Count - 1 ].IsConnected )
  1106. {
  1107. usingDebugPort = true;
  1108. debugIsUsingCustomLighting = m_currentLightModel == StandardShaderLightModel.CustomLighting;
  1109. m_currentDataCollector.GenType = PortGenType.CustomLighting;
  1110. m_currentLightModel = StandardShaderLightModel.CustomLighting;
  1111. ContainerGraph.CurrentCanvasMode = NodeAvailability.CustomLighting;
  1112. }
  1113. if( isInstancedShader )
  1114. {
  1115. m_currentDataCollector.AddToPragmas( UniqueId, IOUtils.InstancedPropertiesHeader );
  1116. }
  1117. if( m_renderingOptionsOpHelper.SpecularHighlightToggle || m_renderingOptionsOpHelper.ReflectionsToggle )
  1118. m_currentDataCollector.AddToProperties( UniqueId, "[Header(Forward Rendering Options)]", 10001 );
  1119. if( m_renderingOptionsOpHelper.SpecularHighlightToggle )
  1120. {
  1121. m_currentDataCollector.AddToProperties( UniqueId, "[ToggleOff] _SpecularHighlights(\"Specular Highlights\", Float) = 1.0", 10002 );
  1122. m_currentDataCollector.AddToPragmas( UniqueId, "shader_feature _SPECULARHIGHLIGHTS_OFF" );
  1123. }
  1124. if( m_renderingOptionsOpHelper.ReflectionsToggle )
  1125. {
  1126. m_currentDataCollector.AddToProperties( UniqueId, "[ToggleOff] _GlossyReflections(\"Reflections\", Float) = 1.0", 10003 );
  1127. m_currentDataCollector.AddToPragmas( UniqueId, "shader_feature _GLOSSYREFLECTIONS_OFF" );
  1128. }
  1129. // See if each node is being used on frag and/or vert ports
  1130. SetupNodeCategories();
  1131. m_containerGraph.CheckPropertiesAutoRegister( ref m_currentDataCollector );
  1132. if( m_refractionPort.IsConnected || m_inputPorts[ m_inputPorts.Count - 1 ].IsConnected )
  1133. {
  1134. m_currentDataCollector.DirtyNormal = true;
  1135. m_currentDataCollector.ForceNormal = true;
  1136. }
  1137. //this.PropagateNodeData( nodeData );
  1138. string tags = "\"RenderType\" = \"{0}\" \"Queue\" = \"{1}\"";
  1139. string finalRenderType = ( m_renderType == RenderType.Custom && m_customRenderType.Length > 0 ) ? m_customRenderType : m_renderType.ToString();
  1140. tags = string.Format( tags, finalRenderType, ( m_renderQueue + ( ( m_queueOrder >= 0 ) ? "+" : string.Empty ) + m_queueOrder ) );
  1141. //if ( !m_customBlendMode )
  1142. {
  1143. if( m_alphaMode == AlphaMode.Transparent || m_alphaMode == AlphaMode.Premultiply )
  1144. {
  1145. //tags += " \"IgnoreProjector\" = \"True\"";
  1146. if( !m_renderingOptionsOpHelper.IgnoreProjectorValue )
  1147. {
  1148. Debug.Log( string.Format( "Setting Ignore Projector to True since it's requires by Blend Mode {0}.", m_alphaMode ) );
  1149. m_renderingOptionsOpHelper.IgnoreProjectorValue = true;
  1150. }
  1151. }
  1152. }
  1153. tags += m_renderingOptionsOpHelper.IgnoreProjectorTag;
  1154. tags += m_renderingOptionsOpHelper.ForceNoShadowCastingTag;
  1155. tags += m_renderingOptionsOpHelper.DisableBatchingTag;
  1156. //add virtual texture support
  1157. if( hasVirtualTexture )
  1158. {
  1159. tags += " \"Amplify\" = \"True\" ";
  1160. }
  1161. //tags = "Tags{ " + tags + " }";
  1162. string outputStruct = "";
  1163. switch( m_currentLightModel )
  1164. {
  1165. case StandardShaderLightModel.CustomLighting: outputStruct = "SurfaceOutputCustomLightingCustom"; break;
  1166. case StandardShaderLightModel.Standard: outputStruct = "SurfaceOutputStandard"; break;
  1167. case StandardShaderLightModel.StandardSpecular: outputStruct = "SurfaceOutputStandardSpecular"; break;
  1168. case StandardShaderLightModel.Unlit:
  1169. case StandardShaderLightModel.Lambert:
  1170. case StandardShaderLightModel.BlinnPhong: outputStruct = "SurfaceOutput"; break;
  1171. }
  1172. if( m_currentLightModel == StandardShaderLightModel.CustomLighting )
  1173. {
  1174. m_currentDataCollector.AddToIncludes( UniqueId, Constants.UnityPBSLightingLib );
  1175. m_currentDataCollector.ChangeCustomInputHeader( m_currentLightModel.ToString() + Constants.CustomLightStructStr );
  1176. m_currentDataCollector.AddToCustomInput( UniqueId, "half3 Albedo", true );
  1177. m_currentDataCollector.AddToCustomInput( UniqueId, "half3 Normal", true );
  1178. m_currentDataCollector.AddToCustomInput( UniqueId, "half3 Emission", true );
  1179. m_currentDataCollector.AddToCustomInput( UniqueId, "half Metallic", true );
  1180. m_currentDataCollector.AddToCustomInput( UniqueId, "half Smoothness", true );
  1181. m_currentDataCollector.AddToCustomInput( UniqueId, "half Occlusion", true );
  1182. m_currentDataCollector.AddToCustomInput( UniqueId, "half Alpha", true );
  1183. m_currentDataCollector.AddToCustomInput( UniqueId, "Input SurfInput", true );
  1184. m_currentDataCollector.AddToCustomInput( UniqueId, "UnityGIInput GIData", true );
  1185. }
  1186. // Need to sort before creating local vars so they can inspect the normal port correctly
  1187. SortedList<int, InputPort> sortedPorts = new SortedList<int, InputPort>();
  1188. for( int i = 0; i < m_inputPorts.Count; i++ )
  1189. {
  1190. sortedPorts.Add( m_inputPorts[ i ].OrderId, m_inputPorts[ i ] );
  1191. }
  1192. bool normalIsConnected = m_normalPort.IsConnected;
  1193. m_tessOpHelper.Reset();
  1194. if( m_inputPorts[ m_inputPorts.Count - 1 ].IsConnected )
  1195. {
  1196. //Debug Port active
  1197. InputPort debugPort = m_inputPorts[ m_inputPorts.Count - 1 ];
  1198. m_currentDataCollector.PortCategory = debugPort.Category;
  1199. if( debugIsUsingCustomLighting )
  1200. {
  1201. m_currentDataCollector.UsingCustomOutput = true;
  1202. WireReference connection = m_inputPorts[ m_inputPorts.Count - 1 ].GetConnection();
  1203. ParentNode node = UIUtils.GetNode( connection.NodeId );
  1204. customLightingCode = node.GetValueFromOutputStr( connection.PortId, WirePortDataType.FLOAT3, ref m_currentDataCollector, false );
  1205. customLightingInstructions = m_currentDataCollector.CustomOutput;
  1206. if( m_currentDataCollector.ForceNormal )
  1207. {
  1208. m_currentDataCollector.AddToStartInstructions( "\t\t\t" + Constants.OutputVarStr + ".Normal = float3(0,0,1);\n" );
  1209. m_currentDataCollector.DirtyNormal = true;
  1210. m_currentDataCollector.ForceNormal = false;
  1211. }
  1212. if( m_currentDataCollector.DirtyVertexVariables )
  1213. {
  1214. m_currentDataCollector.AddVertexInstruction( m_currentDataCollector.VertexLocalVariables, UniqueId, false );
  1215. m_currentDataCollector.ClearVertexLocalVariables();
  1216. }
  1217. m_currentDataCollector.UsingCustomOutput = false;
  1218. }
  1219. else
  1220. {
  1221. CreateInstructionsForPort( debugPort, Constants.OutputVarStr + ".Emission", false, null, null, false, false );
  1222. }
  1223. }
  1224. else
  1225. {
  1226. MasterNodePortCategory currentCategory = sortedPorts[ 0 ].Category;
  1227. //Collect data from standard nodes
  1228. for( int i = 0; i < sortedPorts.Count; i++ )
  1229. {
  1230. // prepare ports for custom lighting
  1231. m_currentDataCollector.GenType = sortedPorts[ i ].GenType;
  1232. if( m_currentLightModel == StandardShaderLightModel.CustomLighting && sortedPorts[ i ].Name.Equals( AlphaStr ) )
  1233. ContainerGraph.ResetNodesLocalVariablesIfNot( MasterNodePortCategory.Vertex );
  1234. if( sortedPorts[ i ].IsConnected )
  1235. {
  1236. m_currentDataCollector.PortCategory = sortedPorts[ i ].Category;
  1237. if( sortedPorts[ i ].Name.Equals( NormalStr ) )// Normal Map is Connected
  1238. {
  1239. m_currentDataCollector.DirtyNormal = true;
  1240. }
  1241. if( sortedPorts[ i ].Name.Equals( TranslucencyStr ) )
  1242. {
  1243. hasTranslucency = true;
  1244. }
  1245. if( sortedPorts[ i ].Name.Equals( TransmissionStr ) )
  1246. {
  1247. hasTransmission = true;
  1248. }
  1249. if( sortedPorts[ i ].Name.Equals( EmissionStr ) )
  1250. {
  1251. hasEmission = true;
  1252. }
  1253. if( sortedPorts[ i ].Name.Equals( RefractionStr ) )
  1254. {
  1255. hasRefraction = true;
  1256. }
  1257. if( sortedPorts[ i ].Name.Equals( AlphaStr ) )
  1258. {
  1259. hasOpacity = true;
  1260. }
  1261. if( sortedPorts[ i ].Name.Equals( DiscardStr ) )
  1262. {
  1263. hasOpacityMask = true;
  1264. }
  1265. if( hasRefraction )
  1266. {
  1267. m_currentDataCollector.AddToInput( UniqueId, SurfaceInputs.SCREEN_POS );
  1268. m_currentDataCollector.AddToInput( UniqueId, SurfaceInputs.WORLD_POS );
  1269. //not necessary, just being safe
  1270. m_currentDataCollector.DirtyNormal = true;
  1271. m_currentDataCollector.ForceNormal = true;
  1272. if( m_grabOrder != 0 )
  1273. {
  1274. m_currentDataCollector.AddGrabPass( "RefractionGrab" + m_grabOrder );
  1275. m_currentDataCollector.AddToUniforms( UniqueId, "uniform sampler2D RefractionGrab" + m_grabOrder + ";" );
  1276. }
  1277. else
  1278. {
  1279. m_currentDataCollector.AddGrabPass( "" );
  1280. m_currentDataCollector.AddToUniforms( UniqueId, "uniform sampler2D _GrabTexture;" );
  1281. }
  1282. m_currentDataCollector.AddToUniforms( UniqueId, "uniform float _ChromaticAberration;" );
  1283. m_currentDataCollector.AddToProperties( UniqueId, "[Header(Refraction)]", m_refractionReorder.OrderIndex );
  1284. m_currentDataCollector.AddToProperties( UniqueId, "_ChromaticAberration(\"Chromatic Aberration\", Range( 0 , 0.3)) = 0.1", m_refractionReorder.OrderIndex + 1 );
  1285. m_currentDataCollector.AddToPragmas( UniqueId, "multi_compile _ALPHAPREMULTIPLY_ON" );
  1286. }
  1287. if( hasTranslucency || hasTransmission )
  1288. {
  1289. //Translucency and Transmission Generation
  1290. //Add properties and uniforms
  1291. m_currentDataCollector.AddToIncludes( UniqueId, Constants.UnityPBSLightingLib );
  1292. if( hasTranslucency )
  1293. {
  1294. m_currentDataCollector.AddToProperties( UniqueId, "[Header(Translucency)]", m_translucencyReorder.OrderIndex );
  1295. m_currentDataCollector.AddToProperties( UniqueId, "_Translucency(\"Strength\", Range( 0 , 50)) = 1", m_translucencyReorder.OrderIndex + 1 );
  1296. m_currentDataCollector.AddToProperties( UniqueId, "_TransNormalDistortion(\"Normal Distortion\", Range( 0 , 1)) = 0.1", m_translucencyReorder.OrderIndex + 2 );
  1297. m_currentDataCollector.AddToProperties( UniqueId, "_TransScattering(\"Scaterring Falloff\", Range( 1 , 50)) = 2", m_translucencyReorder.OrderIndex + 3 );
  1298. m_currentDataCollector.AddToProperties( UniqueId, "_TransDirect(\"Direct\", Range( 0 , 1)) = 1", m_translucencyReorder.OrderIndex + 4 );
  1299. m_currentDataCollector.AddToProperties( UniqueId, "_TransAmbient(\"Ambient\", Range( 0 , 1)) = 0.2", m_translucencyReorder.OrderIndex + 5 );
  1300. m_currentDataCollector.AddToProperties( UniqueId, "_TransShadow(\"Shadow\", Range( 0 , 1)) = 0.9", m_translucencyReorder.OrderIndex + 6 );
  1301. m_currentDataCollector.AddToUniforms( UniqueId, "uniform half _Translucency;" );
  1302. m_currentDataCollector.AddToUniforms( UniqueId, "uniform half _TransNormalDistortion;" );
  1303. m_currentDataCollector.AddToUniforms( UniqueId, "uniform half _TransScattering;" );
  1304. m_currentDataCollector.AddToUniforms( UniqueId, "uniform half _TransDirect;" );
  1305. m_currentDataCollector.AddToUniforms( UniqueId, "uniform half _TransAmbient;" );
  1306. m_currentDataCollector.AddToUniforms( UniqueId, "uniform half _TransShadow;" );
  1307. }
  1308. //Add custom struct
  1309. switch( m_currentLightModel )
  1310. {
  1311. case StandardShaderLightModel.Standard:
  1312. case StandardShaderLightModel.StandardSpecular:
  1313. outputStruct = "SurfaceOutput" + m_currentLightModel.ToString() + Constants.CustomLightStructStr; break;
  1314. }
  1315. m_currentDataCollector.ChangeCustomInputHeader( m_currentLightModel.ToString() + Constants.CustomLightStructStr );
  1316. m_currentDataCollector.AddToCustomInput( UniqueId, "half3 Albedo", true );
  1317. m_currentDataCollector.AddToCustomInput( UniqueId, "half3 Normal", true );
  1318. m_currentDataCollector.AddToCustomInput( UniqueId, "half3 Emission", true );
  1319. switch( m_currentLightModel )
  1320. {
  1321. case StandardShaderLightModel.Standard:
  1322. m_currentDataCollector.AddToCustomInput( UniqueId, "half Metallic", true );
  1323. break;
  1324. case StandardShaderLightModel.StandardSpecular:
  1325. m_currentDataCollector.AddToCustomInput( UniqueId, "half3 Specular", true );
  1326. break;
  1327. }
  1328. m_currentDataCollector.AddToCustomInput( UniqueId, "half Smoothness", true );
  1329. m_currentDataCollector.AddToCustomInput( UniqueId, "half Occlusion", true );
  1330. m_currentDataCollector.AddToCustomInput( UniqueId, "half Alpha", true );
  1331. if( hasTranslucency )
  1332. m_currentDataCollector.AddToCustomInput( UniqueId, "half3 Translucency", true );
  1333. if( hasTransmission )
  1334. m_currentDataCollector.AddToCustomInput( UniqueId, "half3 Transmission", true );
  1335. }
  1336. if( sortedPorts[ i ].Name.Equals( DiscardStr ) )
  1337. {
  1338. //Discard Op Node
  1339. if( m_currentLightModel == StandardShaderLightModel.CustomLighting )
  1340. {
  1341. hasCustomLightingMask = true;
  1342. m_currentDataCollector.UsingCustomOutput = true;
  1343. m_currentDataCollector.GenType = PortGenType.CustomLighting;
  1344. WireReference connection = sortedPorts[ i ].GetConnection();
  1345. ParentNode node = UIUtils.GetNode( connection.NodeId );
  1346. customLightingMaskCode = node.GetValueFromOutputStr( connection.PortId, WirePortDataType.FLOAT, ref m_currentDataCollector, false );
  1347. customLightingMaskCode = "clip( " + customLightingMaskCode + " - " + m_inlineOpacityMaskClipValue.GetValueOrProperty( IOUtils.MaskClipValueName, false ) + " )";
  1348. customLightingInstructions = m_currentDataCollector.CustomOutput;
  1349. m_currentDataCollector.GenType = PortGenType.NonCustomLighting;
  1350. m_currentDataCollector.UsingCustomOutput = false;
  1351. continue;
  1352. }
  1353. else
  1354. {
  1355. string clipIn = "\t\t\tclip( ";
  1356. string clipOut = " - " + m_inlineOpacityMaskClipValue.GetValueOrProperty( IOUtils.MaskClipValueName, false ) + " );\n";
  1357. if( m_alphaToCoverage && m_castShadows )
  1358. {
  1359. clipIn = "\t\t\t#if UNITY_PASS_SHADOWCASTER\n" + clipIn;
  1360. clipOut = clipOut + "\t\t\t#endif\n";
  1361. }
  1362. CreateInstructionsForPort( sortedPorts[ i ], Constants.OutputVarStr + "." + sortedPorts[ i ].DataName, true, clipIn, clipOut, false, normalIsConnected );
  1363. }
  1364. }
  1365. else if( sortedPorts[ i ].DataName.Equals( VertexDataStr ) )
  1366. {
  1367. string vertexInstructions = CreateInstructionsForVertexPort( sortedPorts[ i ] );
  1368. m_currentDataCollector.AddToVertexDisplacement( vertexInstructions, m_vertexMode );
  1369. }
  1370. else if( sortedPorts[ i ].DataName.Equals( VertexNormalStr ) )
  1371. {
  1372. string vertexInstructions = CreateInstructionsForVertexPort( sortedPorts[ i ] );
  1373. m_currentDataCollector.AddToVertexNormal( vertexInstructions );
  1374. }
  1375. else if( m_tessOpHelper.IsTessellationPort( sortedPorts[ i ].PortId ) && sortedPorts[ i ].IsConnected /* && m_tessOpHelper.EnableTesselation*/)
  1376. {
  1377. //Vertex displacement and per vertex custom data
  1378. WireReference connection = sortedPorts[ i ].GetConnection();
  1379. ParentNode node = UIUtils.GetNode( connection.NodeId );
  1380. string vertexInstructions = node.GetValueFromOutputStr( connection.PortId, sortedPorts[ i ].DataType, ref m_currentDataCollector, false );
  1381. if( m_currentDataCollector.DirtySpecialLocalVariables )
  1382. {
  1383. m_tessOpHelper.AddAdditionalData( m_currentDataCollector.SpecialLocalVariables );
  1384. m_currentDataCollector.ClearSpecialLocalVariables();
  1385. }
  1386. if( m_currentDataCollector.DirtyVertexVariables )
  1387. {
  1388. m_tessOpHelper.AddAdditionalData( m_currentDataCollector.VertexLocalVariables );
  1389. m_currentDataCollector.ClearVertexLocalVariables();
  1390. }
  1391. m_tessOpHelper.AddCustomFunction( vertexInstructions );
  1392. }
  1393. else if( sortedPorts[ i ].Name.Equals( RefractionStr ) )
  1394. {
  1395. ContainerGraph.ResetNodesLocalVariables();
  1396. m_currentDataCollector.UsingCustomOutput = true;
  1397. refractionFix = " + 0.00001 * i.screenPos * i.worldPos";
  1398. m_currentDataCollector.AddInstructions( "\t\t\to.Normal = o.Normal" + refractionFix + ";\n" );
  1399. refractionCode = CreateInstructionStringForPort( sortedPorts[ i ], false );
  1400. refractionInstructions = m_currentDataCollector.CustomOutput;
  1401. m_currentDataCollector.UsingCustomOutput = false;
  1402. }
  1403. else if( sortedPorts[ i ].Name.Equals( CustomLightingStr ) )
  1404. {
  1405. m_currentDataCollector.UsingCustomOutput = true;
  1406. WireReference connection = sortedPorts[ i ].GetConnection();
  1407. ParentNode node = UIUtils.GetNode( connection.NodeId );
  1408. customLightingCode = node.GetValueFromOutputStr( connection.PortId, WirePortDataType.FLOAT3, ref m_currentDataCollector, false );
  1409. customLightingInstructions = m_currentDataCollector.CustomOutput;
  1410. if( m_currentDataCollector.ForceNormal )
  1411. {
  1412. m_currentDataCollector.AddToStartInstructions( "\t\t\t" + Constants.OutputVarStr + ".Normal = float3(0,0,1);\n" );
  1413. m_currentDataCollector.DirtyNormal = true;
  1414. m_currentDataCollector.ForceNormal = false;
  1415. }
  1416. if( m_currentDataCollector.DirtyVertexVariables )
  1417. {
  1418. m_currentDataCollector.AddVertexInstruction( m_currentDataCollector.VertexLocalVariables, UniqueId, false );
  1419. m_currentDataCollector.ClearVertexLocalVariables();
  1420. }
  1421. m_currentDataCollector.UsingCustomOutput = false;
  1422. }
  1423. else if( sortedPorts[ i ].Name.Equals( AlphaStr ) && m_currentLightModel == StandardShaderLightModel.CustomLighting )
  1424. {
  1425. m_currentDataCollector.UsingCustomOutput = true;
  1426. m_currentDataCollector.GenType = PortGenType.CustomLighting;
  1427. WireReference connection = sortedPorts[ i ].GetConnection();
  1428. ParentNode node = UIUtils.GetNode( connection.NodeId );
  1429. customLightingAlphaCode = node.GetValueFromOutputStr( connection.PortId, WirePortDataType.FLOAT, ref m_currentDataCollector, false );
  1430. customLightingInstructions = m_currentDataCollector.CustomOutput;
  1431. if( m_currentDataCollector.ForceNormal )
  1432. {
  1433. m_currentDataCollector.AddToStartInstructions( "\t\t\t" + Constants.OutputVarStr + ".Normal = float3(0,0,1);\n" );
  1434. m_currentDataCollector.DirtyNormal = true;
  1435. m_currentDataCollector.ForceNormal = false;
  1436. }
  1437. if( m_currentDataCollector.DirtyVertexVariables )
  1438. {
  1439. m_currentDataCollector.AddVertexInstruction( m_currentDataCollector.VertexLocalVariables, UniqueId, false );
  1440. m_currentDataCollector.ClearVertexLocalVariables();
  1441. }
  1442. m_currentDataCollector.GenType = PortGenType.NonCustomLighting;
  1443. m_currentDataCollector.UsingCustomOutput = false;
  1444. }
  1445. else
  1446. {
  1447. // Surface shader instruccions
  1448. // if working on normals and have normal dependent node then ignore local var generation
  1449. CreateInstructionsForPort( sortedPorts[ i ], Constants.OutputVarStr + "." + sortedPorts[ i ].DataName, false, null, null, false, normalIsConnected );
  1450. }
  1451. }
  1452. else if( sortedPorts[ i ].Name.Equals( AlphaStr ) )
  1453. {
  1454. if( m_currentLightModel != StandardShaderLightModel.CustomLighting )
  1455. {
  1456. m_currentDataCollector.AddInstructions( string.Format( "\t\t\t{0}.{1} = 1;\n", Constants.OutputVarStr, sortedPorts[ i ].DataName ) );
  1457. }
  1458. }
  1459. }
  1460. m_billboardOpHelper.FillDataCollectorWithInternalData( ref m_currentDataCollector );
  1461. }
  1462. if( ( m_castShadows && m_alphaToCoverage ) ||
  1463. ( m_castShadows && hasOpacity ) ||
  1464. ( m_castShadows && ( m_currentDataCollector.UsingWorldNormal || m_currentDataCollector.UsingWorldReflection || m_currentDataCollector.UsingViewDirection ) ) ||
  1465. ( m_castShadows && m_inputPorts[ m_discardPortId ].Available && m_inputPorts[ m_discardPortId ].IsConnected && m_currentLightModel == StandardShaderLightModel.CustomLighting ) )
  1466. m_customShadowCaster = true;
  1467. else
  1468. m_customShadowCaster = false;
  1469. //m_customShadowCaster = true;
  1470. for( int i = 0; i < 4; i++ )
  1471. {
  1472. if( m_currentDataCollector.GetChannelUsage( i ) == TextureChannelUsage.Required )
  1473. {
  1474. string channelName = UIUtils.GetChannelName( i );
  1475. m_currentDataCollector.AddToProperties( -1, UIUtils.GetTex2DProperty( channelName, TexturePropertyValues.white ), -1 );
  1476. }
  1477. }
  1478. m_currentDataCollector.AddToProperties( -1, IOUtils.DefaultASEDirtyCheckProperty, 10000 );
  1479. if( m_inputPorts[ m_discardPortId ].Available && m_inputPorts[ m_discardPortId ].IsConnected )
  1480. {
  1481. if( m_inlineOpacityMaskClipValue.IsValid )
  1482. {
  1483. RangedFloatNode fnode = UIUtils.GetNode( m_inlineOpacityMaskClipValue.NodeId ) as RangedFloatNode;
  1484. if( fnode != null )
  1485. {
  1486. m_currentDataCollector.AddToProperties( fnode.UniqueId, fnode.GetPropertyValue(), fnode.OrderIndex );
  1487. m_currentDataCollector.AddToUniforms( fnode.UniqueId, fnode.GetUniformValue() );
  1488. }
  1489. else
  1490. {
  1491. IntNode inode = UIUtils.GetNode( m_inlineOpacityMaskClipValue.NodeId ) as IntNode;
  1492. m_currentDataCollector.AddToProperties( inode.UniqueId, inode.GetPropertyValue(), inode.OrderIndex );
  1493. m_currentDataCollector.AddToUniforms( inode.UniqueId, inode.GetUniformValue() );
  1494. }
  1495. } else
  1496. {
  1497. m_currentDataCollector.AddToProperties( -1, string.Format( IOUtils.MaskClipValueProperty, OpacityMaskClipValueStr, m_opacityMaskClipValue ), ( m_maskClipReorder != null ) ? m_maskClipReorder.OrderIndex : -1 );
  1498. m_currentDataCollector.AddToUniforms( -1, string.Format( IOUtils.MaskClipValueUniform, m_opacityMaskClipValue ) );
  1499. }
  1500. }
  1501. if( !m_currentDataCollector.DirtyInputs )
  1502. m_currentDataCollector.AddToInput( UniqueId, "half filler", true );
  1503. if( m_currentLightModel == StandardShaderLightModel.BlinnPhong )
  1504. m_currentDataCollector.AddToProperties( -1, "_SpecColor(\"Specular Color\",Color)=(1,1,1,1)", m_specColorReorder.OrderIndex );
  1505. //Tesselation
  1506. if( m_tessOpHelper.EnableTesselation )
  1507. {
  1508. m_tessOpHelper.AddToDataCollector( ref m_currentDataCollector, m_tessellationReorder != null ? m_tessellationReorder.OrderIndex : -1 );
  1509. if( !m_currentDataCollector.DirtyPerVertexData )
  1510. {
  1511. m_currentDataCollector.OpenPerVertexHeader( false );
  1512. }
  1513. }
  1514. if( m_outlineHelper.EnableOutline || ( m_currentDataCollector.UsingCustomOutlineColor || m_currentDataCollector.CustomOutlineSelectedAlpha > 0 || m_currentDataCollector.UsingCustomOutlineWidth ) )
  1515. {
  1516. m_outlineHelper.AddToDataCollector( ref m_currentDataCollector );
  1517. }
  1518. #if !UNITY_2017_1_OR_NEWER
  1519. if( m_renderingOptionsOpHelper.LodCrossfade )
  1520. {
  1521. m_currentDataCollector.AddToPragmas( UniqueId, "multi_compile _ LOD_FADE_CROSSFADE" );
  1522. m_currentDataCollector.AddToStartInstructions( "\t\t\tUNITY_APPLY_DITHER_CROSSFADE(i);\n" );
  1523. m_currentDataCollector.AddToInput( UniqueId, "UNITY_DITHER_CROSSFADE_COORDS", false );
  1524. m_currentDataCollector.AddVertexInstruction( "UNITY_TRANSFER_DITHER_CROSSFADE( " + Constants.VertexShaderOutputStr + ", " + Constants.VertexShaderInputStr + ".vertex )", UniqueId, true );
  1525. }
  1526. #endif
  1527. //m_additionalIncludes.AddToDataCollector( ref m_currentDataCollector );
  1528. //m_additionalPragmas.AddToDataCollector( ref m_currentDataCollector );
  1529. //m_additionalDefines.AddToDataCollector( ref m_currentDataCollector );
  1530. m_additionalDirectives.AddAllToDataCollector( ref m_currentDataCollector );
  1531. //m_currentDataCollector.CloseInputs();
  1532. m_currentDataCollector.CloseCustomInputs();
  1533. m_currentDataCollector.CloseProperties();
  1534. m_currentDataCollector.ClosePerVertexHeader();
  1535. //build Shader Body
  1536. string ShaderBody = string.Empty;
  1537. OpenShaderBody( ref ShaderBody, m_shaderName );
  1538. {
  1539. //set properties
  1540. if( m_currentDataCollector.DirtyProperties )
  1541. {
  1542. ShaderBody += m_currentDataCollector.BuildPropertiesString();
  1543. }
  1544. //set subshader
  1545. OpenSubShaderBody( ref ShaderBody );
  1546. {
  1547. // Add extra depth pass
  1548. m_zBufferHelper.DrawExtraDepthPass( ref ShaderBody );
  1549. // Add optionalPasses
  1550. if( m_outlineHelper.EnableOutline || ( m_currentDataCollector.UsingCustomOutlineColor || m_currentDataCollector.CustomOutlineSelectedAlpha > 0 || m_currentDataCollector.UsingCustomOutlineWidth ) )
  1551. {
  1552. if( !usingDebugPort )
  1553. AddMultilineBody( ref ShaderBody, m_outlineHelper.OutlineFunctionBody( ref m_currentDataCollector, isInstancedShader, m_customShadowCaster, UIUtils.RemoveInvalidCharacters( ShaderName ), ( m_billboardOpHelper.IsBillboard && !usingDebugPort ? m_billboardOpHelper.GetInternalMultilineInstructions() : null ), ref m_tessOpHelper, ShaderModelTypeArr[ m_shaderModelIdx ] ) );
  1554. }
  1555. //Add SubShader tags
  1556. if( hasEmission )
  1557. {
  1558. tags += " \"IsEmissive\" = \"true\" ";
  1559. }
  1560. tags += m_customTagsHelper.GenerateCustomTags();
  1561. tags = "Tags{ " + tags + " }";
  1562. if( !string.IsNullOrEmpty( aboveUsePasses ) )
  1563. {
  1564. ShaderBody += aboveUsePasses;
  1565. }
  1566. AddRenderTags( ref ShaderBody, tags );
  1567. AddShaderLOD( ref ShaderBody, m_shaderLOD );
  1568. AddRenderState( ref ShaderBody, "Cull", m_inlineCullMode.GetValueOrProperty( m_cullMode.ToString() ) );
  1569. m_customBlendAvailable = ( m_alphaMode == AlphaMode.Custom || m_alphaMode == AlphaMode.Opaque );
  1570. if( ( m_zBufferHelper.IsActive && m_customBlendAvailable ) || m_outlineHelper.UsingZWrite || m_outlineHelper.UsingZTest )
  1571. {
  1572. ShaderBody += m_zBufferHelper.CreateDepthInfo( m_outlineHelper.UsingZWrite, m_outlineHelper.UsingZTest );
  1573. }
  1574. if( m_stencilBufferHelper.Active )
  1575. {
  1576. ShaderBody += m_stencilBufferHelper.CreateStencilOp( this );
  1577. }
  1578. if( m_blendOpsHelper.Active )
  1579. {
  1580. ShaderBody += m_blendOpsHelper.CreateBlendOps();
  1581. }
  1582. if( m_alphaToCoverage )
  1583. {
  1584. ShaderBody += "\t\tAlphaToMask On\n";
  1585. }
  1586. // Build Color Mask
  1587. m_colorMaskHelper.BuildColorMask( ref ShaderBody, m_customBlendAvailable );
  1588. //ShaderBody += "\t\tZWrite " + _zWriteMode + '\n';
  1589. //ShaderBody += "\t\tZTest " + _zTestMode + '\n';
  1590. //Add GrabPass
  1591. if( m_currentDataCollector.DirtyGrabPass )
  1592. {
  1593. ShaderBody += m_currentDataCollector.GrabPass;
  1594. }
  1595. // build optional parameters
  1596. string OptionalParameters = string.Empty;
  1597. // addword standard to custom lighting to accepts standard lighting models
  1598. string standardCustomLighting = string.Empty;
  1599. if( m_currentLightModel == StandardShaderLightModel.CustomLighting )
  1600. standardCustomLighting = "Standard";
  1601. //add cg program
  1602. if( m_customShadowCaster )
  1603. OpenCGInclude( ref ShaderBody );
  1604. else
  1605. OpenCGProgram( ref ShaderBody );
  1606. {
  1607. //Add Defines
  1608. if( m_currentDataCollector.DirtyDefines )
  1609. ShaderBody += m_currentDataCollector.Defines;
  1610. //Add Includes
  1611. if( m_customShadowCaster )
  1612. {
  1613. m_currentDataCollector.AddToIncludes( UniqueId, Constants.UnityPBSLightingLib );
  1614. m_currentDataCollector.AddToIncludes( UniqueId, "Lighting.cginc" );
  1615. }
  1616. if( m_currentDataCollector.DirtyIncludes )
  1617. ShaderBody += m_currentDataCollector.Includes;
  1618. //define as surface shader and specify lighting model
  1619. if( UIUtils.GetTextureArrayNodeAmount() > 0 && m_shaderModelIdx < 3 )
  1620. {
  1621. Debug.Log( "Automatically changing Shader Model to 3.5 since it's the minimum required by texture arrays." );
  1622. m_shaderModelIdx = 3;
  1623. }
  1624. // if tessellation is active then we need be at least using shader model 4.6
  1625. if( m_tessOpHelper.EnableTesselation && m_shaderModelIdx < 6 )
  1626. {
  1627. Debug.Log( "Automatically changing Shader Model to 4.6 since it's the minimum required by tessellation." );
  1628. m_shaderModelIdx = 6;
  1629. }
  1630. // if translucency is ON change render path
  1631. if( hasTranslucency && m_renderPath != RenderPath.ForwardOnly )
  1632. {
  1633. Debug.Log( "Automatically changing Render Path to Forward Only since translucency only works in forward rendering." );
  1634. m_renderPath = RenderPath.ForwardOnly;
  1635. }
  1636. // if outline is ON change render path
  1637. if( m_outlineHelper.EnableOutline && m_renderPath != RenderPath.ForwardOnly )
  1638. {
  1639. Debug.Log( "Automatically changing Render Path to Forward Only since outline only works in forward rendering." );
  1640. m_renderPath = RenderPath.ForwardOnly;
  1641. }
  1642. // if transmission is ON change render path
  1643. if( hasTransmission && m_renderPath != RenderPath.ForwardOnly )
  1644. {
  1645. Debug.Log( "Automatically changing Render Path to Forward Only since transmission only works in forward rendering." );
  1646. m_renderPath = RenderPath.ForwardOnly;
  1647. }
  1648. // if refraction is ON change render path
  1649. if( hasRefraction && m_renderPath != RenderPath.ForwardOnly )
  1650. {
  1651. Debug.Log( "Automatically changing Render Path to Forward Only since refraction only works in forward rendering." );
  1652. m_renderPath = RenderPath.ForwardOnly;
  1653. }
  1654. ShaderBody += string.Format( IOUtils.PragmaTargetHeader, ShaderModelTypeArr[ m_shaderModelIdx ] );
  1655. //Add pragmas (needs check to see if all pragmas work with custom shadow caster)
  1656. if( m_currentDataCollector.DirtyPragmas/* && !m_customShadowCaster */)
  1657. ShaderBody += m_currentDataCollector.Pragmas;
  1658. if(m_currentDataCollector.DirtyAdditionalDirectives)
  1659. ShaderBody += m_currentDataCollector.StandardAdditionalDirectives;
  1660. //if ( !m_customBlendMode )
  1661. {
  1662. switch( m_alphaMode )
  1663. {
  1664. case AlphaMode.Opaque:
  1665. case AlphaMode.Masked: break;
  1666. case AlphaMode.Transparent:
  1667. {
  1668. OptionalParameters += "alpha:fade" + Constants.OptionalParametersSep;
  1669. }
  1670. break;
  1671. case AlphaMode.Premultiply:
  1672. {
  1673. OptionalParameters += "alpha:premul" + Constants.OptionalParametersSep;
  1674. }
  1675. break;
  1676. }
  1677. }
  1678. if( m_keepAlpha )
  1679. {
  1680. OptionalParameters += "keepalpha" + Constants.OptionalParametersSep;
  1681. }
  1682. if( hasRefraction )
  1683. {
  1684. OptionalParameters += "finalcolor:RefractionF" + Constants.OptionalParametersSep;
  1685. }
  1686. if( !m_customShadowCaster && m_castShadows )
  1687. {
  1688. OptionalParameters += "addshadow" + Constants.OptionalParametersSep;
  1689. }
  1690. if( m_castShadows )
  1691. {
  1692. OptionalParameters += "fullforwardshadows" + Constants.OptionalParametersSep;
  1693. }
  1694. if( !m_receiveShadows )
  1695. {
  1696. OptionalParameters += "noshadow" + Constants.OptionalParametersSep;
  1697. }
  1698. if( m_renderingOptionsOpHelper.IsOptionActive( " Add Pass" ) && usingDebugPort )
  1699. {
  1700. OptionalParameters += "noforwardadd" + Constants.OptionalParametersSep;
  1701. }
  1702. if( m_renderingOptionsOpHelper.ForceDisableInstancing )
  1703. {
  1704. OptionalParameters += "noinstancing" + Constants.OptionalParametersSep;
  1705. }
  1706. switch( m_renderPath )
  1707. {
  1708. case RenderPath.All: break;
  1709. case RenderPath.DeferredOnly: OptionalParameters += "exclude_path:forward" + Constants.OptionalParametersSep; break;
  1710. case RenderPath.ForwardOnly: OptionalParameters += "exclude_path:deferred" + Constants.OptionalParametersSep; break;
  1711. }
  1712. //Add code generation options
  1713. m_renderingOptionsOpHelper.Build( ref OptionalParameters );
  1714. if( !m_customShadowCaster )
  1715. {
  1716. string customLightSurface = string.Empty;
  1717. if( hasTranslucency || hasTransmission )
  1718. customLightSurface = "Custom";
  1719. m_renderingPlatformOpHelper.SetRenderingPlatforms( ref ShaderBody );
  1720. //Check if Custom Vertex is being used and add tag
  1721. if( m_currentDataCollector.DirtyPerVertexData )
  1722. OptionalParameters += "vertex:" + Constants.VertexDataFunc + Constants.OptionalParametersSep;
  1723. if( m_tessOpHelper.EnableTesselation && !usingDebugPort )
  1724. {
  1725. m_tessOpHelper.WriteToOptionalParams( ref OptionalParameters );
  1726. }
  1727. m_additionalSurfaceOptions.WriteToOptionalSurfaceOptions( ref OptionalParameters );
  1728. AddShaderPragma( ref ShaderBody, "surface surf " + standardCustomLighting + m_currentLightModel.ToString() + customLightSurface + Constants.OptionalParametersSep + OptionalParameters );
  1729. }
  1730. else
  1731. {
  1732. if( /*m_currentDataCollector.UsingWorldNormal ||*/ m_currentDataCollector.UsingInternalData )
  1733. {
  1734. ShaderBody += "\t\t#ifdef UNITY_PASS_SHADOWCASTER\n";
  1735. ShaderBody += "\t\t\t#undef INTERNAL_DATA\n";
  1736. ShaderBody += "\t\t\t#undef WorldReflectionVector\n";
  1737. ShaderBody += "\t\t\t#undef WorldNormalVector\n";
  1738. ShaderBody += "\t\t\t#define INTERNAL_DATA half3 internalSurfaceTtoW0; half3 internalSurfaceTtoW1; half3 internalSurfaceTtoW2;\n";
  1739. ShaderBody += "\t\t\t#define WorldReflectionVector(data,normal) reflect (data.worldRefl, half3(dot(data.internalSurfaceTtoW0,normal), dot(data.internalSurfaceTtoW1,normal), dot(data.internalSurfaceTtoW2,normal)))\n";
  1740. ShaderBody += "\t\t\t#define WorldNormalVector(data,normal) half3(dot(data.internalSurfaceTtoW0,normal), dot(data.internalSurfaceTtoW1,normal), dot(data.internalSurfaceTtoW2,normal))\n";
  1741. ShaderBody += "\t\t#endif\n";
  1742. }
  1743. }
  1744. if( m_currentDataCollector.UsingHigherSizeTexcoords )
  1745. {
  1746. ShaderBody += "\t\t#undef TRANSFORM_TEX\n";
  1747. ShaderBody += "\t\t#define TRANSFORM_TEX(tex,name) float4(tex.xy * name##_ST.xy + name##_ST.zw, tex.z, tex.w)\n";
  1748. }
  1749. if( m_currentDataCollector.DirtyAppData )
  1750. ShaderBody += m_currentDataCollector.CustomAppData;
  1751. // Add Input struct
  1752. if( m_currentDataCollector.DirtyInputs )
  1753. ShaderBody += "\t\t" + m_currentDataCollector.Inputs + "\t\t};" + "\n\n";
  1754. // Add Custom Lighting struct
  1755. if( m_currentDataCollector.DirtyCustomInput )
  1756. ShaderBody += m_currentDataCollector.CustomInput + "\n\n";
  1757. //Add Uniforms
  1758. if( m_currentDataCollector.DirtyUniforms )
  1759. ShaderBody += m_currentDataCollector.Uniforms + "\n";
  1760. // Add Array Derivatives Macros
  1761. if( m_currentDataCollector.UsingArrayDerivatives )
  1762. {
  1763. ShaderBody += "\t\t#if defined(UNITY_COMPILER_HLSL2GLSL) || defined(SHADER_TARGET_SURFACE_ANALYSIS)\n";
  1764. ShaderBody += "\t\t\t#define ASE_SAMPLE_TEX2DARRAY_GRAD(tex,coord,dx,dy) UNITY_SAMPLE_TEX2DARRAY (tex,coord)\n";
  1765. ShaderBody += "\t\t#else\n";
  1766. ShaderBody += "\t\t\t#define ASE_SAMPLE_TEX2DARRAY_GRAD(tex,coord,dx,dy) tex.SampleGrad (sampler##tex,coord,dx,dy)\n";
  1767. ShaderBody += "\t\t#endif\n\n";
  1768. }
  1769. //Add Instanced Properties
  1770. if( isInstancedShader && m_currentDataCollector.DirtyInstancedProperties )
  1771. {
  1772. m_currentDataCollector.SetupInstancePropertiesBlock( UIUtils.RemoveInvalidCharacters( ShaderName ) );
  1773. ShaderBody += m_currentDataCollector.InstancedProperties + "\n";
  1774. }
  1775. if( m_currentDataCollector.DirtyFunctions )
  1776. ShaderBody += m_currentDataCollector.Functions + "\n";
  1777. //Tesselation
  1778. if( m_tessOpHelper.EnableTesselation && !usingDebugPort )
  1779. {
  1780. ShaderBody += m_tessOpHelper.GetCurrentTessellationFunction + "\n";
  1781. }
  1782. //Add Custom Vertex Data
  1783. if( m_currentDataCollector.DirtyPerVertexData )
  1784. {
  1785. ShaderBody += m_currentDataCollector.VertexData;
  1786. }
  1787. if( m_currentLightModel == StandardShaderLightModel.Unlit )
  1788. {
  1789. for( int i = 0; i < VertexLitFunc.Length; i++ )
  1790. {
  1791. ShaderBody += VertexLitFunc[ i ] + "\n";
  1792. }
  1793. }
  1794. //Add custom lighting
  1795. if( m_currentLightModel == StandardShaderLightModel.CustomLighting )
  1796. {
  1797. ShaderBody += "\t\tinline half4 LightingStandard" + m_currentLightModel.ToString() + "( inout " + outputStruct + " " + Constants.CustomLightOutputVarStr + ", half3 viewDir, UnityGI gi )\n\t\t{\n";
  1798. ShaderBody += "\t\t\tUnityGIInput data = s.GIData;\n";
  1799. ShaderBody += "\t\t\tInput i = s.SurfInput;\n";
  1800. ShaderBody += "\t\t\thalf4 c = 0;\n";
  1801. if( m_currentDataCollector.UsingLightAttenuation )
  1802. {
  1803. ShaderBody += "\t\t\t#ifdef UNITY_PASS_FORWARDBASE\n";
  1804. ShaderBody += "\t\t\tfloat ase_lightAtten = data.atten;\n";
  1805. ShaderBody += "\t\t\tif( _LightColor0.a == 0)\n";
  1806. ShaderBody += "\t\t\tase_lightAtten = 0;\n";
  1807. ShaderBody += "\t\t\t#else\n";
  1808. ShaderBody += "\t\t\tfloat3 ase_lightAttenRGB = gi.light.color / ( ( _LightColor0.rgb ) + 0.000001 );\n";
  1809. ShaderBody += "\t\t\tfloat ase_lightAtten = max( max( ase_lightAttenRGB.r, ase_lightAttenRGB.g ), ase_lightAttenRGB.b );\n";
  1810. ShaderBody += "\t\t\t#endif\n";
  1811. ShaderBody += "\t\t\t#if defined(HANDLE_SHADOWS_BLENDING_IN_GI)\n";
  1812. ShaderBody += "\t\t\thalf bakedAtten = UnitySampleBakedOcclusion(data.lightmapUV.xy, data.worldPos);\n";
  1813. ShaderBody += "\t\t\tfloat zDist = dot(_WorldSpaceCameraPos - data.worldPos, UNITY_MATRIX_V[2].xyz);\n";
  1814. ShaderBody += "\t\t\tfloat fadeDist = UnityComputeShadowFadeDistance(data.worldPos, zDist);\n";
  1815. ShaderBody += "\t\t\tase_lightAtten = UnityMixRealtimeAndBakedShadows(data.atten, bakedAtten, UnityComputeShadowFade(fadeDist));\n";
  1816. ShaderBody += "\t\t\t#endif\n";
  1817. }
  1818. //if( m_currentDataCollector.dirtyc )
  1819. ShaderBody += customLightingInstructions;
  1820. ShaderBody += "\t\t\tc.rgb = " + ( !string.IsNullOrEmpty( customLightingCode ) ? customLightingCode : "0" ) + ";\n";
  1821. ShaderBody += "\t\t\tc.a = " + ( !string.IsNullOrEmpty( customLightingAlphaCode ) ? customLightingAlphaCode : "1" ) + ";\n";
  1822. if( m_alphaMode == AlphaMode.Premultiply || ( ( m_alphaMode == AlphaMode.Custom || m_alphaMode == AlphaMode.Opaque ) && m_blendOpsHelper.CurrentBlendRGB.IndexOf( "Premultiplied" ) > -1 ) )
  1823. ShaderBody += "\t\t\tc.rgb *= c.a;\n";
  1824. if( hasCustomLightingMask )
  1825. ShaderBody += "\t\t\t" + customLightingMaskCode + ";\n";
  1826. ShaderBody += "\t\t\treturn c;\n";
  1827. ShaderBody += "\t\t}\n\n";
  1828. //Add GI function
  1829. ShaderBody += "\t\tinline void LightingStandard" + m_currentLightModel.ToString() + "_GI( inout " + outputStruct + " " + Constants.CustomLightOutputVarStr + ", UnityGIInput data, inout UnityGI gi )\n\t\t{\n";
  1830. ShaderBody += "\t\t\ts.GIData = data;\n";
  1831. //ShaderBody += "\t\t\tUNITY_GI(gi, " + Constants.CustomLightOutputVarStr + ", data);\n";
  1832. ShaderBody += "\t\t}\n\n";
  1833. }
  1834. //Add custom lighting function
  1835. if( hasTranslucency || hasTransmission )
  1836. {
  1837. ShaderBody += "\t\tinline half4 Lighting" + m_currentLightModel.ToString() + Constants.CustomLightStructStr + "(" + outputStruct + " " + Constants.CustomLightOutputVarStr + ", half3 viewDir, UnityGI gi )\n\t\t{\n";
  1838. if( hasTranslucency )
  1839. {
  1840. ShaderBody += "\t\t\t#if !DIRECTIONAL\n";
  1841. ShaderBody += "\t\t\tfloat3 lightAtten = gi.light.color;\n";
  1842. ShaderBody += "\t\t\t#else\n";
  1843. ShaderBody += "\t\t\tfloat3 lightAtten = lerp( _LightColor0.rgb, gi.light.color, _TransShadow );\n";
  1844. ShaderBody += "\t\t\t#endif\n";
  1845. ShaderBody += "\t\t\thalf3 lightDir = gi.light.dir + " + Constants.CustomLightOutputVarStr + ".Normal * _TransNormalDistortion;\n";
  1846. ShaderBody += "\t\t\thalf transVdotL = pow( saturate( dot( viewDir, -lightDir ) ), _TransScattering );\n";
  1847. ShaderBody += "\t\t\thalf3 translucency = lightAtten * (transVdotL * _TransDirect + gi.indirect.diffuse * _TransAmbient) * " + Constants.CustomLightOutputVarStr + ".Translucency;\n";
  1848. ShaderBody += "\t\t\thalf4 c = half4( " + Constants.CustomLightOutputVarStr + ".Albedo * translucency * _Translucency, 0 );\n\n";
  1849. }
  1850. if( hasTransmission )
  1851. {
  1852. ShaderBody += "\t\t\thalf3 transmission = max(0 , -dot(" + Constants.CustomLightOutputVarStr + ".Normal, gi.light.dir)) * gi.light.color * " + Constants.CustomLightOutputVarStr + ".Transmission;\n";
  1853. ShaderBody += "\t\t\thalf4 d = half4(" + Constants.CustomLightOutputVarStr + ".Albedo * transmission , 0);\n\n";
  1854. }
  1855. ShaderBody += "\t\t\tSurfaceOutput" + m_currentLightModel.ToString() + " r;\n";
  1856. ShaderBody += "\t\t\tr.Albedo = " + Constants.CustomLightOutputVarStr + ".Albedo;\n";
  1857. ShaderBody += "\t\t\tr.Normal = " + Constants.CustomLightOutputVarStr + ".Normal;\n";
  1858. ShaderBody += "\t\t\tr.Emission = " + Constants.CustomLightOutputVarStr + ".Emission;\n";
  1859. switch( m_currentLightModel )
  1860. {
  1861. case StandardShaderLightModel.Standard:
  1862. ShaderBody += "\t\t\tr.Metallic = " + Constants.CustomLightOutputVarStr + ".Metallic;\n";
  1863. break;
  1864. case StandardShaderLightModel.StandardSpecular:
  1865. ShaderBody += "\t\t\tr.Specular = " + Constants.CustomLightOutputVarStr + ".Specular;\n";
  1866. break;
  1867. }
  1868. ShaderBody += "\t\t\tr.Smoothness = " + Constants.CustomLightOutputVarStr + ".Smoothness;\n";
  1869. ShaderBody += "\t\t\tr.Occlusion = " + Constants.CustomLightOutputVarStr + ".Occlusion;\n";
  1870. ShaderBody += "\t\t\tr.Alpha = " + Constants.CustomLightOutputVarStr + ".Alpha;\n";
  1871. ShaderBody += "\t\t\treturn Lighting" + m_currentLightModel.ToString() + " (r, viewDir, gi)" + ( hasTranslucency ? " + c" : "" ) + ( hasTransmission ? " + d" : "" ) + ";\n";
  1872. ShaderBody += "\t\t}\n\n";
  1873. //Add GI function
  1874. ShaderBody += "\t\tinline void Lighting" + m_currentLightModel.ToString() + Constants.CustomLightStructStr + "_GI(" + outputStruct + " " + Constants.CustomLightOutputVarStr + ", UnityGIInput data, inout UnityGI gi )\n\t\t{\n";
  1875. ShaderBody += "\t\t\t#if defined(UNITY_PASS_DEFERRED) && UNITY_ENABLE_REFLECTION_BUFFERS\n";
  1876. ShaderBody += "\t\t\t\tgi = UnityGlobalIllumination(data, " + Constants.CustomLightOutputVarStr + ".Occlusion, " + Constants.CustomLightOutputVarStr + ".Normal);\n";
  1877. ShaderBody += "\t\t\t#else\n";
  1878. ShaderBody += "\t\t\t\tUNITY_GLOSSY_ENV_FROM_SURFACE( g, " + Constants.CustomLightOutputVarStr + ", data );\n";
  1879. ShaderBody += "\t\t\t\tgi = UnityGlobalIllumination( data, " + Constants.CustomLightOutputVarStr + ".Occlusion, " + Constants.CustomLightOutputVarStr + ".Normal, g );\n";
  1880. ShaderBody += "\t\t\t#endif\n";
  1881. //ShaderBody += "\t\t\tUNITY_GI(gi, " + Constants.CustomLightOutputVarStr + ", data);\n";
  1882. ShaderBody += "\t\t}\n\n";
  1883. }
  1884. if( hasRefraction )
  1885. {
  1886. ShaderBody += "\t\tinline float4 Refraction( Input " + Constants.InputVarStr + ", " + outputStruct + " " + Constants.OutputVarStr + ", float indexOfRefraction, float chomaticAberration ) {\n";
  1887. ShaderBody += "\t\t\tfloat3 worldNormal = " + Constants.OutputVarStr + ".Normal;\n";
  1888. ShaderBody += "\t\t\tfloat4 screenPos = " + Constants.InputVarStr + ".screenPos;\n";
  1889. ShaderBody += "\t\t\t#if UNITY_UV_STARTS_AT_TOP\n";
  1890. ShaderBody += "\t\t\t\tfloat scale = -1.0;\n";
  1891. ShaderBody += "\t\t\t#else\n";
  1892. ShaderBody += "\t\t\t\tfloat scale = 1.0;\n";
  1893. ShaderBody += "\t\t\t#endif\n";
  1894. ShaderBody += "\t\t\tfloat halfPosW = screenPos.w * 0.5;\n";
  1895. ShaderBody += "\t\t\tscreenPos.y = ( screenPos.y - halfPosW ) * _ProjectionParams.x * scale + halfPosW;\n";
  1896. ShaderBody += "\t\t\t#if SHADER_API_D3D9 || SHADER_API_D3D11\n";
  1897. ShaderBody += "\t\t\t\tscreenPos.w += 0.00000000001;\n";
  1898. ShaderBody += "\t\t\t#endif\n";
  1899. ShaderBody += "\t\t\tfloat2 projScreenPos = ( screenPos / screenPos.w ).xy;\n";
  1900. ShaderBody += "\t\t\tfloat3 worldViewDir = normalize( UnityWorldSpaceViewDir( " + Constants.InputVarStr + ".worldPos ) );\n";
  1901. ShaderBody += "\t\t\tfloat3 refractionOffset = ( ( ( ( indexOfRefraction - 1.0 ) * mul( UNITY_MATRIX_V, float4( worldNormal, 0.0 ) ) ) * ( 1.0 / ( screenPos.z + 1.0 ) ) ) * ( 1.0 - dot( worldNormal, worldViewDir ) ) );\n";
  1902. ShaderBody += "\t\t\tfloat2 cameraRefraction = float2( refractionOffset.x, -( refractionOffset.y * _ProjectionParams.x ) );\n";
  1903. string grabpass = "_GrabTexture";
  1904. if( m_grabOrder != 0 )
  1905. grabpass = "RefractionGrab" + m_grabOrder;
  1906. ShaderBody += "\t\t\tfloat4 redAlpha = tex2D( " + grabpass + ", ( projScreenPos + cameraRefraction ) );\n";
  1907. ShaderBody += "\t\t\tfloat green = tex2D( " + grabpass + ", ( projScreenPos + ( cameraRefraction * ( 1.0 - chomaticAberration ) ) ) ).g;\n";
  1908. ShaderBody += "\t\t\tfloat blue = tex2D( " + grabpass + ", ( projScreenPos + ( cameraRefraction * ( 1.0 + chomaticAberration ) ) ) ).b;\n";
  1909. ShaderBody += "\t\t\treturn float4( redAlpha.r, green, blue, redAlpha.a );\n";
  1910. ShaderBody += "\t\t}\n\n";
  1911. ShaderBody += "\t\tvoid RefractionF( Input " + Constants.InputVarStr + ", " + outputStruct + " " + Constants.OutputVarStr + ", inout half4 color )\n";
  1912. ShaderBody += "\t\t{\n";
  1913. ShaderBody += "\t\t\t#ifdef UNITY_PASS_FORWARDBASE\n";
  1914. ShaderBody += refractionInstructions;
  1915. ShaderBody += "\t\t\tcolor.rgb = color.rgb + Refraction( " + Constants.InputVarStr + ", " + Constants.OutputVarStr + ", " + refractionCode + ", _ChromaticAberration ) * ( 1 - color.a );\n";
  1916. ShaderBody += "\t\t\tcolor.a = 1;\n";
  1917. ShaderBody += "\t\t\t#endif\n";
  1918. ShaderBody += "\t\t}\n\n";
  1919. }
  1920. //Add Surface Shader body
  1921. ShaderBody += "\t\tvoid surf( Input " + Constants.InputVarStr + " , inout " + outputStruct + " " + Constants.OutputVarStr + " )\n\t\t{\n";
  1922. {
  1923. // Pass input information to custom lighting function
  1924. if( m_currentLightModel == StandardShaderLightModel.CustomLighting )
  1925. ShaderBody += "\t\t\t" + Constants.OutputVarStr + ".SurfInput = " + Constants.InputVarStr + ";\n";
  1926. //add local vars
  1927. if( m_currentDataCollector.DirtyLocalVariables )
  1928. ShaderBody += m_currentDataCollector.LocalVariables;
  1929. //add nodes ops
  1930. if( m_currentDataCollector.DirtyInstructions )
  1931. ShaderBody += m_currentDataCollector.Instructions;
  1932. }
  1933. ShaderBody += "\t\t}\n";
  1934. }
  1935. CloseCGProgram( ref ShaderBody );
  1936. //Add custom Shadow Caster
  1937. if( m_customShadowCaster )
  1938. {
  1939. OpenCGProgram( ref ShaderBody );
  1940. string customLightSurface = hasTranslucency || hasTransmission ? "Custom" : "";
  1941. m_renderingPlatformOpHelper.SetRenderingPlatforms( ref ShaderBody );
  1942. //Check if Custom Vertex is being used and add tag
  1943. if( m_currentDataCollector.DirtyPerVertexData )
  1944. OptionalParameters += "vertex:" + Constants.VertexDataFunc + Constants.OptionalParametersSep;
  1945. if( m_tessOpHelper.EnableTesselation && !usingDebugPort )
  1946. {
  1947. m_tessOpHelper.WriteToOptionalParams( ref OptionalParameters );
  1948. }
  1949. //if ( hasRefraction )
  1950. // ShaderBody += "\t\t#pragma multi_compile _ALPHAPREMULTIPLY_ON\n";
  1951. m_additionalSurfaceOptions.WriteToOptionalSurfaceOptions( ref OptionalParameters );
  1952. AddShaderPragma( ref ShaderBody, "surface surf " + standardCustomLighting + m_currentLightModel.ToString() + customLightSurface + Constants.OptionalParametersSep + OptionalParameters );
  1953. CloseCGProgram( ref ShaderBody );
  1954. ShaderBody += "\t\tPass\n";
  1955. ShaderBody += "\t\t{\n";
  1956. ShaderBody += "\t\t\tName \"ShadowCaster\"\n";
  1957. ShaderBody += "\t\t\tTags{ \"LightMode\" = \"ShadowCaster\" }\n";
  1958. ShaderBody += "\t\t\tZWrite On\n";
  1959. if( m_alphaToCoverage )
  1960. ShaderBody += "\t\t\tAlphaToMask Off\n";
  1961. ShaderBody += "\t\t\tCGPROGRAM\n";
  1962. ShaderBody += "\t\t\t#pragma vertex vert\n";
  1963. ShaderBody += "\t\t\t#pragma fragment frag\n";
  1964. ShaderBody += "\t\t\t#pragma target " + ShaderModelTypeArr[ m_shaderModelIdx ] + "\n";
  1965. //ShaderBody += "\t\t\t#pragma multi_compile_instancing\n";
  1966. ShaderBody += "\t\t\t#pragma multi_compile_shadowcaster\n";
  1967. ShaderBody += "\t\t\t#pragma multi_compile UNITY_PASS_SHADOWCASTER\n";
  1968. ShaderBody += "\t\t\t#pragma skip_variants FOG_LINEAR FOG_EXP FOG_EXP2\n";
  1969. ShaderBody += "\t\t\t#include \"HLSLSupport.cginc\"\n";
  1970. #if UNITY_2018_3_OR_NEWER
  1971. //Preventing WebGL to throw error Duplicate system value semantic definition: input semantic 'SV_POSITION' and input semantic 'VPOS'
  1972. ShaderBody += "\t\t\t#if ( SHADER_API_D3D11 || SHADER_API_GLCORE || SHADER_API_GLES || SHADER_API_GLES3 || SHADER_API_METAL || SHADER_API_VULKAN )\n";
  1973. #else
  1974. ShaderBody += "\t\t\t#if ( SHADER_API_D3D11 || SHADER_API_GLCORE || SHADER_API_GLES3 || SHADER_API_METAL || SHADER_API_VULKAN )\n";
  1975. #endif
  1976. ShaderBody += "\t\t\t\t#define CAN_SKIP_VPOS\n";
  1977. ShaderBody += "\t\t\t#endif\n";
  1978. ShaderBody += "\t\t\t#include \"UnityCG.cginc\"\n";
  1979. ShaderBody += "\t\t\t#include \"Lighting.cginc\"\n";
  1980. ShaderBody += "\t\t\t#include \"UnityPBSLighting.cginc\"\n";
  1981. if( !( m_alphaToCoverage && hasOpacity && hasOpacityMask ) )
  1982. if( hasOpacity )
  1983. ShaderBody += "\t\t\tsampler3D _DitherMaskLOD;\n";
  1984. //ShaderBody += "\t\t\tsampler3D _DitherMaskLOD;\n";
  1985. ShaderBody += "\t\t\tstruct v2f\n";
  1986. ShaderBody += "\t\t\t{\n";
  1987. ShaderBody += "\t\t\t\tV2F_SHADOW_CASTER;\n";
  1988. int texcoordIndex = 1;
  1989. for( int i = 0; i < m_currentDataCollector.PackSlotsList.Count; i++ )
  1990. {
  1991. int size = 4 - m_currentDataCollector.PackSlotsList[ i ];
  1992. if( size > 0 )
  1993. {
  1994. ShaderBody += "\t\t\t\tfloat" + size + " customPack" + ( i + 1 ) + " : TEXCOORD" + ( i + 1 ) + ";\n";
  1995. }
  1996. texcoordIndex++;
  1997. }
  1998. if( !m_currentDataCollector.UsingInternalData )
  1999. ShaderBody += "\t\t\t\tfloat3 worldPos : TEXCOORD" + ( texcoordIndex++ ) + ";\n";
  2000. if( m_currentDataCollector.UsingScreenPos )
  2001. ShaderBody += "\t\t\t\tfloat4 screenPos : TEXCOORD" + ( texcoordIndex++ ) + ";\n";
  2002. if( /*m_currentDataCollector.UsingWorldNormal || m_currentDataCollector.UsingWorldPosition ||*/ m_currentDataCollector.UsingInternalData || m_currentDataCollector.DirtyNormal )
  2003. {
  2004. ShaderBody += "\t\t\t\tfloat4 tSpace0 : TEXCOORD" + ( texcoordIndex++ ) + ";\n";
  2005. ShaderBody += "\t\t\t\tfloat4 tSpace1 : TEXCOORD" + ( texcoordIndex++ ) + ";\n";
  2006. ShaderBody += "\t\t\t\tfloat4 tSpace2 : TEXCOORD" + ( texcoordIndex++ ) + ";\n";
  2007. }
  2008. else if( !m_currentDataCollector.UsingInternalData && m_currentDataCollector.UsingWorldNormal )
  2009. {
  2010. ShaderBody += "\t\t\t\tfloat3 worldNormal : TEXCOORD" + ( texcoordIndex++ ) + ";\n";
  2011. }
  2012. if( m_currentDataCollector.UsingVertexColor )
  2013. ShaderBody += "\t\t\t\thalf4 color : COLOR0;\n";
  2014. ShaderBody += "\t\t\t\tUNITY_VERTEX_INPUT_INSTANCE_ID\n";
  2015. ShaderBody += "\t\t\t};\n";
  2016. ShaderBody += "\t\t\tv2f vert( "+m_currentDataCollector.CustomAppDataName + " v )\n";
  2017. ShaderBody += "\t\t\t{\n";
  2018. ShaderBody += "\t\t\t\tv2f o;\n";
  2019. ShaderBody += "\t\t\t\tUNITY_SETUP_INSTANCE_ID( v );\n";
  2020. ShaderBody += "\t\t\t\tUNITY_INITIALIZE_OUTPUT( v2f, o );\n";
  2021. ShaderBody += "\t\t\t\tUNITY_TRANSFER_INSTANCE_ID( v, o );\n";
  2022. if( m_currentDataCollector.DirtyPerVertexData || m_currentDataCollector.CustomShadowCoordsList.Count > 0 )
  2023. ShaderBody += "\t\t\t\tInput customInputData;\n";
  2024. if( m_currentDataCollector.DirtyPerVertexData )
  2025. {
  2026. ShaderBody += "\t\t\t\tvertexDataFunc( v" + ( m_currentDataCollector.TesselationActive ? "" : ", customInputData" ) + " );\n";
  2027. }
  2028. ShaderBody += "\t\t\t\tfloat3 worldPos = mul( unity_ObjectToWorld, v.vertex ).xyz;\n";
  2029. ShaderBody += "\t\t\t\thalf3 worldNormal = UnityObjectToWorldNormal( v.normal );\n";
  2030. if( m_currentDataCollector.UsingInternalData || m_currentDataCollector.DirtyNormal )
  2031. {
  2032. ShaderBody += "\t\t\t\thalf3 worldTangent = UnityObjectToWorldDir( v.tangent.xyz );\n";
  2033. ShaderBody += "\t\t\t\thalf tangentSign = v.tangent.w * unity_WorldTransformParams.w;\n";
  2034. ShaderBody += "\t\t\t\thalf3 worldBinormal = cross( worldNormal, worldTangent ) * tangentSign;\n";
  2035. ShaderBody += "\t\t\t\to.tSpace0 = float4( worldTangent.x, worldBinormal.x, worldNormal.x, worldPos.x );\n";
  2036. ShaderBody += "\t\t\t\to.tSpace1 = float4( worldTangent.y, worldBinormal.y, worldNormal.y, worldPos.y );\n";
  2037. ShaderBody += "\t\t\t\to.tSpace2 = float4( worldTangent.z, worldBinormal.z, worldNormal.z, worldPos.z );\n";
  2038. }
  2039. else if( !m_currentDataCollector.UsingInternalData && m_currentDataCollector.UsingWorldNormal )
  2040. {
  2041. ShaderBody += "\t\t\t\to.worldNormal = worldNormal;\n";
  2042. }
  2043. for( int i = 0; i < m_currentDataCollector.CustomShadowCoordsList.Count; i++ )
  2044. {
  2045. int size = UIUtils.GetChannelsAmount( m_currentDataCollector.CustomShadowCoordsList[ i ].DataType );
  2046. string channels = string.Empty;
  2047. for( int j = 0; j < size; j++ )
  2048. {
  2049. channels += Convert.ToChar( 120 + m_currentDataCollector.CustomShadowCoordsList[ i ].TextureIndex + j );
  2050. }
  2051. channels = channels.Replace( '{', 'w' );
  2052. ShaderBody += "\t\t\t\to.customPack" + ( m_currentDataCollector.CustomShadowCoordsList[ i ].TextureSlot + 1 ) + "." + channels + " = customInputData." + m_currentDataCollector.CustomShadowCoordsList[ i ].CoordName + ";\n";
  2053. //TODO: TEMPORARY SOLUTION, this needs to go somewhere else, there's no need for these comparisons
  2054. if( m_currentDataCollector.CustomShadowCoordsList[ i ].CoordName.StartsWith( "uv_" ) )
  2055. {
  2056. ShaderBody += "\t\t\t\to.customPack" + ( m_currentDataCollector.CustomShadowCoordsList[ i ].TextureSlot + 1 ) + "." + channels + " = v.texcoord;\n";
  2057. }
  2058. else if( m_currentDataCollector.CustomShadowCoordsList[ i ].CoordName.StartsWith( "uv2_" ) )
  2059. {
  2060. ShaderBody += "\t\t\t\to.customPack" + ( m_currentDataCollector.CustomShadowCoordsList[ i ].TextureSlot + 1 ) + "." + channels + " = v.texcoord1;\n";
  2061. }
  2062. else if( m_currentDataCollector.CustomShadowCoordsList[ i ].CoordName.StartsWith( "uv3_" ) )
  2063. {
  2064. ShaderBody += "\t\t\t\to.customPack" + ( m_currentDataCollector.CustomShadowCoordsList[ i ].TextureSlot + 1 ) + "." + channels + " = v.texcoord2;\n";
  2065. }
  2066. else if( m_currentDataCollector.CustomShadowCoordsList[ i ].CoordName.StartsWith( "uv4_" ) )
  2067. {
  2068. ShaderBody += "\t\t\t\to.customPack" + ( m_currentDataCollector.CustomShadowCoordsList[ i ].TextureSlot + 1 ) + "." + channels + " = v.texcoord3;\n";
  2069. }
  2070. }
  2071. if( !m_currentDataCollector.UsingInternalData )
  2072. ShaderBody += "\t\t\t\to.worldPos = worldPos;\n";
  2073. ShaderBody += "\t\t\t\tTRANSFER_SHADOW_CASTER_NORMALOFFSET( o )\n";
  2074. if( m_currentDataCollector.UsingScreenPos )
  2075. ShaderBody += "\t\t\t\to.screenPos = ComputeScreenPos( o.pos );\n";
  2076. if( m_currentDataCollector.UsingVertexColor )
  2077. ShaderBody += "\t\t\t\to.color = v.color;\n";
  2078. ShaderBody += "\t\t\t\treturn o;\n";
  2079. ShaderBody += "\t\t\t}\n";
  2080. ShaderBody += "\t\t\thalf4 frag( v2f IN\n";
  2081. ShaderBody += "\t\t\t#if !defined( CAN_SKIP_VPOS )\n";
  2082. ShaderBody += "\t\t\t, UNITY_VPOS_TYPE vpos : VPOS\n";
  2083. ShaderBody += "\t\t\t#endif\n";
  2084. ShaderBody += "\t\t\t) : SV_Target\n";
  2085. ShaderBody += "\t\t\t{\n";
  2086. ShaderBody += "\t\t\t\tUNITY_SETUP_INSTANCE_ID( IN );\n";
  2087. ShaderBody += "\t\t\t\tInput surfIN;\n";
  2088. ShaderBody += "\t\t\t\tUNITY_INITIALIZE_OUTPUT( Input, surfIN );\n";
  2089. for( int i = 0; i < m_currentDataCollector.CustomShadowCoordsList.Count; i++ )
  2090. {
  2091. int size = UIUtils.GetChannelsAmount( m_currentDataCollector.CustomShadowCoordsList[ i ].DataType );
  2092. string channels = string.Empty;
  2093. for( int j = 0; j < size; j++ )
  2094. {
  2095. channels += Convert.ToChar( 120 + m_currentDataCollector.CustomShadowCoordsList[ i ].TextureIndex + j );
  2096. }
  2097. channels = channels.Replace( '{', 'w' );
  2098. ShaderBody += "\t\t\t\tsurfIN." + m_currentDataCollector.CustomShadowCoordsList[ i ].CoordName + " = IN.customPack" + ( m_currentDataCollector.CustomShadowCoordsList[ i ].TextureSlot + 1 ) + "." + channels + ";\n";
  2099. }
  2100. if( m_currentDataCollector.UsingInternalData )
  2101. ShaderBody += "\t\t\t\tfloat3 worldPos = float3( IN.tSpace0.w, IN.tSpace1.w, IN.tSpace2.w );\n";
  2102. else
  2103. ShaderBody += "\t\t\t\tfloat3 worldPos = IN.worldPos;\n";
  2104. ShaderBody += "\t\t\t\thalf3 worldViewDir = normalize( UnityWorldSpaceViewDir( worldPos ) );\n";
  2105. if( m_currentDataCollector.UsingViewDirection && !m_currentDataCollector.DirtyNormal )
  2106. ShaderBody += "\t\t\t\tsurfIN.viewDir = worldViewDir;\n";
  2107. else if( m_currentDataCollector.UsingViewDirection )
  2108. ShaderBody += "\t\t\t\tsurfIN.viewDir = IN.tSpace0.xyz * worldViewDir.x + IN.tSpace1.xyz * worldViewDir.y + IN.tSpace2.xyz * worldViewDir.z;\n";
  2109. if( m_currentDataCollector.UsingWorldPosition )
  2110. ShaderBody += "\t\t\t\tsurfIN.worldPos = worldPos;\n";
  2111. if( m_currentDataCollector.UsingWorldNormal && m_currentDataCollector.UsingInternalData )
  2112. ShaderBody += "\t\t\t\tsurfIN.worldNormal = float3( IN.tSpace0.z, IN.tSpace1.z, IN.tSpace2.z );\n";
  2113. else if( !m_currentDataCollector.UsingInternalData && m_currentDataCollector.UsingWorldNormal )
  2114. ShaderBody += "\t\t\t\tsurfIN.worldNormal = IN.worldNormal;\n";
  2115. if( m_currentDataCollector.UsingWorldReflection )
  2116. ShaderBody += "\t\t\t\tsurfIN.worldRefl = -worldViewDir;\n";
  2117. if( m_currentDataCollector.UsingInternalData )
  2118. {
  2119. ShaderBody += "\t\t\t\tsurfIN.internalSurfaceTtoW0 = IN.tSpace0.xyz;\n";
  2120. ShaderBody += "\t\t\t\tsurfIN.internalSurfaceTtoW1 = IN.tSpace1.xyz;\n";
  2121. ShaderBody += "\t\t\t\tsurfIN.internalSurfaceTtoW2 = IN.tSpace2.xyz;\n";
  2122. }
  2123. if( m_currentDataCollector.UsingScreenPos )
  2124. ShaderBody += "\t\t\t\tsurfIN.screenPos = IN.screenPos;\n";
  2125. if( m_currentDataCollector.UsingVertexColor )
  2126. ShaderBody += "\t\t\t\tsurfIN.vertexColor = IN.color;\n";
  2127. ShaderBody += "\t\t\t\t" + outputStruct + " o;\n";
  2128. ShaderBody += "\t\t\t\tUNITY_INITIALIZE_OUTPUT( " + outputStruct + ", o )\n";
  2129. ShaderBody += "\t\t\t\tsurf( surfIN, o );\n";
  2130. if( ( hasOpacity || hasOpacityMask ) && m_currentLightModel == StandardShaderLightModel.CustomLighting )
  2131. {
  2132. ShaderBody += "\t\t\t\tUnityGI gi;\n";
  2133. ShaderBody += "\t\t\t\tUNITY_INITIALIZE_OUTPUT( UnityGI, gi );\n";
  2134. ShaderBody += "\t\t\t\to.Alpha = LightingStandardCustomLighting( o, worldViewDir, gi ).a;\n";
  2135. }
  2136. ShaderBody += "\t\t\t\t#if defined( CAN_SKIP_VPOS )\n";
  2137. ShaderBody += "\t\t\t\tfloat2 vpos = IN.pos;\n";
  2138. ShaderBody += "\t\t\t\t#endif\n";
  2139. if( ( m_alphaToCoverage && hasOpacity && m_inputPorts[ m_discardPortId ].IsConnected ) )
  2140. {
  2141. }
  2142. else if( hasOpacity )
  2143. {
  2144. ShaderBody += "\t\t\t\thalf alphaRef = tex3D( _DitherMaskLOD, float3( vpos.xy * 0.25, o.Alpha * 0.9375 ) ).a;\n";
  2145. ShaderBody += "\t\t\t\tclip( alphaRef - 0.01 );\n";
  2146. }
  2147. ShaderBody += "\t\t\t\tSHADOW_CASTER_FRAGMENT( IN )\n";
  2148. ShaderBody += "\t\t\t}\n";
  2149. ShaderBody += "\t\t\tENDCG\n";
  2150. ShaderBody += "\t\t}\n";
  2151. }
  2152. }
  2153. if( !string.IsNullOrEmpty( bellowUsePasses ) )
  2154. {
  2155. ShaderBody += bellowUsePasses;
  2156. }
  2157. CloseSubShaderBody( ref ShaderBody );
  2158. if( m_dependenciesHelper.HasDependencies )
  2159. {
  2160. ShaderBody += m_dependenciesHelper.GenerateDependencies();
  2161. }
  2162. if( m_fallbackHelper.Active )
  2163. {
  2164. ShaderBody += m_fallbackHelper.TabbedFallbackShader;
  2165. }
  2166. else if( m_castShadows || m_receiveShadows )
  2167. {
  2168. AddShaderProperty( ref ShaderBody, "Fallback", "Diffuse" );
  2169. }
  2170. if( !string.IsNullOrEmpty( m_customInspectorName ) )
  2171. {
  2172. AddShaderProperty( ref ShaderBody, "CustomEditor", m_customInspectorName );
  2173. }
  2174. }
  2175. CloseShaderBody( ref ShaderBody );
  2176. if( usingDebugPort )
  2177. {
  2178. m_currentLightModel = cachedLightModel;
  2179. ContainerGraph.CurrentCanvasMode = cachedAvailability;
  2180. }
  2181. // Generate Graph info
  2182. ShaderBody += ContainerGraph.ParentWindow.GenerateGraphInfo();
  2183. //TODO: Remove current SaveDebugShader and uncomment SaveToDisk as soon as pathname is editable
  2184. if( !String.IsNullOrEmpty( pathname ) )
  2185. {
  2186. IOUtils.StartSaveThread( ShaderBody, ( isFullPath ? pathname : ( IOUtils.dataPath + pathname ) ) );
  2187. }
  2188. else
  2189. {
  2190. IOUtils.StartSaveThread( ShaderBody, Application.dataPath + "/AmplifyShaderEditor/Samples/Shaders/" + m_shaderName + ".shader" );
  2191. }
  2192. // Load new shader into material
  2193. if( CurrentShader == null )
  2194. {
  2195. AssetDatabase.Refresh( ImportAssetOptions.ForceUpdate );
  2196. CurrentShader = Shader.Find( ShaderName );
  2197. }
  2198. //else
  2199. //{
  2200. // // need to always get asset datapath because a user can change and asset location from the project window
  2201. // AssetDatabase.ImportAsset( AssetDatabase.GetAssetPath( m_currentShader ) );
  2202. // //ShaderUtil.UpdateShaderAsset( m_currentShader, ShaderBody );
  2203. //}
  2204. if( m_currentShader != null )
  2205. {
  2206. m_currentDataCollector.UpdateShaderImporter( ref m_currentShader );
  2207. if( m_currentMaterial != null )
  2208. {
  2209. if( m_currentShader != m_currentMaterial.shader )
  2210. m_currentMaterial.shader = m_currentShader;
  2211. #if UNITY_5_6_OR_NEWER
  2212. if ( isInstancedShader )
  2213. {
  2214. m_currentMaterial.enableInstancing = true;
  2215. }
  2216. #endif
  2217. m_currentDataCollector.UpdateMaterialOnPropertyNodes( m_currentMaterial );
  2218. UpdateMaterialEditor();
  2219. // need to always get asset datapath because a user can change and asset location from the project window
  2220. //AssetDatabase.ImportAsset( AssetDatabase.GetAssetPath( m_currentMaterial ) );
  2221. }
  2222. }
  2223. m_currentDataCollector.Destroy();
  2224. m_currentDataCollector = null;
  2225. return m_currentShader;
  2226. }
  2227. public override void UpdateFromShader( Shader newShader )
  2228. {
  2229. if( m_currentMaterial != null && m_currentMaterial.shader != newShader )
  2230. {
  2231. m_currentMaterial.shader = newShader;
  2232. }
  2233. CurrentShader = newShader;
  2234. }
  2235. public override void Destroy()
  2236. {
  2237. base.Destroy();
  2238. if( m_dummyProperty != null )
  2239. {
  2240. m_dummyProperty.Destroy();
  2241. GameObject.DestroyImmediate( m_dummyProperty );
  2242. m_dummyProperty = null;
  2243. }
  2244. m_translucencyPort = null;
  2245. m_transmissionPort = null;
  2246. m_refractionPort = null;
  2247. m_normalPort = null;
  2248. m_renderingOptionsOpHelper.Destroy();
  2249. m_renderingOptionsOpHelper = null;
  2250. m_additionalIncludes.Destroy();
  2251. m_additionalIncludes = null;
  2252. m_additionalPragmas.Destroy();
  2253. m_additionalPragmas = null;
  2254. m_additionalDefines.Destroy();
  2255. m_additionalDefines = null;
  2256. m_additionalSurfaceOptions.Destroy();
  2257. m_additionalSurfaceOptions = null;
  2258. m_additionalDirectives.Destroy();
  2259. m_additionalDirectives = null;
  2260. m_customTagsHelper.Destroy();
  2261. m_customTagsHelper = null;
  2262. m_dependenciesHelper.Destroy();
  2263. m_dependenciesHelper = null;
  2264. m_renderingPlatformOpHelper = null;
  2265. m_inspectorDefaultStyle = null;
  2266. m_inspectorFoldoutStyle = null;
  2267. m_zBufferHelper = null;
  2268. m_stencilBufferHelper = null;
  2269. m_blendOpsHelper = null;
  2270. m_tessOpHelper.Destroy();
  2271. m_tessOpHelper = null;
  2272. m_outlineHelper.Destroy();
  2273. m_outlineHelper = null;
  2274. m_colorMaskHelper.Destroy();
  2275. m_colorMaskHelper = null;
  2276. m_billboardOpHelper = null;
  2277. m_fallbackHelper.Destroy();
  2278. GameObject.DestroyImmediate( m_fallbackHelper );
  2279. m_fallbackHelper = null;
  2280. m_usePass.Destroy();
  2281. GameObject.DestroyImmediate( m_usePass );
  2282. m_usePass = null;
  2283. }
  2284. public override int VersionConvertInputPortId( int portId )
  2285. {
  2286. int newPort = portId;
  2287. //added translucency input after occlusion
  2288. if( UIUtils.CurrentShaderVersion() <= 2404 )
  2289. {
  2290. switch( m_currentLightModel )
  2291. {
  2292. case StandardShaderLightModel.Standard:
  2293. case StandardShaderLightModel.StandardSpecular:
  2294. if( portId >= 6 )
  2295. newPort += 1;
  2296. break;
  2297. case StandardShaderLightModel.CustomLighting:
  2298. case StandardShaderLightModel.Unlit:
  2299. case StandardShaderLightModel.Lambert:
  2300. case StandardShaderLightModel.BlinnPhong:
  2301. if( portId >= 5 )
  2302. newPort += 1;
  2303. break;
  2304. }
  2305. }
  2306. portId = newPort;
  2307. //added transmission input after occlusion
  2308. if( UIUtils.CurrentShaderVersion() < 2407 )
  2309. {
  2310. switch( m_currentLightModel )
  2311. {
  2312. case StandardShaderLightModel.Standard:
  2313. case StandardShaderLightModel.StandardSpecular:
  2314. if( portId >= 6 )
  2315. newPort += 1;
  2316. break;
  2317. case StandardShaderLightModel.CustomLighting:
  2318. case StandardShaderLightModel.Unlit:
  2319. case StandardShaderLightModel.Lambert:
  2320. case StandardShaderLightModel.BlinnPhong:
  2321. if( portId >= 5 )
  2322. newPort += 1;
  2323. break;
  2324. }
  2325. }
  2326. portId = newPort;
  2327. //added tessellation ports
  2328. if( UIUtils.CurrentShaderVersion() < 3002 )
  2329. {
  2330. switch( m_currentLightModel )
  2331. {
  2332. case StandardShaderLightModel.Standard:
  2333. case StandardShaderLightModel.StandardSpecular:
  2334. if( portId >= 13 )
  2335. newPort += 1;
  2336. break;
  2337. case StandardShaderLightModel.CustomLighting:
  2338. case StandardShaderLightModel.Unlit:
  2339. case StandardShaderLightModel.Lambert:
  2340. case StandardShaderLightModel.BlinnPhong:
  2341. if( portId >= 10 )
  2342. newPort += 1;
  2343. break;
  2344. }
  2345. }
  2346. portId = newPort;
  2347. //added refraction after translucency
  2348. if( UIUtils.CurrentShaderVersion() < 3204 )
  2349. {
  2350. switch( m_currentLightModel )
  2351. {
  2352. case StandardShaderLightModel.Standard:
  2353. case StandardShaderLightModel.StandardSpecular:
  2354. if( portId >= 8 )
  2355. newPort += 1;
  2356. break;
  2357. case StandardShaderLightModel.CustomLighting:
  2358. case StandardShaderLightModel.Unlit:
  2359. case StandardShaderLightModel.Lambert:
  2360. case StandardShaderLightModel.BlinnPhong:
  2361. if( portId >= 7 )
  2362. newPort += 1;
  2363. break;
  2364. }
  2365. }
  2366. portId = newPort;
  2367. //removed custom lighting port
  2368. //if ( UIUtils.CurrentShaderVersion() < 10003 ) //runs everytime because this system is only used after 5000 version
  2369. {
  2370. switch( m_currentLightModel )
  2371. {
  2372. case StandardShaderLightModel.Standard:
  2373. case StandardShaderLightModel.StandardSpecular:
  2374. if( portId >= 13 )
  2375. newPort -= 1;
  2376. break;
  2377. case StandardShaderLightModel.CustomLighting:
  2378. case StandardShaderLightModel.Unlit:
  2379. case StandardShaderLightModel.Lambert:
  2380. case StandardShaderLightModel.BlinnPhong:
  2381. if( portId >= 12 )
  2382. newPort -= 1;
  2383. break;
  2384. }
  2385. }
  2386. portId = newPort;
  2387. //if( UIUtils.CurrentShaderVersion() < 13802 ) //runs everytime because this system is only used after 5000 version
  2388. {
  2389. switch( m_currentLightModel )
  2390. {
  2391. case StandardShaderLightModel.Standard:
  2392. case StandardShaderLightModel.StandardSpecular:
  2393. if( portId >= 11 )
  2394. newPort += 1;
  2395. break;
  2396. case StandardShaderLightModel.CustomLighting:
  2397. case StandardShaderLightModel.Unlit:
  2398. case StandardShaderLightModel.Lambert:
  2399. case StandardShaderLightModel.BlinnPhong:
  2400. if( portId >= 10 )
  2401. newPort += 1;
  2402. break;
  2403. }
  2404. }
  2405. portId = newPort;
  2406. return newPort;
  2407. }
  2408. public override void ReadFromString( ref string[] nodeParams )
  2409. {
  2410. try
  2411. {
  2412. base.ReadFromString( ref nodeParams );
  2413. m_currentLightModel = (StandardShaderLightModel)Enum.Parse( typeof( StandardShaderLightModel ), GetCurrentParam( ref nodeParams ) );
  2414. if( CurrentMasterNodeCategory == AvailableShaderTypes.SurfaceShader && m_currentLightModel == StandardShaderLightModel.CustomLighting )
  2415. {
  2416. ContainerGraph.CurrentCanvasMode = NodeAvailability.CustomLighting;
  2417. ContainerGraph.ParentWindow.CurrentNodeAvailability = NodeAvailability.CustomLighting;
  2418. }
  2419. else if( CurrentMasterNodeCategory == AvailableShaderTypes.SurfaceShader )
  2420. {
  2421. ContainerGraph.CurrentCanvasMode = NodeAvailability.SurfaceShader;
  2422. ContainerGraph.ParentWindow.CurrentNodeAvailability = NodeAvailability.SurfaceShader;
  2423. }
  2424. //if ( _shaderCategory.Length > 0 )
  2425. // _shaderCategory = UIUtils.RemoveInvalidCharacters( _shaderCategory );
  2426. ShaderName = GetCurrentParam( ref nodeParams );
  2427. if( m_shaderName.Length > 0 )
  2428. ShaderName = UIUtils.RemoveShaderInvalidCharacters( ShaderName );
  2429. m_renderingOptionsOpHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
  2430. m_cullMode = (CullMode)Enum.Parse( typeof( CullMode ), GetCurrentParam( ref nodeParams ) );
  2431. m_zBufferHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
  2432. string alphaMode = GetCurrentParam( ref nodeParams );
  2433. if( UIUtils.CurrentShaderVersion() < 4003 )
  2434. {
  2435. if( alphaMode.Equals( "Fade" ) )
  2436. {
  2437. alphaMode = "Transparent";
  2438. }
  2439. else if( alphaMode.Equals( "Transparent" ) )
  2440. {
  2441. alphaMode = "Premultiply";
  2442. }
  2443. }
  2444. m_alphaMode = (AlphaMode)Enum.Parse( typeof( AlphaMode ), alphaMode );
  2445. m_opacityMaskClipValue = Convert.ToSingle( GetCurrentParam( ref nodeParams ) );
  2446. m_keepAlpha = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
  2447. m_keepAlpha = true;
  2448. m_castShadows = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
  2449. m_queueOrder = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
  2450. if( UIUtils.CurrentShaderVersion() > 11 )
  2451. {
  2452. m_customBlendMode = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
  2453. m_renderType = (RenderType)Enum.Parse( typeof( RenderType ), GetCurrentParam( ref nodeParams ) );
  2454. if( UIUtils.CurrentShaderVersion() > 14305 )
  2455. {
  2456. m_customRenderType = GetCurrentParam( ref nodeParams );
  2457. }
  2458. m_renderQueue = (RenderQueue)Enum.Parse( typeof( RenderQueue ), GetCurrentParam( ref nodeParams ) );
  2459. }
  2460. if( UIUtils.CurrentShaderVersion() > 2402 )
  2461. {
  2462. m_renderPath = (RenderPath)Enum.Parse( typeof( RenderPath ), GetCurrentParam( ref nodeParams ) );
  2463. }
  2464. if( UIUtils.CurrentShaderVersion() > 2405 )
  2465. {
  2466. m_renderingPlatformOpHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
  2467. }
  2468. if( UIUtils.CurrentShaderVersion() > 2500 )
  2469. {
  2470. m_colorMaskHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
  2471. }
  2472. if( UIUtils.CurrentShaderVersion() > 2501 )
  2473. {
  2474. m_stencilBufferHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
  2475. }
  2476. if( UIUtils.CurrentShaderVersion() > 2504 )
  2477. {
  2478. m_tessOpHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
  2479. }
  2480. if( UIUtils.CurrentShaderVersion() > 2505 )
  2481. {
  2482. m_receiveShadows = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
  2483. }
  2484. if( UIUtils.CurrentShaderVersion() > 3202 )
  2485. {
  2486. m_blendOpsHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
  2487. }
  2488. if( UIUtils.CurrentShaderVersion() > 3203 )
  2489. {
  2490. m_grabOrder = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
  2491. }
  2492. if( UIUtils.CurrentShaderVersion() > 5003 )
  2493. {
  2494. m_outlineHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
  2495. }
  2496. if( UIUtils.CurrentShaderVersion() > 5110 )
  2497. {
  2498. m_billboardOpHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
  2499. }
  2500. if( UIUtils.CurrentShaderVersion() > 6101 )
  2501. {
  2502. m_vertexMode = (VertexMode)Enum.Parse( typeof( VertexMode ), GetCurrentParam( ref nodeParams ) );
  2503. }
  2504. if( UIUtils.CurrentShaderVersion() > 6102 )
  2505. {
  2506. m_shaderLOD = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
  2507. m_fallbackHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
  2508. }
  2509. if( UIUtils.CurrentShaderVersion() > 7102 )
  2510. {
  2511. m_maskClipOrderIndex = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
  2512. m_translucencyOrderIndex = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
  2513. m_refractionOrderIndex = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
  2514. m_tessellationOrderIndex = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
  2515. }
  2516. if( UIUtils.CurrentShaderVersion() > 10010 && UIUtils.CurrentShaderVersion() < 15312 )
  2517. {
  2518. m_additionalIncludes.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
  2519. }
  2520. if( UIUtils.CurrentShaderVersion() > 11006 )
  2521. {
  2522. m_customTagsHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
  2523. }
  2524. if( UIUtils.CurrentShaderVersion() > 13102 && UIUtils.CurrentShaderVersion() < 15312 )
  2525. {
  2526. m_additionalPragmas.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
  2527. }
  2528. if( UIUtils.CurrentShaderVersion() > 13205 )
  2529. {
  2530. m_alphaToCoverage = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
  2531. }
  2532. if( UIUtils.CurrentShaderVersion() > 13903 )
  2533. {
  2534. m_dependenciesHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
  2535. }
  2536. if( UIUtils.CurrentShaderVersion() > 14005 && UIUtils.CurrentShaderVersion() < 15312 )
  2537. {
  2538. m_additionalDefines.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
  2539. }
  2540. if( UIUtils.CurrentShaderVersion() > 14501 )
  2541. {
  2542. m_inlineCullMode.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
  2543. }
  2544. if( UIUtils.CurrentShaderVersion() > 14502 )
  2545. {
  2546. m_specColorOrderIndex = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
  2547. }
  2548. if( UIUtils.CurrentShaderVersion() > 15204 )
  2549. {
  2550. m_inlineOpacityMaskClipValue.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
  2551. }
  2552. if( UIUtils.CurrentShaderVersion() > 15311 )
  2553. {
  2554. m_additionalDirectives.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
  2555. m_additionalSurfaceOptions.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
  2556. }
  2557. else
  2558. {
  2559. m_additionalDirectives.AddItems( AdditionalLineType.Define, m_additionalDefines.DefineList );
  2560. m_additionalDirectives.AddItems( AdditionalLineType.Include, m_additionalIncludes.IncludeList );
  2561. m_additionalDirectives.AddItems( AdditionalLineType.Pragma, m_additionalPragmas.PragmaList );
  2562. }
  2563. if( UIUtils.CurrentShaderVersion() > 15402 )
  2564. {
  2565. m_usePass.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
  2566. }
  2567. m_lightModelChanged = true;
  2568. m_lastLightModel = m_currentLightModel;
  2569. DeleteAllInputConnections( true );
  2570. AddMasterPorts();
  2571. UpdateFromBlendMode();
  2572. m_customBlendMode = TestCustomBlendMode();
  2573. ContainerGraph.CurrentPrecision = m_currentPrecisionType;
  2574. }
  2575. catch( Exception e )
  2576. {
  2577. Debug.Log( e );
  2578. }
  2579. }
  2580. public override void RefreshExternalReferences()
  2581. {
  2582. base.RefreshExternalReferences();
  2583. // change port connection from emission to the new custom lighting port
  2584. if( m_currentLightModel == StandardShaderLightModel.CustomLighting && m_inputPorts[ m_emissionPortId ].IsConnected && UIUtils.CurrentShaderVersion() < 13802 )
  2585. {
  2586. OutputPort port = m_inputPorts[ m_emissionPortId ].GetOutputConnection( 0 );
  2587. m_inputPorts[ m_emissionPortId ].FullDeleteConnections();
  2588. UIUtils.SetConnection( m_inputPorts[ m_customLightingPortId ].NodeId, m_inputPorts[ m_customLightingPortId ].PortId, port.NodeId, port.PortId );
  2589. }
  2590. }
  2591. public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
  2592. {
  2593. base.WriteToString( ref nodeInfo, ref connectionsInfo );
  2594. IOUtils.AddFieldValueToString( ref nodeInfo, m_currentLightModel );
  2595. IOUtils.AddFieldValueToString( ref nodeInfo, m_shaderName );
  2596. m_renderingOptionsOpHelper.WriteToString( ref nodeInfo );
  2597. IOUtils.AddFieldValueToString( ref nodeInfo, m_cullMode );
  2598. m_zBufferHelper.WriteToString( ref nodeInfo );
  2599. IOUtils.AddFieldValueToString( ref nodeInfo, m_alphaMode );
  2600. IOUtils.AddFieldValueToString( ref nodeInfo, m_opacityMaskClipValue );
  2601. IOUtils.AddFieldValueToString( ref nodeInfo, m_keepAlpha );
  2602. IOUtils.AddFieldValueToString( ref nodeInfo, m_castShadows );
  2603. IOUtils.AddFieldValueToString( ref nodeInfo, m_queueOrder );
  2604. IOUtils.AddFieldValueToString( ref nodeInfo, m_customBlendMode );
  2605. IOUtils.AddFieldValueToString( ref nodeInfo, m_renderType );
  2606. IOUtils.AddFieldValueToString( ref nodeInfo, m_customRenderType );
  2607. IOUtils.AddFieldValueToString( ref nodeInfo, m_renderQueue );
  2608. IOUtils.AddFieldValueToString( ref nodeInfo, m_renderPath );
  2609. m_renderingPlatformOpHelper.WriteToString( ref nodeInfo );
  2610. m_colorMaskHelper.WriteToString( ref nodeInfo );
  2611. m_stencilBufferHelper.WriteToString( ref nodeInfo );
  2612. m_tessOpHelper.WriteToString( ref nodeInfo );
  2613. IOUtils.AddFieldValueToString( ref nodeInfo, m_receiveShadows );
  2614. m_blendOpsHelper.WriteToString( ref nodeInfo );
  2615. IOUtils.AddFieldValueToString( ref nodeInfo, m_grabOrder );
  2616. m_outlineHelper.WriteToString( ref nodeInfo );
  2617. m_billboardOpHelper.WriteToString( ref nodeInfo );
  2618. IOUtils.AddFieldValueToString( ref nodeInfo, m_vertexMode );
  2619. IOUtils.AddFieldValueToString( ref nodeInfo, m_shaderLOD );
  2620. m_fallbackHelper.WriteToString( ref nodeInfo );
  2621. IOUtils.AddFieldValueToString( ref nodeInfo, ( m_maskClipReorder != null ) ? m_maskClipReorder.OrderIndex : -1 );
  2622. IOUtils.AddFieldValueToString( ref nodeInfo, ( m_translucencyReorder != null ) ? m_translucencyReorder.OrderIndex : -1 );
  2623. IOUtils.AddFieldValueToString( ref nodeInfo, ( m_refractionReorder != null ) ? m_refractionReorder.OrderIndex : -1 );
  2624. IOUtils.AddFieldValueToString( ref nodeInfo, ( m_tessellationReorder != null ) ? m_tessellationReorder.OrderIndex : -1 );
  2625. //m_additionalIncludes.WriteToString( ref nodeInfo );
  2626. m_customTagsHelper.WriteToString( ref nodeInfo );
  2627. //m_additionalPragmas.WriteToString( ref nodeInfo );
  2628. IOUtils.AddFieldValueToString( ref nodeInfo, m_alphaToCoverage );
  2629. m_dependenciesHelper.WriteToString( ref nodeInfo );
  2630. //m_additionalDefines.WriteToString( ref nodeInfo );
  2631. m_inlineCullMode.WriteToString( ref nodeInfo );
  2632. IOUtils.AddFieldValueToString( ref nodeInfo, ( m_specColorReorder != null ) ? m_specColorReorder.OrderIndex : -1 );
  2633. m_inlineOpacityMaskClipValue.WriteToString( ref nodeInfo );
  2634. m_additionalDirectives.WriteToString( ref nodeInfo );
  2635. m_additionalSurfaceOptions.WriteToString( ref nodeInfo );
  2636. m_usePass.WriteToString( ref nodeInfo );
  2637. }
  2638. private bool TestCustomBlendMode()
  2639. {
  2640. switch( m_alphaMode )
  2641. {
  2642. case AlphaMode.Opaque:
  2643. {
  2644. if( m_renderType == RenderType.Opaque && m_renderQueue == RenderQueue.Geometry )
  2645. return false;
  2646. }
  2647. break;
  2648. case AlphaMode.Masked:
  2649. {
  2650. if( m_renderType == RenderType.TransparentCutout && m_renderQueue == RenderQueue.AlphaTest )
  2651. return false;
  2652. }
  2653. break;
  2654. case AlphaMode.Transparent:
  2655. case AlphaMode.Premultiply:
  2656. {
  2657. if( m_renderType == RenderType.Transparent && m_renderQueue == RenderQueue.Transparent )
  2658. return false;
  2659. }
  2660. break;
  2661. case AlphaMode.Translucent:
  2662. {
  2663. if( m_renderType == RenderType.Opaque && m_renderQueue == RenderQueue.Transparent )
  2664. return false;
  2665. }
  2666. break;
  2667. }
  2668. return true;
  2669. }
  2670. private void UpdateFromBlendMode()
  2671. {
  2672. m_checkChanges = true;
  2673. bool lockRefractionPort = false;
  2674. if( m_currentLightModel == StandardShaderLightModel.Unlit || m_currentLightModel == StandardShaderLightModel.CustomLighting )
  2675. {
  2676. lockRefractionPort = true;
  2677. }
  2678. switch( m_alphaMode )
  2679. {
  2680. case AlphaMode.Opaque:
  2681. {
  2682. m_renderType = RenderType.Opaque;
  2683. m_renderQueue = RenderQueue.Geometry;
  2684. m_keepAlpha = true;
  2685. m_refractionPort.Locked = true;
  2686. m_inputPorts[ m_opacityPortId ].Locked = true;
  2687. m_inputPorts[ m_discardPortId ].Locked = true;
  2688. }
  2689. break;
  2690. case AlphaMode.Masked:
  2691. {
  2692. m_renderType = RenderType.TransparentCutout;
  2693. m_renderQueue = RenderQueue.AlphaTest;
  2694. m_keepAlpha = true;
  2695. m_refractionPort.Locked = true;
  2696. m_inputPorts[ m_opacityPortId ].Locked = true;
  2697. m_inputPorts[ m_discardPortId ].Locked = false;
  2698. }
  2699. break;
  2700. case AlphaMode.Transparent:
  2701. case AlphaMode.Premultiply:
  2702. {
  2703. m_renderType = RenderType.Transparent;
  2704. m_renderQueue = RenderQueue.Transparent;
  2705. m_refractionPort.Locked = false || lockRefractionPort;
  2706. m_inputPorts[ m_opacityPortId ].Locked = false;
  2707. m_inputPorts[ m_discardPortId ].Locked = true;
  2708. }
  2709. break;
  2710. case AlphaMode.Translucent:
  2711. {
  2712. m_renderType = RenderType.Opaque;
  2713. m_renderQueue = RenderQueue.Transparent;
  2714. m_refractionPort.Locked = false || lockRefractionPort;
  2715. m_inputPorts[ m_opacityPortId ].Locked = false;
  2716. m_inputPorts[ m_discardPortId ].Locked = true;
  2717. }
  2718. break;
  2719. case AlphaMode.Custom:
  2720. {
  2721. m_refractionPort.Locked = false || lockRefractionPort;
  2722. m_inputPorts[ m_opacityPortId ].Locked = false;
  2723. m_inputPorts[ m_discardPortId ].Locked = false;
  2724. }
  2725. break;
  2726. }
  2727. m_blendOpsHelper.SetBlendOpsFromBlendMode( m_alphaMode, ( m_alphaMode == AlphaMode.Custom || m_alphaMode == AlphaMode.Opaque ) );
  2728. }
  2729. public StandardShaderLightModel CurrentLightingModel { get { return m_currentLightModel; } }
  2730. public CullMode CurrentCullMode { get { return m_cullMode; } }
  2731. //public AdditionalIncludesHelper AdditionalIncludes { get { return m_additionalIncludes; } set { m_additionalIncludes = value; } }
  2732. //public AdditionalPragmasHelper AdditionalPragmas { get { return m_additionalPragmas; } set { m_additionalPragmas = value; } }
  2733. //public AdditionalDefinesHelper AdditionalDefines { get { return m_additionalDefines; } set { m_additionalDefines = value; } }
  2734. public TemplateAdditionalDirectivesHelper AdditionalDirectives { get { return m_additionalDirectives; } }
  2735. public OutlineOpHelper OutlineHelper { get { return m_outlineHelper; } }
  2736. public float OpacityMaskClipValue { get { return m_opacityMaskClipValue; } }
  2737. public InlineProperty InlineOpacityMaskClipValue { get { return m_inlineOpacityMaskClipValue; } set { m_inlineOpacityMaskClipValue = value; } }
  2738. }
  2739. }