コード例 #1
0
        static void OnConsoleConfigCommand(string arguments, object userData)
        {
            EngineConfig.Parameter parameter = (EngineConfig.Parameter)userData;

            if (string.IsNullOrEmpty(arguments))
            {
                object value = parameter.GetValue();
                Print(string.Format("Value: \"{0}\", Default value: \"{1}\"",
                                    value != null ? value : "(null)", parameter.DefaultValue));
                return;
            }

            try
            {
                if (parameter.Field != null)
                {
                    object value = SimpleTypes.ParseValue(parameter.Field.FieldType,
                                                          arguments);
                    if (value == null)
                    {
                        throw new Exception("Not simple type");
                    }
                    parameter.Field.SetValue(null, value);
                }
                else if (parameter.Property != null)
                {
                    object value = SimpleTypes.ParseValue(parameter.Property.PropertyType,
                                                          arguments);
                    if (value == null)
                    {
                        throw new Exception("Not simple type");
                    }
                    parameter.Property.SetValue(null, value, null);
                }
            }
            catch (FormatException e)
            {
                string s = "";
                if (parameter.Field != null)
                {
                    s = parameter.Field.FieldType.ToString();
                }
                else if (parameter.Property != null)
                {
                    s = parameter.Property.PropertyType.ToString();
                }
                Print(string.Format("Config : Invalid parameter format \"{0}\" {1}", s, e.Message), new ColorValue(1, 0, 0));
            }
        }
コード例 #2
0
        static void ParseSettingsFromDefaultSettingsConfig()
        {
            var v = DefaultSettingsConfig.GetAttribute("RendererBackend");

            if (!string.IsNullOrEmpty(v))
            {
                EngineSettings.Init.RendererBackend = (RendererBackend)Enum.Parse(typeof(RendererBackend), v);
            }

            v = DefaultSettingsConfig.GetAttribute("SimulationVSync");
            if (!string.IsNullOrEmpty(v))
            {
                EngineSettings.Init.SimulationVSync = bool.Parse(v);
            }

            v = DefaultSettingsConfig.GetAttribute("SimulationTripleBuffering");
            if (!string.IsNullOrEmpty(v))
            {
                EngineSettings.Init.SimulationTripleBuffering = bool.Parse(v);
            }

            v = DefaultSettingsConfig.GetAttribute("RendererReportDebugToLog");
            if (!string.IsNullOrEmpty(v))
            {
                EngineSettings.Init.RendererReportDebugToLog = (bool)SimpleTypes.ParseValue(typeof(bool), v);
            }

            v = DefaultSettingsConfig.GetAttribute("UseShaderCache");
            if (!string.IsNullOrEmpty(v))
            {
                EngineSettings.Init.UseShaderCache = (bool)SimpleTypes.ParseValue(typeof(bool), v);
            }

            v = DefaultSettingsConfig.GetAttribute("AnisotropicFiltering");
            if (!string.IsNullOrEmpty(v))
            {
                EngineSettings.Init.AnisotropicFiltering = (bool)SimpleTypes.ParseValue(typeof(bool), v);
            }

            v = DefaultSettingsConfig.GetAttribute("SoundSystemDLL");
            if (!string.IsNullOrEmpty(v))
            {
                EngineSettings.Init.SoundSystemDLL = v;
            }

            v = DefaultSettingsConfig.GetAttribute("SoundMaxReal2DChannels");
            if (!string.IsNullOrEmpty(v))
            {
                EngineSettings.Init.SoundMaxReal2DChannels = int.Parse(v);
            }

            v = DefaultSettingsConfig.GetAttribute("SoundMaxReal3DChannels");
            if (!string.IsNullOrEmpty(v))
            {
                EngineSettings.Init.SoundMaxReal3DChannels = int.Parse(v);
            }

            v = DefaultSettingsConfig.GetAttribute("ScriptingCompileProjectSolutionAtStartup");
            if (!string.IsNullOrEmpty(v))
            {
                EngineSettings.Init.ScriptingCompileProjectSolutionAtStartup = bool.Parse(v);
            }

            v = DefaultSettingsConfig.GetAttribute("AutoUnloadTexturesNotUsedForLongTimeInSecondsInEditor");
            if (!string.IsNullOrEmpty(v))
            {
                EngineSettings.Init.AutoUnloadTexturesNotUsedForLongTimeInSecondsInEditor = double.Parse(v);
            }

            v = DefaultSettingsConfig.GetAttribute("AutoUnloadTexturesNotUsedForLongTimeInSecondsInSimulation");
            if (!string.IsNullOrEmpty(v))
            {
                EngineSettings.Init.AutoUnloadTexturesNotUsedForLongTimeInSecondsInSimulation = double.Parse(v);
            }
        }
