protected override void OnCreate() { var changer = this.Scene.ActiveCamera.Entity.GetComponent <OptionChanger>(); this.enabledProp = this.Shader.GetProperty <bool>("enabled"); changer.AddOption(new SimpleBoolOption("Use SSR", true, (bool value) => { this.Shader.Set(enabledProp, value); })); }
public static void SetProperty(this ComputeShader shader, ShaderProperty property) { switch (property.Type) { case ShaderProperty.PropertyType.Float: shader.SetFloat(property.Id, property.FloatValue); break; case ShaderProperty.PropertyType.Int: shader.SetInt(property.Id, property.IntValue); break; case ShaderProperty.PropertyType.Vector: shader.SetVector(property.Id, property.VectorValue); break; case ShaderProperty.PropertyType.Bool: shader.SetBool(property.Id, property.BoolValue); break; case ShaderProperty.PropertyType.Matrix: shader.SetMatrix(property.Id, property.MatrixValue); break; case ShaderProperty.PropertyType.Texture: shader.SetTexture(property.KernelIndex, property.Id, property.TextureValue); break; default: throw new ArgumentOutOfRangeException(); } }
protected override void OnCreate() { var resourceManager = ResourceManager.Instance; var scene = this.Scene; var shader = this.Shader; var noiseTexture = PrefabGenerator.GenerateNoiseTexture(4, 4); var noiseTextureProp = shader.GetProperty <Texture>("noiseTexture"); shader.Set(noiseTextureProp, noiseTexture); screenWidthProp = shader.GetProperty <int>("screenWidth"); screenHeightProp = shader.GetProperty <int>("screenHeight"); // SetKernelSize(64); var changer = this.Scene.ActiveCamera.Entity.GetComponent <OptionChanger>(); this.radiusProp = this.Shader.GetProperty <float>("radius"); changer.AddOption(new SimpleFloatOption("SSAO Radius", 0.5f, 0.01f, 5.0f, 0.01f, (float value) => { this.Shader.Set(this.radiusProp, value); })); this.powerRadius = this.Shader.GetProperty <float>("power"); changer.AddOption(new SimpleFloatOption("SSAO Power", 2.0f, 0.1f, 20.0f, 0.1f, (float value) => { this.Shader.Set(this.powerRadius, value); })); kernelSizeProp = this.Shader.GetProperty <int>("kernelSize"); changer.AddOption(new SimpleIntOption("SSAO Kernel Size", 16, 1, 128, 1, SetKernelSize)); this.enabledProp = this.Shader.GetProperty <bool>("enabled"); changer.AddOption(new SimpleBoolOption("Use SSAO", true, (bool value) => { this.Shader.Set(enabledProp, value); })); }
void Start() { m_Range = 16.0f; m_RangeR = 1.0f / m_Range; m_Vertex_r = new Vector3[SNOW_NUM * VERTEX_NUM]; for (int i = 0; i < SNOW_NUM; i++) { int _Idx = i * VERTEX_NUM; Vector3 _Point = new Vector3(makeRandom(), makeRandom(), makeRandom()); m_Vertex_r[_Idx] = _Point; m_Vertex_r[_Idx + 1] = _Point; m_Vertex_r[_Idx + 2] = _Point; m_Vertex_r[_Idx + 3] = _Point; } m_Triangle_r = new int[SNOW_NUM * 6]; for (int i = 0; i < SNOW_NUM; i++) { int _Idx = i * 6; int _IdxVertex = i * VERTEX_NUM; // Polygon 1 m_Triangle_r[_Idx] = _IdxVertex; m_Triangle_r[_Idx + 1] = _IdxVertex + 1; m_Triangle_r[_Idx + 2] = _IdxVertex + 2; // Polygon 2 m_Triangle_r[_Idx + 3] = _IdxVertex + 2; m_Triangle_r[_Idx + 4] = _IdxVertex + 1; m_Triangle_r[_Idx + 5] = _IdxVertex + 3; } m_UV_r = new Vector2[SNOW_NUM * VERTEX_NUM]; for (int i = 0; i < SNOW_NUM; i++) { int _Idx = i * VERTEX_NUM; m_UV_r[_Idx] = new Vector2(0.0f, 0.0f); m_UV_r[_Idx + 1] = new Vector2(1.0f, 0.0f); m_UV_r[_Idx + 2] = new Vector2(0.0f, 1.0f); m_UV_r[_Idx + 3] = new Vector2(1.0f, 1.0f); } Mesh _Mesh = new Mesh(); _Mesh.name = "MeshSnowFlake"; _Mesh.vertices = m_Vertex_r; _Mesh.triangles = m_Triangle_r; _Mesh.uv = m_UV_r; _Mesh.bounds = new Bounds(Vector3.zero, Vector3.one * 99999999); MeshFilter _Filter = GetComponent <MeshFilter> (); _Filter.sharedMesh = _Mesh; m_Material = GetComponent <Renderer> ().material; m_ShaderProperty = new ShaderProperty(); m_ShaderProperty._IdTargetPosition = Shader.PropertyToID("_TargetPosition"); m_ShaderProperty._IdRange = Shader.PropertyToID("_Range"); m_ShaderProperty._IdRangeR = Shader.PropertyToID("_RangeR"); m_ShaderProperty._IdSize = Shader.PropertyToID("_Size"); m_ShaderProperty._IdMoveTotal = Shader.PropertyToID("_MoveTotal"); m_ShaderProperty._IdCamUp = Shader.PropertyToID("_CamUp"); }
void Start() { ShaderParamsProperty = new ShaderProperty("_ShaderParams"); SearchCenterProperty = new ShaderProperty("_SearchCenter"); SearchExtentsProperty = new ShaderProperty("_SearchExtents"); objectTracker = FindObjectOfType <ObjectTracker>(); searchAreaController = FindObjectOfType <SearchAreaController>(); }
public void ExposeProperties() { int l = ShaderUtil.GetPropertyCount(material.shader); properties = new ShaderProperty[l]; for (int i = 0; i < l; ++i) { properties[i] = ShaderProperty.Get(material, i); } }
protected override void OnCreate() { var changer = this.Scene.ActiveCamera.Entity.GetComponent <OptionChanger>(); this.enabledProp = this.Shader.GetProperty <bool>("enabled"); changer.AddOption(new SimpleBoolOption("Use Bloom", true, (bool value) => { this.Shader.Set(this.enabledProp, value); })); this.thresholdProp = this.Shader.GetProperty <float>("threshold"); changer.AddOption(new SimpleFloatOption("Bloom Threshold", 1.0f, 0.0f, 5.0f, 0.01f, (float value) => { this.Shader.Set(this.thresholdProp, value); })); }
public void CopyFrom([CanBeNull] ShaderProperty property) { if (property == null) { return; } Name = property.Name; ValueA = property.ValueA; ValueB = property.ValueB?.ToArray(); ValueC = property.ValueC?.ToArray(); ValueD = property.ValueD?.ToArray(); }
//function to handle the drawing of header or property void drawShaderPart(ShaderPart part, MaterialEditor materialEditor) { if (part is ShaderHeader) { ShaderHeader header = (ShaderHeader)part; drawShaderHeader(header, materialEditor); } else { ShaderProperty property = (ShaderProperty)part; drawShaderProperty(property, materialEditor); } }
public CustomMaterialProperty(ShaderProperty sp, Type implementationType) { implementation = (Imp_MaterialProperty)Activator.CreateInstance(implementationType, new object[] { sp }); var menuLabel = implementationType.GetProperty("MenuLabel", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); string label = (string)menuLabel.GetValue(null, null); label = label.Replace("Material Property/", ""); implementation.PropertyName = string.Format("_{0}", SGUILayout.Utils.RemoveWhitespaces("My " + label)); implementation.Label = SGUILayout.Utils.VariableNameToReadable(implementation.PropertyName); implementation.IsCustomMaterialProperty = true; implementationTypeLabel = label; }
//-------------Init functions-------------------- //finds all properties and headers and stores them in correct order private void CollectAllProperties(MaterialProperty[] props, MaterialEditor materialEditor) { shaderparts = new ShaderHeader(); Stack <ShaderHeader> headerStack = new Stack <ShaderHeader>(); headerStack.Push(shaderparts); headerStack.Push(shaderparts); footer = new List <string>(); textureFieldsCount = 0; int headerCount = 0; for (int i = 0; i < props.Length; i++) { if (props[i].name.StartsWith("m_end") && props[i].flags == MaterialProperty.PropFlags.HideInInspector) { headerStack.Pop(); headerCount--; } else if (props[i].name.StartsWith("m_start") && props[i].flags == MaterialProperty.PropFlags.HideInInspector) { headerCount++; ShaderHeader newHeader = new ShaderHeader(props[i], materialEditor, headerCount); headerStack.Peek().addPart(newHeader); headerStack.Push(newHeader); } else if (props[i].name.StartsWith("m_") && props[i].flags == MaterialProperty.PropFlags.HideInInspector) { ShaderHeader newHeader = new ShaderHeader(props[i], materialEditor, headerCount); headerStack.Pop(); headerStack.Peek().addPart(newHeader); headerStack.Push(newHeader); } else if (props[i].name.StartsWith("footer_") && props[i].flags == MaterialProperty.PropFlags.HideInInspector) { footer.Add(props[i].displayName); } else if (props[i].flags != MaterialProperty.PropFlags.HideInInspector) { int extraOffset = 0; extraOffset = PoiHelper.propertyOptionToInt(EXTRA_OFFSET_OPTION, props[i]); string displayName = props[i].displayName.Replace("-" + EXTRA_OFFSET_OPTION + "=" + extraOffset, ""); ShaderProperty newPorperty = new ShaderProperty(props[i], displayName, headerCount + extraOffset); headerStack.Peek().addPart(newPorperty); if (props[i].type == MaterialProperty.PropType.Texture) { textureFieldsCount++; } } } }
public MaterialLayer() { uid = GenerateUID(); sourceShaderProperty = new ShaderProperty("layer_" + uid, ShaderProperty.VariableType.@float); sourceShaderProperty.materialLayerUid = uid; sourceShaderProperty.SetDefaultImplementations(new ShaderProperty.Implementation[] { new ShaderProperty.Imp_MaterialProperty_Texture(sourceShaderProperty) { Label = "Source Texture" } }); sourceShaderProperty.DisplayName = uid + " Source"; }
static MaterialLayer Deserialize(string data, object[] args) { var materialLayer = new MaterialLayer(); // custom callback for ShaderProperty Func <object, string, object> onDeserializeShaderProperty = (spObj, spData) => { if (spData == "__NULL__") { return(null); } // HACK figure out which property is being deserialized based on name // substring(11) will strip: sp(name:" ShaderProperty targetProperty = materialLayer.sourceShaderProperty; if (spData.Substring(9).StartsWith("contrast_")) { // Can't deserialize to null, so we need to create the Shader Property first materialLayer.contrastProperty = new ShaderProperty("temp_contrast", ShaderProperty.VariableType.@float); targetProperty = materialLayer.contrastProperty; } if (spData.Substring(9).StartsWith("noise_")) { // Can't deserialize to null, so we need to create the Shader Property first materialLayer.noiseProperty = new ShaderProperty("temp_noise", ShaderProperty.VariableType.@float); targetProperty = materialLayer.noiseProperty; } if (targetProperty == null) { return(null); } // custom callback for Implementations Func <object, string, object> onDeserializeImplementation = (impObj, impData) => { return(ShaderGenerator2.CurrentConfig.DeserializeImplementationHandler(impObj, impData, targetProperty)); }; var implementationHandling = new Dictionary <Type, Func <object, string, object> > { { typeof(ShaderProperty.Implementation), onDeserializeImplementation } }; return(Serialization.DeserializeTo(targetProperty, spData, typeof(ShaderProperty), null, implementationHandling)); }; var shaderPropertyHandling = new Dictionary <Type, Func <object, string, object> > { { typeof(ShaderProperty), onDeserializeShaderProperty } }; return((MaterialLayer)Serialization.DeserializeTo(materialLayer, data, typeof(MaterialLayer), null, shaderPropertyHandling)); }
protected override void OnCreate() { var changer = this.Scene.ActiveCamera.Entity.GetComponent <OptionChanger>(); this.exposureProp = this.Shader.GetProperty <float>("exposure"); changer.AddOption(new SimpleFloatOption("Exposure", 1.1f, 0.1f, 5.0f, 0.01f, (float value) => { this.Shader.Set(this.exposureProp, value); })); this.gammaProp = this.Shader.GetProperty <float>("gamma"); changer.AddOption(new SimpleFloatOption("Gamma", 2.2f, 0.1f, 5.0f, 0.01f, (float value) => { this.Shader.Set(this.gammaProp, value); })); this.drawImageProp = this.Shader.GetProperty <int>("drawImage"); changer.AddOption(new GenericOption <DrawImage>("Draw Image", DrawImageHandler, DrawImage.Normal)); }
internal static bool AddMaterialProperty( ref MaterialContext context, Material material, ShaderValue sv, List <ShaderProperty> shaderPropertyKey) { if (sv.name == "_Cutoff" || sv.name == "_SrcBlend" || sv.name == "_DstBlend" || sv.name == "_ZWrite" || sv.name == "_DebugMode") { return(false); } ShaderProperty sp = shaderPropertyKey.Find((x) => { return(x.shaderProperty == sv.name); }); if (sp != null) { return(AddMaterialProperty(ref context, material, sp)); } else { if (shaderNameKeys == null) { shaderNameKeys = System.Enum.GetNames(typeof(EShaderKeyID)); for (int i = 0; i < shaderNameKeys.Length; ++i) { shaderNameKeys[i] = "_" + shaderNameKeys[i]; } } for (int i = 0; i < shaderNameKeys.Length; ++i) { if (shaderNameKeys[i] == sv.name) { shareSp.shaderID = i; shareSp.isTex = sv is ShaderTexValue; shareSp.shaderProperty = sv.name; return(AddMaterialProperty(ref context, material, shareSp)); } } Debug.LogErrorFormat("null property:{0} mat:{1}", sv.name, material.name); return(false); } }
private void CollectAllProperties(MaterialProperty[] props, MaterialEditor materialEditor) { shaderparts = new ShaderHeader(null); Stack <ShaderHeader> headerStack = new Stack <ShaderHeader>(); headerStack.Push(shaderparts); headerStack.Push(shaderparts); int headerCount = 0; for (int i = 0; i < props.Length; i++) { //Debug.Log("Name: "+ props[i].name +",Display Name: " +props[i].displayName+ ",flags: "+ props[i].flags+",type: "+props[i].type); if (props[i].name.StartsWith("m_end") && props[i].flags == MaterialProperty.PropFlags.HideInInspector) { headerStack.Pop(); headerCount--; } else if (props[i].name.StartsWith("m_start") && props[i].flags == MaterialProperty.PropFlags.HideInInspector) { //Debug.Log("Header: " + props[i].displayName); headerCount++; ShaderHeader newHeader = new ShaderHeader(props[i], materialEditor, headerCount); headerStack.Peek().addPart(newHeader); headerStack.Push(newHeader); } else if (props[i].name.StartsWith("m_") && props[i].flags == MaterialProperty.PropFlags.HideInInspector) { //Debug.Log("Header: " + props[i].displayName); ShaderHeader newHeader = new ShaderHeader(props[i], materialEditor, headerCount); headerStack.Pop(); headerStack.Peek().addPart(newHeader); headerStack.Push(newHeader); } else if (props[i].flags != MaterialProperty.PropFlags.HideInInspector) { //Debug.Log("Property: " + props[i].displayName); int extraOffset = 0; extraOffset = propertyOptionToInt(EXTRA_OFFSET_OPTION, props[i]); string displayName = props[i].displayName.Replace("-" + EXTRA_OFFSET_OPTION + "=" + extraOffset, ""); ShaderProperty newPorperty = new ShaderProperty(props[i], displayName, headerCount + extraOffset); headerStack.Peek().addPart(newPorperty); } } }
static CustomMaterialProperty Deserialize(string data, object[] args) { ShaderProperty shaderProperty = ShaderGenerator2.CurrentConfig.customMaterialPropertyShaderProperty; // find the class name of the implementation, as it is needed to create an instance of CustomMaterialProperty string serializedClassName = data.Substring(data.IndexOf("cimp:") + "cimp:".Length); serializedClassName = serializedClassName.Substring(0, serializedClassName.IndexOf('(')); Type implementationType = null; var allTypes = typeof(Serialization).Assembly.GetTypes(); foreach (var t in allTypes) { var classAttributes = t.GetCustomAttributes(typeof(Serialization.SerializeAsAttribute), false); if (classAttributes != null && classAttributes.Length == 1) { var name = (classAttributes[0] as Serialization.SerializeAsAttribute).serializedName; if (name == serializedClassName) { //match! implementationType = t; } } } var customMaterialProperty = new CustomMaterialProperty(shaderProperty, implementationType); Func <object, string, object> onDeserializeImplementation = (impObj, impData) => { // Make sure to deserialize as a new object, so that final Implementation subtype is kept instead of creating base Implementation class // Imp should only be an Imp_MaterialProperty var imp = Serialization.Deserialize(impData, new object[] { shaderProperty }); return(imp); }; var implementationHandling = new Dictionary <Type, Func <object, string, object> > { { typeof(Imp_MaterialProperty), onDeserializeImplementation } }; Serialization.DeserializeTo(customMaterialProperty, data, typeof(CustomMaterialProperty), args, implementationHandling); return(customMaterialProperty); }
public static void SetProperty(this Material material, ShaderProperty property) { switch (property.Type) { case ShaderProperty.PropertyType.Float: material.SetFloat(property.Id, property.FloatValue); break; case ShaderProperty.PropertyType.Int: material.SetInt(property.Id, property.IntValue); break; case ShaderProperty.PropertyType.Vector: material.SetVector(property.Id, property.VectorValue); break; case ShaderProperty.PropertyType.Color: material.SetColor(property.Id, property.ColorValue); break; case ShaderProperty.PropertyType.Matrix: material.SetMatrix(property.Id, property.MatrixValue); break; case ShaderProperty.PropertyType.Texture: material.SetTexture(property.Id, property.TextureValue); break; case ShaderProperty.PropertyType.TextureScale: material.SetTextureScale(property.Id, property.TextureOffsetValue); break; case ShaderProperty.PropertyType.TextureOffset: material.SetTextureOffset(property.Id, property.TextureScaleValue); break; default: throw new ArgumentOutOfRangeException(); } }
public AdvancedShader(Shader _shader) { if (_shader == null) { throw new Exception("[ShaderUtility] Couldnt find shader with name"); } // Initialize ShaderName = _shader.name; ShaderPropertyList = new List <ShaderProperty>(); // Iterate through properties int _propertyCount = ShaderUtil.GetPropertyCount(_shader); for (int _iter = 0; _iter < _propertyCount; _iter++) { ShaderProperty _property = new ShaderProperty(ShaderUtil.GetPropertyName(_shader, _iter), ShaderUtil.GetPropertyType(_shader, _iter)); // Add it to list ShaderPropertyList.Add(_property); } }
protected override void OnCreate() { var changer = this.Scene.ActiveCamera.Entity.GetComponent <OptionChanger>(); // this.useSSAOProp = this.Shader.GetProperty<bool>("useSSAO"); // changer.AddOption(new SimpleBoolOption("Use SSAO", true, (bool value) => { this.Shader.Set(useSSAOProp, value); })); this.usePCFProp = this.Shader.GetProperty <bool>("usePCF"); changer.AddOption(new SimpleBoolOption("Use PCF", true, (bool value) => { this.Shader.Set(usePCFProp, value); })); this.useRaysProp = this.Shader.GetProperty <bool>("useRays"); changer.AddOption(new SimpleBoolOption("Use Rays", true, (bool value) => { this.Shader.Set(useRaysProp, value); })); this.directionalPCFSamplesProp = this.Shader.GetProperty <int>("directionalPCFSamples"); changer.AddOption(new SimpleIntOption("Directional PCF Samples", 8, 1, 32, 1, (int value) => { this.Shader.Set(directionalPCFSamplesProp, value); })); this.pointPCFSamplesProp = this.Shader.GetProperty <int>("pointPCFSamples"); changer.AddOption(new SimpleIntOption("Point PCF Samples", 4, 1, 32, 1, (int value) => { this.Shader.Set(pointPCFSamplesProp, value); })); this.directionalBiasProp = this.Shader.GetProperty <float>("directionalBias"); changer.AddOption(new SimpleFloatOption("Directional bias", 1, 0, 10, 0.01f, (float value) => { this.Shader.Set(directionalBiasProp, value); })); }
void drawShaderProperty(ShaderProperty property, MaterialEditor materialEditor) { //materialEditor.ShaderProperty(property.materialProperty, property.style); if (property.materialProperty.type == MaterialProperty.PropType.Texture) { int oldIndentLevel = EditorGUI.indentLevel; EditorGUI.indentLevel = property.xOffset * 2 + 1; Rect rect = materialEditor.TexturePropertySingleLine(new GUIContent(property.materialProperty.displayName, "Click here for scale / offset"), property.materialProperty); var e = Event.current; bool value = false; if (e.type == EventType.MouseDown && rect.Contains(e.mousePosition)) { if (showTextureScaleOffset.TryGetValue(property.materialProperty.name, out value)) { showTextureScaleOffset.Remove(property.materialProperty.name); } value = !value; showTextureScaleOffset.Add(property.materialProperty.name, value); e.Use(); } if (!showTextureScaleOffset.TryGetValue(property.materialProperty.name, out value)) { value = false; } if (value) { materialEditor.TextureScaleOffsetProperty(property.materialProperty); } EditorGUI.indentLevel = oldIndentLevel; } else { materialEditor.ShaderProperty(property.materialProperty, property.style.text, property.xOffset * 2 + 1); } }
public ShaderInfo(Shader _shader) { if (_shader == null) { throw new Exception("[ShaderUtility] Couldnt find shader with name"); } // Initialize Name = _shader.name; PropertyList = new List <ShaderProperty>(); // Iterate through properties int _propertyCount = ShaderUtil.GetPropertyCount(_shader); for (int _iter = 0; _iter < _propertyCount; _iter++) { string _propertyName = ShaderUtil.GetPropertyName(_shader, _iter); ShaderUtil.ShaderPropertyType _propertyType = ShaderUtil.GetPropertyType(_shader, _iter); ShaderProperty _newProperty = new ShaderProperty(_propertyName, _propertyType); // Add it to list PropertyList.Add(_newProperty); } }
private IEnumerator ShaderEventCoroutine(ShaderProperty property, float startTime, float duration, Functions easing) { if (property == null) { Logger.log.Error("ShaderEventCoroutine received null ShaderProperty!"); yield return(null); } while (true) { float elapsedTime = _customEventCallbackController._audioTimeSource.songTime - startTime; float time = Easings.Interpolate(Mathf.Min(elapsedTime / duration, 1f), easing); PointDefinition points = property.Points; if (points != null) { switch (property.PropertyType) { case PropertyType.Linear: property.SetValue(points.InterpolateLinear(time)); break; case PropertyType.Vector3: property.Value = points.Interpolate(time); break; case PropertyType.Vector4: property.Value = points.InterpolateVector4(time); break; case PropertyType.Quaternion: property.Value = points.InterpolateQuaternion(time); break; } } else { Logger.log.Error("ShaderEventCoroutine: ShaderCommand with id \"" + property.ParentCommand.ID + "\" and _ref \"" + property.ParentCommand.ReferenceName + "\" has invalid points at \"" + property.Property + "\"!"); } if (elapsedTime < duration) { yield return(null); } else { break; } } if (property.IsLast && property.ParentCommand.ClearAfterLastPropIsDone) { if (!_shaderManager.RemoveMaterial(property.ParentCommand.ID, property.ParentCommand.ShaderEffectData)) { Logger.log.Error($"Tried to remove a Shader with an ID that doesn't exist: '{property.ParentCommand.ID}' at time (in beats) {_customEventCallbackController._audioTimeSource.songTime / 60 * _beatmapObjectSpawnController.currentBpm}!"); } StopAllCoroutinesModifyingMaterials(new List <Material>() { property.ParentCommand.Material }); Logger.log.Debug($"Material removed after last property stopped animating! ID: {property.ParentCommand.ID} - ref: {property.ParentCommand.ReferenceName}"); } }
//finds all properties and headers and stores them in correct order private void CollectAllProperties() { //load display names from file if it exists MaterialProperty[] props = current.properties; Dictionary <string, string> labels = LoadDisplayNamesFromFile(); LoadLocales(); current.propertyDictionary = new Dictionary <string, ShaderProperty>(); shaderparts = new ShaderHeader(); //init top object that all Shader Objects are childs of Stack <ShaderGroup> headerStack = new Stack <ShaderGroup>(); //header stack. used to keep track if current header to parent new objects to headerStack.Push(shaderparts); //add top object as top object to stack headerStack.Push(shaderparts); //add top object a second time, because it get's popped with first actual header item footer = new List <ButtonData>(); //init footer list int headerCount = 0; Type materialPropertyDrawerType = typeof(UnityEditor.Editor).Assembly.GetType("UnityEditor.MaterialPropertyHandler"); MethodInfo getPropertyHandlerMethod = materialPropertyDrawerType.GetMethod("GetShaderPropertyHandler", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); PropertyInfo drawerProperty = materialPropertyDrawerType.GetProperty("propertyDrawer"); Type materialToggleDrawerType = typeof(UnityEditor.Editor).Assembly.GetType("UnityEditor.MaterialToggleDrawer"); FieldInfo keyWordField = materialToggleDrawerType.GetField("keyword", BindingFlags.Instance | BindingFlags.NonPublic); for (int i = 0; i < props.Length; i++) { string displayName = props[i].displayName; if (locale != null) { foreach (string key in locale.GetAllKeys()) { if (displayName.Contains("locale::" + key)) { displayName = displayName.Replace("locale::" + key, locale.Get(key)); } } } displayName = Regex.Replace(displayName, @"''", "\""); if (labels.ContainsKey(props[i].name)) { displayName = labels[props[i].name]; } PropertyOptions options = ExtractExtraOptionsFromDisplayName(ref displayName); int offset = options.offset + headerCount; //Handle keywords object propertyHandler = getPropertyHandlerMethod.Invoke(null, new object[] { current.shader, props[i].name }); //if has custom drawer if (propertyHandler != null) { object propertyDrawer = drawerProperty.GetValue(propertyHandler, null); //if custom drawer exists if (propertyDrawer != null) { if (propertyDrawer.GetType().ToString() == "UnityEditor.MaterialToggleDrawer") { object keyword = keyWordField.GetValue(propertyDrawer); if (keyword != null) { foreach (Material m in current.materials) { if (m.GetFloat(props[i].name) == 1) { m.EnableKeyword((string)keyword); } else { m.DisableKeyword((string)keyword); } } } } } } ThryPropertyType type = GetPropertyType(props[i], options); switch (type) { case ThryPropertyType.header: headerStack.Pop(); break; case ThryPropertyType.header_start: offset = options.offset + ++headerCount; break; case ThryPropertyType.header_end: headerStack.Pop(); headerCount--; break; case ThryPropertyType.on_swap_to: on_swap_to_actions = options.actions; break; } ShaderProperty newPorperty = null; switch (type) { case ThryPropertyType.master_label: masterLabelText = displayName; break; case ThryPropertyType.footer: footer.Add(Parser.ParseToObject <ButtonData>(displayName)); break; case ThryPropertyType.header: case ThryPropertyType.header_start: ShaderHeader newHeader = new ShaderHeader(props[i], current.editor, displayName, offset, options); headerStack.Peek().addPart(newHeader); headerStack.Push(newHeader); break; case ThryPropertyType.group_start: ShaderGroup new_group = new ShaderGroup(options); headerStack.Peek().addPart(new_group); headerStack.Push(new_group); break; case ThryPropertyType.group_end: headerStack.Pop(); break; case ThryPropertyType.none: case ThryPropertyType.property: DrawingData.lastPropertyUsedCustomDrawer = false; current.editor.GetPropertyHeight(props[i]); bool forceOneLine = props[i].type == MaterialProperty.PropType.Vector && !DrawingData.lastPropertyUsedCustomDrawer; if (props[i].type == MaterialProperty.PropType.Texture) { newPorperty = new TextureProperty(props[i], displayName, offset, options, props[i].flags != MaterialProperty.PropFlags.NoScaleOffset, !DrawingData.lastPropertyUsedCustomDrawer); } else { newPorperty = new ShaderProperty(props[i], displayName, offset, options, forceOneLine); } break; case ThryPropertyType.lightmap_flags: newPorperty = new GIProperty(props[i], displayName, offset, options, false); break; case ThryPropertyType.dsgi: newPorperty = new DSGIProperty(props[i], displayName, offset, options, false); break; case ThryPropertyType.instancing: newPorperty = new InstancingProperty(props[i], displayName, offset, options, false); break; case ThryPropertyType.locale: newPorperty = new LocaleProperty(props[i], displayName, offset, options, false); break; } if (newPorperty != null) { if (current.propertyDictionary.ContainsKey(props[i].name)) { continue; } current.propertyDictionary.Add(props[i].name, newPorperty); if (type != ThryPropertyType.none) { headerStack.Peek().addPart(newPorperty); } } } }
//finds all properties and headers and stores them in correct order private void CollectAllProperties() { //load display names from file if it exists MaterialProperty[] props = current.properties; Dictionary <string, string> labels = LoadDisplayNamesFromFile(); current.propertyDictionary = new Dictionary <string, ShaderProperty>(); shaderparts = new ShaderHeader(); //init top object that all Shader Objects are childs of Stack <ShaderHeader> headerStack = new Stack <ShaderHeader>(); //header stack. used to keep track if current header to parent new objects to headerStack.Push(shaderparts); //add top object as top object to stack headerStack.Push(shaderparts); //add top object a second time, because it get's popped with first actual header item footer = new List <ButtonData>(); //init footer list int headerCount = 0; for (int i = 0; i < props.Length; i++) { string displayName = props[i].displayName; displayName = Regex.Replace(displayName, @"''", "\""); if (labels.ContainsKey(props[i].name)) { displayName = labels[props[i].name]; } PropertyOptions options = ExtractExtraOptionsFromDisplayName(ref displayName); int offset = options.offset + headerCount; ThryPropertyType type = GetPropertyType(props[i]); switch (type) { case ThryPropertyType.header: headerStack.Pop(); break; case ThryPropertyType.header_start: offset = options.offset + ++headerCount; break; case ThryPropertyType.header_end: headerStack.Pop(); headerCount--; break; } switch (type) { case ThryPropertyType.footer: footer.Add(Parser.ParseToObject <ButtonData>(displayName)); break; case ThryPropertyType.header: case ThryPropertyType.header_start: ShaderHeader newHeader = new ShaderHeader(props[i], current.editor, displayName, offset, options); headerStack.Peek().addPart(newHeader); headerStack.Push(newHeader); break; case ThryPropertyType.property: ShaderProperty newPorperty = null; DrawingData.lastPropertyUsedCustomDrawer = false; current.editor.GetPropertyHeight(props[i]); bool forceOneLine = props[i].type == MaterialProperty.PropType.Vector && !DrawingData.lastPropertyUsedCustomDrawer; if (props[i].type == MaterialProperty.PropType.Texture) { newPorperty = new TextureProperty(props[i], displayName, offset, options, props[i].flags != MaterialProperty.PropFlags.NoScaleOffset, !DrawingData.lastPropertyUsedCustomDrawer); } else { newPorperty = new ShaderProperty(props[i], displayName, offset, options, forceOneLine); } headerStack.Peek().addPart(newPorperty); current.propertyDictionary.Add(props[i].name, newPorperty); break; case ThryPropertyType.lightmap_flags: current.draw_material_option_lightmap = true; break; case ThryPropertyType.dsgi: current.draw_material_option_dsgi = true; break; case ThryPropertyType.instancing: current.draw_material_option_instancing = true; break; } } }
//-------------Init functions-------------------- //finds all properties and headers and stores them in correct order private void CollectAllProperties() { //load display names from file if it exists MaterialProperty label_file_property = null; MaterialProperty[] props = current.properties; foreach (MaterialProperty m in props) { if (m.name == "shader_properties_label_file") { label_file_property = m; } } Dictionary <string, string> labels = new Dictionary <string, string>(); if (label_file_property != null) { string[] guids = AssetDatabase.FindAssets(label_file_property.displayName); if (guids.Length == 0) { Debug.LogError("Label File could not be found"); } string path = AssetDatabase.GUIDToAssetPath(guids[0]); string[] data = Regex.Split(Helper.ReadFileIntoString(path), @"\r?\n"); foreach (string d in data) { string[] set = Regex.Split(d, ":="); if (set.Length > 1) { labels[set[0]] = set[1]; } } } shaderparts = new ShaderHeader(); //init top object that all Shader Objects are childs of Stack <ShaderHeader> headerStack = new Stack <ShaderHeader>(); //header stack. used to keep track if current header to parent new objects to headerStack.Push(shaderparts); //add top object as top object to stack headerStack.Push(shaderparts); //add top object a second time, because it get's popped with first actual header item footer = new List <string>(); //init footer list int headerCount = 0; for (int i = 0; i < props.Length; i++) { //if property is a footer add to footer list if (props[i].name.StartsWith("footer_") && props[i].flags == MaterialProperty.PropFlags.HideInInspector) { footer.Add(props[i].displayName); //if property is end if a header block pop the top header } else if (props[i].name.StartsWith("m_end") && props[i].flags == MaterialProperty.PropFlags.HideInInspector) { headerStack.Pop(); headerCount--; } else //else add new object under current header { //get the display name out of property or file string displayName = props[i].displayName; if (labels.ContainsKey(props[i].name)) { displayName = labels[props[i].name]; } string ogDisplayName = displayName; //extract offset int extraOffset = Helper.propertyOptionToInt(EXTRA_OFFSET_OPTION, ogDisplayName); int offset = extraOffset + headerCount; displayName = displayName.Replace(EXTRA_OPTION_PREFIX + EXTRA_OFFSET_OPTION + EXTRA_OPTION_INFIX + extraOffset, ""); //extract on hover string onHover = Helper.getPropertyOptionValue(HOVER_OPTION, ogDisplayName); displayName = displayName.Replace(EXTRA_OPTION_PREFIX + HOVER_OPTION + EXTRA_OPTION_INFIX + onHover, ""); //extract alt click string altClick = Helper.getPropertyOptionValue(ON_ALT_CLICK_OPTION, ogDisplayName); displayName = displayName.Replace(EXTRA_OPTION_PREFIX + ON_ALT_CLICK_OPTION + EXTRA_OPTION_INFIX + altClick, ""); //if property is submenu add 1 extra offset if (props[i].name.StartsWith("m_start") && props[i].flags == MaterialProperty.PropFlags.HideInInspector) { offset = extraOffset + ++headerCount; } //if property is normal menu pop out if old header else if (props[i].name.StartsWith("m_") && props[i].flags == MaterialProperty.PropFlags.HideInInspector) { headerStack.Pop(); } //if proeprty is submenu or normal menu push in header stack if (props[i].name.StartsWith("m_") && props[i].flags == MaterialProperty.PropFlags.HideInInspector) { ShaderHeader newHeader = new ShaderHeader(props[i], current.editor, displayName, offset, onHover, altClick); headerStack.Peek().addPart(newHeader); headerStack.Push(newHeader); } //if property is actual property and not hidden add under current header else if (props[i].flags != MaterialProperty.PropFlags.HideInInspector) { ShaderProperty newPorperty = null; DrawingData.lastPropertyUsedCustomDrawer = false; current.editor.GetPropertyHeight(props[i]); if (props[i].type == MaterialProperty.PropType.Texture) { newPorperty = new TextureProperty(props[i], displayName, offset, onHover, altClick, !DrawingData.lastPropertyUsedCustomDrawer); } else { newPorperty = new ShaderProperty(props[i], displayName, offset, onHover, altClick); } headerStack.Peek().addPart(newPorperty); } } } }
public string PrintVariableSurfaceOutput(VariableType variableType) { return(string.Format("half{0} {1};", ShaderProperty.VariableTypeToChannelsCount(variableType), this.PrintVariableFragment())); }
internal static bool AddMaterialProperty(ref MaterialContext context, Material material, ShaderProperty sp) { if (material.HasProperty(sp.shaderProperty)) { if (sp.isTex) { Texture tex = material.GetTexture(sp.shaderProperty); if (tex != null) { ShaderTexPropertyValue stpv = new ShaderTexPropertyValue() { shaderID = sp.shaderID, value = tex, path = tex.name }; context.textureValue.Add(stpv); return(true); } else { Debug.LogErrorFormat("null tex property:{0} mat:{1}", sp.shaderProperty, material.name); return(false); } } else { Vector4 param = material.GetVector(sp.shaderProperty); ShaderPropertyValue spv = new ShaderPropertyValue() { shaderID = sp.shaderID, value = param, }; context.shaderIDs.Add(spv); return(true); } } return(false); }
internal ShaderProperty[] GetConditionalShaderProperties(ParsedLine[] parsedLines, out Dictionary <int, GUIContent> headers) { headers = new Dictionary <int, GUIContent>(); var shaderPropertiesList = new List <ShaderProperty>(); for (var i = 0; i < parsedLines.Length; i++) { var line = parsedLines[i].line; if (line.StartsWith("#PROPERTIES_NEW")) { while (i < parsedLines.Length) { line = parsedLines[i].line; i++; if (line.StartsWith("#END")) { return(shaderPropertiesList.ToArray()); } if (line.StartsWith("//") || line.StartsWith("#") || string.IsNullOrEmpty(line)) { continue; } if (line.Trim().StartsWith("header")) { var data = line.Split(new string[] { "\t" }, System.StringSplitOptions.RemoveEmptyEntries); var gc = new GUIContent(data[1], data.Length > 2 ? data[2].Trim('\"') : null); if (!headers.ContainsKey(shaderPropertiesList.Count)) { headers.Add(shaderPropertiesList.Count, null); } headers[shaderPropertiesList.Count] = gc; // only take the last one into account, so that empty headers will be ignored continue; } try { var shaderProperty = ShaderProperty.CreateFromTemplateData(line); var match = GetShaderPropertyByName(shaderProperty.Name); if (match == null) { Debug.LogError(ShaderGenerator2.ErrorMsg("Can't find Shader Property in Template, yet it was found for Config")); } else { shaderPropertiesList.Add(match); } } catch (Exception e) { Debug.LogError(ShaderGenerator2.ErrorMsg(string.Format("Parsing error in <b>#PROPERTIES_NEW</b> block:\n'{0}'\n{1}", e.Message, e.StackTrace))); } } } } return(shaderPropertiesList.ToArray()); }
//Get all Shader Properties regardless of conditions, only their visibility will be affected by the Config //This ensures that they are always in the correct order //Also link the pending Imp_ShaderPropertyReferences at this time, if any //and assign the correct pass bitmask based on usage static ShaderProperty[] GetShaderProperties(string[] lines, int i) { var shaderPropertiesList = new List <ShaderProperty>(); string subline; do { subline = lines[i]; i++; if (subline == "#END") { break; } if (subline.Trim().StartsWith("//") || subline.StartsWith("#") || string.IsNullOrEmpty(subline)) { continue; } if (subline.Trim().StartsWith("header")) { continue; } try { var shaderProperty = ShaderProperty.CreateFromTemplateData(subline); shaderPropertiesList.Add(shaderProperty); } catch (Exception e) { Debug.LogError(ShaderGenerator2.ErrorMsg(string.Format("Parsing error in <b>#PROPERTIES_NEW</b> block:\n\nError: '{0}'\n\nLine: '{1}'", e.ToString(), subline))); } }while (subline != "#END" && subline != null); //link shader property references foreach (var shaderProperty in shaderPropertiesList) { if (shaderProperty.implementations != null && shaderProperty.implementations.Count > 0) { foreach (var imp in shaderProperty.implementations) { var impSpRef = imp as ShaderProperty.Imp_ShaderPropertyReference; if (impSpRef != null && !string.IsNullOrEmpty(impSpRef.LinkedShaderPropertyName)) { var match = shaderPropertiesList.Find(sp => sp.Name == impSpRef.LinkedShaderPropertyName); if (match != null) { var channels = impSpRef.Channels; impSpRef.LinkedShaderProperty = match; //restore channels from template data, it's up to the template to match the referenced shader property if (!string.IsNullOrEmpty(channels)) { impSpRef.Channels = channels.ToUpperInvariant(); } impSpRef.ForceUpdateParentDefaultHash(); } else { Debug.LogError(ShaderGenerator2.ErrorMsg(string.Format("Can't find referenced Shader Property in template.\n'{0}' tried to reference '{1}'", shaderProperty.Name, impSpRef.LinkedShaderPropertyName))); } } } } } //iterate rest of template to check usage of each shader property per pass int currentPass = -1; for (; i < lines.Length; i++) { var line = lines[i].Trim(); // update pass if (line.StartsWith("#PASS")) { currentPass++; continue; } // check value usage: used in which pass(es), and which generic implementation they can use var end = 0; while (line.IndexOf("[[", end) >= 0) { var start = line.IndexOf("[[", end); end = line.IndexOf("]]", end + 1); var tag = line.Substring(start + 2, end - start - 2); if (tag.StartsWith("VALUE:") || tag.StartsWith("SAMPLE_VALUE_SHADER_PROPERTY:")) { var propName = tag.Substring(tag.IndexOf(':') + 1); int argsStart = propName.IndexOf('('); if (argsStart > 0) { propName = propName.Substring(0, argsStart); } var sp = shaderPropertiesList.Find(x => x.Name == propName); if (sp != null) { // found used Shader Property sp.AddPassUsage(currentPass); } else { Debug.LogError(ShaderGenerator2.ErrorMsg(string.Format("No match for used Shader Property in code: '<b>{0}</b>'", tag))); } } } } return(shaderPropertiesList.ToArray()); }