コード例 #3
0
        protected override void OnRender(ViewportRenderingContext context, Component_RenderingPipeline.IFrameData frameData, ref Component_Image actualTexture)
        {
            var result = Result as CompiledDataSimple;

            //!!!!так?
            if (result == null)
            {
                return;
            }

            if (result.vertexProgram == null || result.fragmentProgram == null)
            {
                return;
            }

            //!!!!валится если файла нет. или не указан.
            //!!!!!!как быстро проверять о том что файла нет? может из кеша шейдеров или типа того. как тогда обновлять
            //string shaderFile = Shader;
            //if( string.IsNullOrEmpty( shaderFile ) )
            //	return;

            //!!!!formats. т.е. эффект поддерживает и LDR и HDR. где еще
            //!!!!!можно по сути у эффекта указывать что он ожидает получить на входе. ну или это EffectsHDR, EffectsLDR
            var outputTexture = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize, actualTexture.Result.ResultFormat);

            context.SetViewport(outputTexture.Result.GetRenderTarget().Viewports[0]);

            CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
            shader.CompiledVertexProgram   = result.vertexProgram;
            shader.CompiledFragmentProgram = result.fragmentProgram;

            //shader.VertexProgramFileName = shaderFile;
            //shader.VertexProgramFunctionName = "main_vp";
            //shader.FragmentProgramFileName = shaderFile;
            //shader.FragmentProgramFunctionName = "main_fp";

            //{
            //	var defines = new List<GuiRenderer.ShaderItem.DefineItem>();

            //	//defines.Add( new GuiRenderer.ShaderItem.DefineItem( "FRAGMENT_CODE_BODY", "color = float4(0,1,0,1);" ) );

            //	if( defines.Count != 0 )
            //		shader.Defines = defines.ToArray();
            //}

            shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0 /*"sourceTexture"*/,
                                                                               actualTexture, TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.Point));
            //shader.Parameters.Set( "0"/*"sourceTexture"*/, new GpuMaterialPass.TextureParameterValue( actualTexture,
            //	TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.Point ) );

            var size = actualTexture.Result.ResultSize;

            shader.Parameters.Set("viewportSize", new Vector4(size.X, size.Y, 1.0 / (double)size.X, 1.0 / (double)size.Y).ToVector4F());

            //!!!!типы
            //bool, int, uint, dword, half, float, double
            //Vec2, Vec3, Vec4, VecxF, Mat2, 3, 4
            //Texture
            //Structs
            //arrays?
            //Structured Buffer
            //byte buffers

            //set shader parameters by properties
            foreach (var m in MetadataGetMembers())
            {
                var p = m as Metadata.Property;
                if (p != null)
                {
                    if (CanBeShaderParameter(this, p, out object value))
                    {
                        Component_Image texture = value as Component_Image;
                        if (texture != null)
                        {
                            foreach (Component_Image.BindSettingsAttribute attr in
                                     p.GetCustomAttributes(typeof(Component_Image.BindSettingsAttribute), true))
                            {
                                shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(attr.SamplerIndex,
                                                                                                   texture, attr.AddressingMode, attr.FilteringMin, attr.FilteringMag, attr.FilteringMip));
                                break;
                            }

                            //GpuMaterialPass.TextureParameterValue textureValue = null;

                            //int samplerIndex = -1;

                            //foreach( Component_Image.BindSettingsAttribute attr in p.GetCustomAttributes(
                            //	typeof( Component_Image.BindSettingsAttribute ), true ) )
                            //{
                            //	textureValue = new GpuMaterialPass.TextureParameterValue( texture,
                            //		attr.AddressingMode, attr.FilteringMin, attr.FilteringMag, attr.FilteringMip );
                            //	samplerIndex = attr.SamplerIndex;
                            //	break;
                            //}

                            //if( samplerIndex != -1 )
                            //	shader.Parameters.Set( samplerIndex.ToString(), textureValue );
                        }
                        else
                        {
                            //!!!!
                            //convert to float type
                            value = SimpleTypes.ConvertDoubleToFloat(value);
                            //ColorValuePowered: convert to ColorValue
                            if (value is ColorValuePowered)
                            {
                                value = ((ColorValuePowered)value).ToColorValue();
                            }

                            shader.Parameters.Set(p.Name, value);
                            shader.Parameters.Set(ToLowerFirstCharacter(p.Name), value);
                        }
                    }
                }
            }

            OnSetShaderParameters(context, frameData, actualTexture, shader);
            SetShaderParametersEvent?.Invoke(this, context, shader);

            context.RenderQuadToCurrentViewport(shader);

            //change actual texture
            context.DynamicTexture_Free(actualTexture);
            actualTexture = outputTexture;
        }
コード例 #4
0
            object LoadValue(TextBlock block, Type valueType)
            {
                if (valueType.IsGenericType && valueType.Name == typeof(List <>).Name)
                {
                    //List<>
                    Type[] genericArguments = valueType.GetGenericArguments();
                    Trace.Assert(genericArguments.Length == 1);
                    Type itemType = genericArguments[0];

                    MethodInfo methodAdd = valueType.GetMethod("Add");

                    TextBlock listBlock = block.FindChild(name);

                    if (listBlock == null)
                    {
                        return(null);
                    }

                    //create list
                    object value;
                    {
                        value = valueType.InvokeMember("", BindingFlags.Public |
                                                       BindingFlags.NonPublic | BindingFlags.CreateInstance |
                                                       BindingFlags.Instance, null, null, null);
                        //ConstructorInfo constructor = valueType.GetConstructor( new Type[ 0 ] );
                        //value = constructor.Invoke( null );
                    }

                    if (itemType == typeof(string))
                    {
                        for (int n = 0; ; n++)
                        {
                            string attributeName = string.Format("item{0}", n);

                            if (!listBlock.AttributeExists(attributeName))
                            {
                                break;
                            }

                            string itemValue = listBlock.GetAttribute(attributeName);
                            methodAdd.Invoke(value, new object[] { itemValue });
                        }
                    }
                    else
                    {
                        List <FieldInfo> itemFields = new List <FieldInfo>();
                        {
                            foreach (FieldInfo field in itemType.GetFields(BindingFlags.Instance |
                                                                           BindingFlags.NonPublic | BindingFlags.Public))
                            {
                                if (field.GetCustomAttributes(typeof(EngineConfigAttribute), true).Length != 0)
                                {
                                    itemFields.Add(field);
                                }
                            }
                        }
                        List <PropertyInfo> itemProperties = new List <PropertyInfo>();
                        {
                            foreach (PropertyInfo property in itemType.GetProperties(BindingFlags.Instance |
                                                                                     BindingFlags.NonPublic | BindingFlags.Public))
                            {
                                if (property.GetCustomAttributes(typeof(EngineConfigAttribute), true).Length != 0)
                                {
                                    itemProperties.Add(property);
                                }
                            }
                        }

                        foreach (TextBlock itemBlock in listBlock.Children)
                        {
                            object itemValue = itemType.InvokeMember("", BindingFlags.Public |
                                                                     BindingFlags.NonPublic | BindingFlags.CreateInstance |
                                                                     BindingFlags.Instance, null, null, null);
                            //ConstructorInfo constructor = itemType.GetConstructor( new Type[ 0 ] );
                            //object itemValue = constructor.Invoke( null );

                            //item fields
                            foreach (FieldInfo itemField in itemFields)
                            {
                                string itemName = ((EngineConfigAttribute)itemField.GetCustomAttributes(typeof(EngineConfigAttribute), true)[0]).GetName(itemField);

                                if (!itemBlock.AttributeExists(itemName))
                                {
                                    continue;
                                }

                                string strValue = itemBlock.GetAttribute(itemName);

                                try
                                {
                                    object v = SimpleTypes.ParseValue(
                                        itemField.FieldType, strValue);

                                    if (v == null)
                                    {
                                        Log.Error("Config: Not implemented parameter type \"{0}\"", itemField.FieldType.ToString());
                                    }
                                    if (v != null)
                                    {
                                        itemField.SetValue(itemValue, v);
                                    }
                                }
                                catch (Exception e)
                                {
                                    Log.Warning("Config: {0} ({1})", itemName, e.Message);
                                }
                            }

                            //property fields
                            foreach (PropertyInfo itemProperty in itemProperties)
                            {
                                string itemName = ((EngineConfigAttribute)itemProperty.GetCustomAttributes(typeof(EngineConfigAttribute), true)[0]).GetName(itemProperty);

                                if (!itemBlock.AttributeExists(itemName))
                                {
                                    continue;
                                }

                                string strValue = itemBlock.GetAttribute(itemName);

                                try
                                {
                                    object v = SimpleTypes.ParseValue(
                                        itemProperty.PropertyType, strValue);

                                    if (v == null)
                                    {
                                        Log.Error("Config: Not implemented parameter type \"{0}\"", itemProperty.PropertyType.ToString());
                                    }
                                    if (v != null)
                                    {
                                        itemProperty.SetValue(itemValue, v, null);
                                    }
                                }
                                catch (Exception e)
                                {
                                    Log.Warning("Config: {0} ({1})", itemName, e.Message);
                                }
                            }

                            methodAdd.Invoke(value, new object[] { itemValue });
                        }
                    }
                    return(value);
                }

                // default load
                if (block.AttributeExists(name))
                {
                    string strValue = block.GetAttribute(name);

                    try
                    {
                        object value = SimpleTypes.ParseValue(valueType, strValue);

                        if (value == null)
                        {
                            Log.Error("Config: Not implemented parameter type \"{0}\"", valueType.ToString());
                        }

                        return(value);
                    }
                    catch (Exception e)
                    {
                        Log.Warning("Config: {0} ({1})", name, e.Message);
                        return(null);
                    }
                }
                return(null);
            }
コード例 #5
0
		public static bool ParseFile( string fileName, out EDictionary<string, string> resultData, out Encoding encoding, out bool wide )
		{
			resultData = null;
			encoding = null;
			wide = false;

			var fileBase = Path.Combine( VirtualFileSystem.Directories.EngineInternal, "Localization", fileName );
			var pathInfo = fileBase + ".info";
			var pathTxt = fileBase + ".txt";

			if( File.Exists( pathTxt ) )
			{
				try
				{
					string encodingName = null;
					int? encodingCodepage = null;

					if( File.Exists( pathInfo ) )
					{
						var block = TextBlockUtility.LoadFromRealFile( pathInfo );
						if( block != null )
						{
							//Encoding
							{
								var value = block.GetAttribute( "Encoding" );
								if( int.TryParse( value, out var codepage ) )
									encodingCodepage = codepage;
								else
									encodingName = value;
							}

							//WideLanguage
							{
								var value = block.GetAttribute( "WideLanguage" );
								if( !string.IsNullOrEmpty( value ) )
									wide = (bool)SimpleTypes.ParseValue( typeof( bool ), value );
							}
						}
					}

#if !DEPLOY
					if( encodingCodepage.HasValue )
						encoding = CodePagesEncodingProvider.Instance.GetEncoding( encodingCodepage.Value );
					else if( !string.IsNullOrEmpty( encodingName ) )
						encoding = CodePagesEncodingProvider.Instance.GetEncoding( encodingName );
#endif
					//if( encodingCodepage.HasValue )
					//	encoding = Encoding.GetEncoding( encodingCodepage.Value );
					//else if( !string.IsNullOrEmpty( encodingName ) )
					//	encoding = Encoding.GetEncoding( encodingName );

					string[] lines = null;
					if( encoding != null )
						lines = File.ReadAllLines( pathTxt, encoding );
					else
						lines = File.ReadAllLines( pathTxt );

					resultData = new EDictionary<string, string>();

					foreach( var line in lines )
					{
						if( !string.IsNullOrEmpty( line ) )
						{
							var strs = line.Split( new char[] { '|' } );
							if( strs.Length != 3 )
								throw new Exception( string.Format( "Invalid format for line \'{0}\'.", line ) );
							resultData[ strs[ 0 ] + "|" + strs[ 1 ] ] = strs[ 2 ];
						}
					}

					return true;
				}
				catch( Exception e )
				{
					Log.Warning( e.Message );
				}
			}

			return false;
		}
コード例 #6
0
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        protected override void OnRender(ViewportRenderingContext context, Component_RenderingPipeline.IFrameData frameData, ref Component_Image actualTexture)
        {
            var result = Result as CompiledDataCodeGenerated;

            //!!!!так?
            if (result == null)
            {
                return;
            }

            if (result.vertexProgram == null || result.fragmentProgram == null)
            {
                return;
            }

            //!!!!валится если файла нет. или не указан.
            //!!!!!!как быстро проверять о том что файла нет? может из кеша шейдеров или типа того. как тогда обновлять
            //string shaderFile = Shader;
            //if( string.IsNullOrEmpty( shaderFile ) )
            //	return;

            //!!!!formats. т.е. эффект поддерживает и LDR и HDR. где еще
            //!!!!!можно по сути у эффекта указывать что он ожидает получить на входе. ну или это EffectsHDR, EffectsLDR
            var outputTexture = context.RenderTarget2D_Alloc(actualTexture.Result.ResultSize, actualTexture.Result.ResultFormat);

            context.SetViewport(outputTexture.Result.GetRenderTarget().Viewports[0]);

            CanvasRenderer.ShaderItem shader = new CanvasRenderer.ShaderItem();
            shader.CompiledVertexProgram   = result.vertexProgram;
            shader.CompiledFragmentProgram = result.fragmentProgram;

            //shader.VertexProgramFileName = shaderFile;
            //shader.VertexProgramFunctionName = "main_vp";
            //shader.FragmentProgramFileName = shaderFile;
            //shader.FragmentProgramFunctionName = "main_fp";

            //{
            //	var defines = new List<GuiRenderer.ShaderItem.DefineItem>();

            //	//defines.Add( new GuiRenderer.ShaderItem.DefineItem( "FRAGMENT_CODE_BODY", "color = float4(0,1,0,1);" ) );

            //	if( defines.Count != 0 )
            //		shader.Defines = defines.ToArray();
            //}

            shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(0 /*"sourceTexture"*/,
                                                                               actualTexture, TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.Point));
            //shader.Parameters.Set( "0"/*"sourceTexture"*/, new GpuMaterialPass.TextureParameterValue( actualTexture,
            //	TextureAddressingMode.Clamp, FilterOption.Point, FilterOption.Point, FilterOption.Point ) );

            unsafe
            {
                Vector4F value = Vector4F.One;
                if (!Color.ReferenceSpecified)
                {
                    value = Color.Value.ToVector4F();
                }
                shader.Parameters.Set("u_paramColor", ParameterType.Vector4, 1, &value, sizeof(Vector4F));
            }

            //!!!!пока так
            if (result.fragmentGeneratedCode != null)
            {
                //!!!!copy code из MaterialStandard

                //var materialParameters = materialData.GetShaderParameters();
                var code = result.fragmentGeneratedCode;

                //foreach( var code in codes )
                //{
                if (code.parameters != null)
                {
                    foreach (var item in code.parameters)
                    {
                        //!!!!надо ссылки сконвертить или как-то так? чтобы работало, если это в типе

                        var value = item.component.GetValue();
                        if (value != null)
                        {
                            //!!!!
                            //convert to float type
                            value = SimpleTypes.ConvertDoubleToFloat(value);
                            //ColorValuePowered: convert to ColorValue
                            if (value is ColorValuePowered)
                            {
                                value = ((ColorValuePowered)value).ToColorValue();
                            }

                            shader.Parameters /*container*/.Set(item.nameInShader, value);
                        }
                    }
                }

                if (code.textures != null)
                {
                    foreach (var item in code.textures)
                    {
                        //!!!!надо ссылки сконвертить или как-то так? чтобы работало, если это в типе

                        //!!!!не только 2D

                        Component_Image texture = item.component.Texture;
                        if (texture == null)
                        {
                            texture = ResourceUtility.WhiteTexture2D;
                        }

                        //!!!!options

                        shader.Parameters.Set(new ViewportRenderingContext.BindTextureData(item.textureRegister,
                                                                                           texture, TextureAddressingMode.Wrap, FilterOption.Linear, FilterOption.Linear, FilterOption.Linear));

                        ////!!!!
                        //var textureValue = new GpuMaterialPass.TextureParameterValue( texture,
                        //	TextureAddressingMode.Wrap, FilterOption.Linear, FilterOption.Linear, FilterOption.Linear );
                        ////!!!!
                        //ParameterType parameterType = ParameterType.Texture2D;

                        //shader.Parameters/*container*/.Set( item.textureRegister.ToString(), textureValue, parameterType );
                        ////shader.Parameters/*container*/.Set( item.nameInShader, textureValue, parameterType );
                    }
                }
                //}
            }

            var size = actualTexture.Result.ResultSize;

            shader.Parameters.Set("viewportSize", new Vector4(size.X, size.Y, 1.0 / (double)size.X, 1.0 / (double)size.Y).ToVector4F());

            shader.Parameters.Set("intensity", (float)Intensity.Value);

            //!!!!auto parameters
            //if( result.fragmentGeneratedCode != null )
            {
                //!!!!не так потом

                shader.Parameters.Set("param_viewportSize", new Vector2F(size.X, size.Y));

                //foreach( var item in result.fragmentGeneratedCode.autoConstantParameters )
                //{
                //}
            }

            context.RenderQuadToCurrentViewport(shader);

            //change actual texture
            context.DynamicTexture_Free(actualTexture);
            actualTexture = outputTexture;
        }