Exemplo n.º 1
0
        /// <summary>Compiles the effect for the provided graphics device</summary>
        /// <returns>The compiled effect</returns>
        internal static void Compile()
        {
            // Compile the effect code for x86 platforms
            {
                CompiledEffect compiledEffect = Effect.CompileEffectFromSource(
                    EffectSource, null, null, CompilerOptions.None, TargetPlatform.Windows
                    );
                if (!compiledEffect.Success)
                {
                    throw new Exception("Error compiling effect: " + compiledEffect.ErrorsAndWarnings);
                }

                using (FileStream effectFile = new FileStream("solidcolor.x86", FileMode.Create)) {
                    byte[] code = compiledEffect.GetEffectCode();
                    effectFile.Write(code, 0, code.Length);
                }
            }

            // Compile the effect code for XBox 360 platforms
            {
                CompiledEffect compiledEffect = Effect.CompileEffectFromSource(
                    EffectSource, null, null, CompilerOptions.None, TargetPlatform.Xbox360
                    );
                if (!compiledEffect.Success)
                {
                    throw new Exception("Error compiling effect: " + compiledEffect.ErrorsAndWarnings);
                }

                using (FileStream effectFile = new FileStream("solidcolor.360", FileMode.Create)) {
                    byte[] code = compiledEffect.GetEffectCode();
                    effectFile.Write(code, 0, code.Length);
                }
            }
        }
Exemplo n.º 2
0
        public Renderer(VideoSystem videosystem)
        {
            if (videosystem == null)
            {
                throw new ArgumentNullException("videosystem");
            }

            m_videosystem = videosystem;

            using (IO.File effectfile = m_videosystem.GetSubSystem <IO.FileSystem>().OpenFile("xnaMugen.data.Shader.fx"))
            {
                CompiledEffect compiled = Effect.CompileEffectFromSource(effectfile.ReadToEnd(), null, null, CompilerOptions.None, TargetPlatform.Windows);
                if (compiled.Success == false)
                {
                    throw new InvalidOperationException("Cannot successfully create shader.");
                }

                m_effect = new Effect(Device, compiled.GetEffectCode(), CompilerOptions.NotCloneable, null);
            }

            m_drawbuffer = new Vertex[500];
            m_parameters = new KeyedCollection <String, EffectParameter>(x => x.Name);

            m_nullpixels  = m_videosystem.CreatePixelTexture(new Point(2, 2));
            m_nullpalette = m_videosystem.CreatePaletteTexture();

            Byte[] pixels = new Byte[] { 1, 2, 1, 2 };
            m_nullpixels.SetData <Byte>(pixels);

            Color[] paldata = new Color[256];
            paldata[1] = Color.White;
            paldata[2] = Color.Red;
            m_nullpalette.SetData <Color>(paldata);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Processes a PaletteInfo object into a PaletteMaterialContent object.
        /// </summary>
        /// <param name="input">The PaletteInfo to process.</param>
        /// <param name="context">The processor context.</param>
        /// <returns>The processed PaletteMaterialContent</returns>
        public override PaletteMaterialContent Process(PaletteInfo input,
                                                       ContentProcessorContext context)
        {
            // Set all the variables based on the input.
            EffectProcessor effectProcessor = new EffectProcessor();
            EffectContent   effectContent   = new EffectContent();

            effectContent.EffectCode = input.SourceCode;
            CompiledEffect         compiled = effectProcessor.Process(effectContent, context);
            PaletteMaterialContent content  = new PaletteMaterialContent();

            content.PaletteSize = input.PaletteSize;
            content.ByteCode    = compiled.GetEffectCode();
            BasicMaterialContent basic = input.BasicContent;

            content.Alpha              = basic.Alpha;
            content.DiffuseColor       = basic.DiffuseColor;
            content.EmissiveColor      = basic.EmissiveColor;
            content.Name               = basic.Name;
            content.SpecularColor      = basic.SpecularColor;
            content.SpecularPower      = basic.SpecularPower;
            content.Texture            = basic.Texture;
            content.VertexColorEnabled = basic.VertexColorEnabled;
            return(content);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Create a new game.
        /// </summary>
        public Game1()
        {
            InitializeComponent();

            float aspectRatio = 640.0f / 480.0f;
            float fov         = MathHelper.PiOver4;

            // Initialize the matrices.
            this.viewTransformation       = Matrix.CreateLookAt(new Vector3(0, 0, 150), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
            this.projectionTransformation = Matrix.CreatePerspectiveFieldOfView(fov, aspectRatio, 1, 600);

            // Initialize the shader.
            CompiledEffect cEffect = Effect.CompileEffectFromFile("color.fx", null, null, CompilerOptions.None, TargetPlatform.Windows);

            this.effect = new Effect(this.graphics.GraphicsDevice, cEffect.GetShaderCode(), CompilerOptions.None, null);

            // Get the parameters.
            EffectParameterCollection coll = this.effect.Parameters;

            this.transform = coll.GetParameterBySemantic("WorldViewProjection");
            this.color     = coll.GetParameterBySemantic("Color");

            // Create and add volumes.
            this.volumes = new List <BoundingVolume>();
            this.AddBoundingVolumes();
        }
Exemplo n.º 5
0
        /// <summary>compile and load an effect from a string containing effect code</summary>
        private Effect LoadContentRuntimeString(string content, string name)
        {
            Effect reffect = null;

            try {
                // ForcePixelShaderSoftwareNoOptimizations gives wrong answers
                // SkipOptimizations makes the variable size convolution work, but at what cost??
                CompilerOptions copts          = CompilerOptions.SkipOptimization; // | CompilerOptions.AvoidFlowControl;
                CompiledEffect  compiledEffect = Effect.CompileEffectFromSource(content, null, null, copts, TargetPlatform.Windows);

                if (compiledEffect.Success)
                {
                    EffectPool effectPool = new EffectPool();
                    reffect = new Effect(graphicsDevice, compiledEffect.GetEffectCode(), CompilerOptions.None, effectPool);
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("Error in dynamic shader " + name + ".  Previous version will be used.\n\n" + compiledEffect.ErrorsAndWarnings);
                }
            }
            catch (Exception e) {
                System.Windows.Forms.MessageBox.Show("Unexpected error in dynamic shader " + name + ".  Previous version will be used.\n\n" + e);
            }
            return(reffect);
        }
Exemplo n.º 6
0
        private void CreateEffect(object sender, EventArgs e)
        {
            CompiledEffect ce = Effect.CompileEffectFromSource(EffectSource, new CompilerMacro[0],
                                                               null, CompilerOptions.None, TargetPlatform.Windows);

            mEffect = new Effect(mGraphics.GraphicsDevice, ce.GetEffectCode(), CompilerOptions.None, null);
        }
Exemplo n.º 7
0
        public override TOutput Process(TInput input, ContentProcessorContext context)
        {
            Dictionary <string, Q3BSPMaterialContent> processedDictionary = new Dictionary <string, Q3BSPMaterialContent>();

            #region Initialize StreamWriter, if necessary
#if DEBUG
            StreamWriter sw = new StreamWriter(context.OutputFilename.Substring(0, context.OutputFilename.LastIndexOf('.')) + ".compiled.txt");
#else
            StreamWriter sw = null;
#endif
            #endregion

            for (int i = 0; i < input.Count; i++)
            {
                Q3BSPMaterialContent shader = input[i];

                #region Throw any errors in the parsed shader
                if (shader.stages.Count > 8)
                {
                    throw new InvalidContentException(shader.shaderName + " has " + shader.stages.Count + " stages, but the maximum supported is 8.");
                }
                if (processedDictionary.ContainsKey(shader.shaderName))
                {
                    throw new InvalidContentException("Material " + shader.shaderName + " is defined more than once.");
                }
                #endregion

                #region Log any needed warnings
                if (shader.stages.Count > 4 && shaderModel == ShaderModel.ShaderModel1)
                {
                    context.Logger.LogWarning("", new ContentIdentity(), shader.shaderName + " has more than 4 stages, Shader Model 2.0 is required.");
                }
                #endregion

                #region Compile the Effect
#if DEBUG
                CompiledEffect compiledEffect = Effect.CompileEffectFromSource(GenerateEffectFromShader(shader, sw), null, null, CompilerOptions.Debug, TargetPlatform.Windows);
#else
                CompiledEffect compiledEffect = Effect.CompileEffectFromSource(GenerateEffectFromShader(shader, sw), null, null, CompilerOptions.None, TargetPlatform.Windows);
#endif
                #endregion

                if (compiledEffect.ErrorsAndWarnings.Contains("error"))
                {
                    throw new InvalidContentException(shader.shaderName + ": " + compiledEffect.ErrorsAndWarnings);
                }

                shader.compiledEffect = compiledEffect;
                shader.ShaderCode     = compiledEffect.GetEffectCode();

                processedDictionary.Add(shader.shaderName, shader);
            }
#if DEBUG
            sw.Flush();
            sw.Dispose();
#endif

            return(processedDictionary);
        }
        }         // Dispose()

        #endregion

        #region Reload effect
        /// <summary>
        /// Reload
        /// </summary>
        public void Load()
        {
            if (effect != null)
            {
                return;
            }

            // Dispose old shader
            //Dispose();

            string shaderContentName = Filename;

            // Load shader
            try
            {
                // We have to try, there is no "Exists" method.
                // We could try to check the xnb filename, but why bother? ^^
                effect = BaseGame.Content.Load <Effect>(
                    Path.Combine(Directories.ContentDirectory, shaderContentName));
            }             // try
#if XBOX360
            catch (Exception ex)
            {
                Log.Write("Failed to load shader " + shaderContentName + ". " +
                          "Error: " + ex.ToString());
                // Rethrow error, app can't continue!
                throw ex;
            }
#else
            catch
            {
                // Try again by loading by filename (only allowed for windows!)
                // Content file was most likely removed for easier testing :)
                try
                {
                    CompiledEffect compiledEffect = Effect.CompileEffectFromFile(
                        Path.Combine("Shaders", shaderContentName + ".fx"),
                        null, null, CompilerOptions.None,
                        TargetPlatform.Windows);

                    effect = new Effect(BaseGame.Device,
                                        compiledEffect.GetEffectCode(), CompilerOptions.None, null);
                }                 // try
                catch (Exception ex)
                {
                    Log.Write("Failed to load shader " + shaderContentName + ". " +
                              "Error: " + ex.ToString());
                    // Rethrow error, app can't continue!
                    throw ex;
                }         // catch
            }             // catch
#endif

            ResetParameters();
            GetParameters();
        }         // Load()
Exemplo n.º 9
0
        /// <summary>
        /// Event handler called when the graphics device is created
        /// </summary>
        /// <param name="sender">unused</param>
        /// <param name="e">unused</param>
        private void OnDeviceCreated(object sender, EventArgs e)
        {
            GraphicsDevice device = mGraphics.GraphicsDevice;

            CompiledEffect ce = Effect.CompileEffectFromSource(EffectSource, new CompilerMacro[0],
                                                               null, CompilerOptions.None, TargetPlatform.Windows);

            mEffect = new Effect(mGraphics.GraphicsDevice, ce.GetEffectCode(), CompilerOptions.None, null);

            mVertexDeclaration = new VertexDeclaration(device,
                                                       new VertexElement[] { new VertexElement(0, 0, VertexElementFormat.Vector3,
                                                                                               VertexElementMethod.Default, VertexElementUsage.Position, 0) });
        }
Exemplo n.º 10
0
        } // Dispose()

        /// <summary>
        /// Reload effect (can be useful if we change the fx file dynamically).
        /// </summary>
        public virtual void Load(Microsoft.Xna.Framework.Content.ContentManager content)
        {
            //obs?
            // Dispose old shader
            if (effect != null)
            {
                effect.Dispose();
                effect = null;
            }


            // Load shader
            try
            {
                // We have to try, there is no "Exists" method.
                // We could try to check the xnb filename, but why bother? ^^
                effect = content.Load <Effect>(shaderContentName);
                //Path.Combine( Directories.ContentDirectory, shaderContentName ) );
            } // try

            catch
            {
                if (System.IO.File.Exists(shaderContentName) == false)
                {
                    throw new System.IO.FileNotFoundException("Shader file '" + shaderContentName + "' not found!");
                }
                // Try again by loading by filename (only allowed for windows!)
                // Content file was most likely removed for easier testing :)
                try
                {
                    CompiledEffect compiledEffect = Effect.CompileEffectFromFile(
                        shaderContentName,
                        //Path.Combine( "Shaders", shaderContentName + ".fx" ),
                        null, null, CompilerOptions.None,
                        TargetPlatform.Windows);

                    effect = new Effect(game.GraphicsDevice,
                                        compiledEffect.GetEffectCode(), CompilerOptions.None, null);
                } // try
                catch (Exception ex)
                {
                    /*Log.Write( "Failed to load shader " + shaderContentName + ". " +
                     *  "Error: " + ex.ToString() );*/
                    // Rethrow error, app can't continue!
                    throw ex;
                } // catch
            }     // catch


            GetParameters();
        } // Load()
Exemplo n.º 11
0
        private void SetupXNADevice()
        {
            device = graphics.GraphicsDevice;

            graphics.PreferredBackBufferWidth  = 500;
            graphics.PreferredBackBufferHeight = 500;

            graphics.IsFullScreen = false;

            graphics.ApplyChanges();

            Window.Title = "riemer`s XNA tutorial 02 - series 1";

            CompiledEffect compiledEffect = Effect.CompileEffectFromFile("@/../../../../effects.fx", null, null, CompilerOptions.None, TargetPlatform.Windows); // effects.fx파일로 부터 effect코드 컴파일

            effect = new Effect(graphics.GraphicsDevice, compiledEffect.GetEffectCode(), CompilerOptions.None, null);                                           // effect 설정
        }
Exemplo n.º 12
0
        private void compileEffectButton_Click(object sender, EventArgs e)
        {
            // Get the effect source
            string effectSource = string.Empty;

            for (int i = 0; i < effectEditBox.Lines.Length; i++)
            {
                effectSource += effectEditBox.Lines[i] + Environment.NewLine;
            }

            // Start output
            effectCompileOutput.Clear();
            effectCompileOutput.AppendText("Compiling Effect..." + Environment.NewLine);

            // Compile the effect
            CompiledEffect effectCompiled = Effect.CompileEffectFromSource(
                effectSource,
                null, //new CompilerMacro[] { },
                null,
                CompilerOptions.None,
                TargetPlatform.Windows);

            // Check for errors
            if (!effectCompiled.Success)
            {
                effectCompileOutput.AppendText("There were  errors:" + Environment.NewLine);
                effectCompileOutput.AppendText("    " + effectCompiled.ErrorsAndWarnings + Environment.NewLine);
            }
            else
            {
                effectCompileOutput.AppendText("Success!");

                effectPropertyGrid.SelectedObject = null;

                // Apply the effect
                Effect effect = modelViewPanel.ApplyEffect(effectCompiled.GetEffectCode());

                // Set the property grid
                EffectPropertyEditor editor = new EffectPropertyEditor(effect);
                effectPropertyGrid.SelectedObject = editor;

                // Switch tabs
                mainTabControl.SelectedTab = mainTabControl.TabPages[0];
            }
        }
Exemplo n.º 13
0
        static void EffectParser(string inputfile, string outputfile)
        {
            CompilerMacro[] macroArray = null;
            macroArray         = new CompilerMacro[2];
            macroArray[0].Name = "XBOX";
            macroArray[1].Name = "XBOX360";
            CompiledEffect compiledEffect = Microsoft.Xna.Framework.Graphics.Effect.CompileEffectFromFile(inputfile, macroArray, null, CompilerOptions.None, TargetPlatform.Xbox360);

            if (compiledEffect.Success)
            {
                System.IO.File.WriteAllBytes(outputfile, compiledEffect.GetEffectCode());
            }
            else
            {
                Console.WriteLine("Error compiling effect:");
            }

            if (compiledEffect.ErrorsAndWarnings != string.Empty)
            {
                Console.WriteLine(compiledEffect.ErrorsAndWarnings);
            }
        }
Exemplo n.º 14
0
        private Effect LoadEffectFromFile(string source_file)
        {
            CompiledEffect compiled_effect = Effect.CompileEffectFromFile(source_file, null, null, CompilerOptions.None, Microsoft.Xna.Framework.TargetPlatform.Windows);

            return(new Effect(device, compiled_effect.GetEffectCode(), CompilerOptions.None, null));
        }
Exemplo n.º 15
0
        public WaterSurface(GraphicsDevice device, Camera camera, Vector3 normal, float position, int sizeX, int sizeY)
        {
            Vector3 x;

            Device             = device;
            Camera             = camera;
            Normal             = normal;
            Position           = position;
            Plane              = new Plane(normal, position);
            NoiseMaker         = new NoiseMaker(Device, GridSizeX, GridSizeY);
            PlaneWithinFrustum = false;

            // Set the initial water color
            WaterColor = Color.Aquamarine;

            // Calculate the U and V vectors
            if (Math.Abs(Vector3.Dot(Vector3.UnitX, normal)) < Math.Abs(Vector3.Dot(Vector3.UnitY, normal)))
            {
                x = Vector3.UnitX;
            }
            else
            {
                x = Vector3.UnitY;
            }

            U = x - normal * Vector3.Dot(normal, x);
            U = Vector3.Normalize(U);

            // Get V (cross)
            V = Vector3.Cross(U, normal);

            GridSizeX = sizeX + 1;
            GridSizeY = sizeY + 1;

            SetDisplacementAmplitude(0);

            if (!InitializeBuffers())
            {
                return;
            }

            // Load the textures
            if ((Fresnel = Texture2D.FromFile(Device, "textures/fresnel_water_linear.bmp")) == null)
            {
                return;
            }
            if ((XYNoise = Texture2D.FromFile(Device, "textures/xynoise.png")) == null)
            {
                return;
            }

            // Initialize the reflection and refraction textures, and the depth stencil
            Reflection = new Texture2D(Device, REFLREFRDETAIL, REFLREFRDETAIL, 1, ResourceUsage.RenderTarget,
                                       SurfaceFormat.Color, ResourcePool.Default);
            Refraction = new Texture2D(Device, REFLREFRDETAIL, REFLREFRDETAIL, 1, ResourceUsage.RenderTarget,
                                       SurfaceFormat.Color, ResourcePool.Default);
            DepthStencil = Device.CreateDepthStencilSurface(REFLREFRDETAIL, REFLREFRDETAIL, DepthFormat.Depth24Stencil8,
                                                            MultiSampleType.None, 0, true);

            // Load the effect
            CompiledEffect water = Effect.CompileEffectFromFile("shaders/watereffect.fx", null, null,
                                                                CompilerOptions.Debug | CompilerOptions.SkipOptimization, TargetPlatform.Windows);

            if (!water.Success)
            {
                return;
            }
            else
            {
                WaterEffect = new Effect(Device, water.GetShaderCode(), CompilerOptions.None, null);
            }

            Initialized = true;
        }
        }         // Dispose()

        #endregion

        #region Reload effect
        /// <summary>
        /// Reload effect (can be useful if we change the fx file dynamically).
        /// </summary>
        public void Load()
        {
            if (effect != null)
            {
                return;
            }

            /*obs
             * // Dispose old shader
             * if (effect != null)
             *      Dispose();
             */

            // Load shader
            try
            {
                // We have to try, there is no "Exists" method.
                // We could try to check the xnb filename, but why bother? ^^
                effect = BaseGame.Content.Load <Effect>(
                    Path.Combine(Directories.ContentDirectory, shaderContentName));
            }             // try
#if XBOX360
            catch (Exception ex)
            {
                Log.Write("Failed to load shader " + shaderContentName + ". " +
                          "Error: " + ex.ToString());
                // Rethrow error, app can't continue!
                throw ex;
            }
#else
            catch
            {
                // Try again by loading by filename (only allowed for windows!)
                // Content file was most likely removed for easier testing :)
                try
                {
                    CompiledEffect compiledEffect = Effect.CompileEffectFromFile(
                        Path.Combine("Shaders", shaderContentName + ".fx"),
                        null, null, CompilerOptions.None,
                        TargetPlatform.Windows);

                    effect = new Effect(BaseGame.Device,
                                        compiledEffect.GetEffectCode(), CompilerOptions.None, null);
                }                 // try
                catch (Exception ex)
                {
                    /*obs
                     * Log.Write("Failed to compile shader, this happend most likely " +
                     *      "because the shader has some syntax error, please check it. " +
                     *      "Error: " + ex.ToString());
                     */
                    Log.Write("Failed to load shader " + shaderContentName + ". " +
                              "Error: " + ex.ToString());
                    // Rethrow error, app can't continue!
                    throw ex;
                }         // catch
            }             // catch
#endif

            // Reset and get all avialable parameters.
            // This is especially important for derived classes.
            ResetParameters();
            GetParameters();
        }         // Reload()
        /// <summary>
        /// Procesar el mapa de alturas
        /// </summary>
        /// <param name="input">Información del escenario de entrada</param>
        /// <param name="context">Contexto de procesado</param>
        /// <returns>Devuelve la información de escenario leída</returns>
        public override SceneryInfo Process(SceneryFile input, ContentProcessorContext context)
        {
            // Cargar la textura del mapa de alturas
            Texture2DContent terrain = context.BuildAndLoadAsset <Texture2DContent, Texture2DContent>(new ExternalReference <Texture2DContent>(input.HeightMapFile), null);

            // Obtener el mapa de alturas
            HeightMap heightMap = this.BuildHeightMap(terrain, input.HeightMapCellScale, context);

            // Generar los vértices e inicializar el buffer de vértices
            VertexMultitextured[] vertList = heightMap.BuildVertices(
                input.HeightMapCellSize,
                input.ProportionTexture1,
                input.ProportionTexture2,
                input.ProportionTexture3);
            VertexBufferContent vertexBuffer = new VertexBufferContent(VertexMultitextured.SizeInBytes * vertList.Length);

            vertexBuffer.Write <VertexMultitextured>(0, VertexMultitextured.SizeInBytes, vertList, context.TargetPlatform);

            // Generar los índices e inicializar los buffers de índices
            double          lowOrderLevels   = (Math.Sqrt(heightMap.DataLength) - 1) * 0.5f;
            int             levelCount       = Convert.ToInt32(Math.Log(lowOrderLevels, 4.0d));
            SceneryNodeInfo sceneryIndexInfo = SceneryNodeInfo.Build(
                vertList,
                heightMap.Width,
                heightMap.Deep,
                levelCount);

            // Efecto de renderización
            CompiledEffect effect = Effect.CompileEffectFromFile(
                input.EffectFile,
                null,
                null,
                CompilerOptions.None,
                context.TargetPlatform);

            // Texturas del terreno
            Texture2DContent texture1       = context.BuildAndLoadAsset <Texture2DContent, Texture2DContent>(new ExternalReference <Texture2DContent>(input.Texture1File), null);
            Texture2DContent texture2       = context.BuildAndLoadAsset <Texture2DContent, Texture2DContent>(new ExternalReference <Texture2DContent>(input.Texture2File), null);
            Texture2DContent texture3       = context.BuildAndLoadAsset <Texture2DContent, Texture2DContent>(new ExternalReference <Texture2DContent>(input.Texture3File), null);
            Texture2DContent texture4       = context.BuildAndLoadAsset <Texture2DContent, Texture2DContent>(new ExternalReference <Texture2DContent>(input.Texture4File), null);
            Texture2DContent detailTexture1 = context.BuildAndLoadAsset <Texture2DContent, Texture2DContent>(new ExternalReference <Texture2DContent>(input.DetailTexture1File), null);
            Texture2DContent detailTexture2 = context.BuildAndLoadAsset <Texture2DContent, Texture2DContent>(new ExternalReference <Texture2DContent>(input.DetailTexture2File), null);
            Texture2DContent detailTexture3 = context.BuildAndLoadAsset <Texture2DContent, Texture2DContent>(new ExternalReference <Texture2DContent>(input.DetailTexture3File), null);
            Texture2DContent detailTexture4 = context.BuildAndLoadAsset <Texture2DContent, Texture2DContent>(new ExternalReference <Texture2DContent>(input.DetailTexture4File), null);

            CompiledEffect billboardEffect = Effect.CompileEffectFromFile(
                input.BillboardEffectFile,
                null,
                null,
                CompilerOptions.None,
                context.TargetPlatform);

            Texture2DContent billboardGrassTexture = context.BuildAndLoadAsset <Texture2DContent, Texture2DContent>(new ExternalReference <Texture2DContent>(input.BillboardGrassTextureFile), null);
            Texture2DContent billboardTreeTexture  = context.BuildAndLoadAsset <Texture2DContent, Texture2DContent>(new ExternalReference <Texture2DContent>(input.BillboardTreeTextureFile), null);
            int   billboardsPerTriangle            = input.BillboardsPerTriangle;
            float billboardTreesPercent            = input.BillboardTreesPercent;

            return(new SceneryInfo()
            {
                Terrain = terrain,
                TerrainBuffer = vertexBuffer,
                TerrainBufferVertexCount = vertList.Length,
                TerrainInfo = sceneryIndexInfo,
                Effect = effect,
                Texture1 = texture1,
                Texture2 = texture2,
                Texture3 = texture3,
                Texture4 = texture4,
                DetailTexture1 = detailTexture1,
                DetailTexture2 = detailTexture2,
                DetailTexture3 = detailTexture3,
                DetailTexture4 = detailTexture4,
                BillboardEffect = billboardEffect,
                BillboardGrass = billboardGrassTexture,
                BillboardTree = billboardTreeTexture,
                BillboardsPerTriangle = billboardsPerTriangle,
                BillboardTreesPercent = billboardTreesPercent,
            });
        }
Exemplo n.º 18
0
        public DecompiledEffect(SourceShader source, Platform platform)
        {
            CompilerMacro[] macros = null;
            if (platform == Platform.Xbox)
            {
                macros = XboxCompileMacros;
            }

            CompilerIncludeHandler include = null;
            TargetPlatform         target  = TargetPlatform.Windows;

            this.techniqueDefaults = new Dictionary <string, TechniqueExtraData>();

            if (platform != Platform.Both)
            {
                include = new VFetchIncludeHandler(source.FileName, true);                 //ALWAYS target the PC for the vfetch macro
            }
            else
            {
                include = new VFetchIncludeHandler(source.FileName);                 //Acts as a generic handler
            }
            CompiledEffect compiledEffect = Effect.CompileEffectFromSource(source.ShaderSource, macros, include, source.CompilerOptions, target);

            if (!compiledEffect.Success)
            {
                Common.ThrowError(compiledEffect.ErrorsAndWarnings, source.ShaderSource);
            }

            //now pull the good stuff out.
            using (EffectPool pool = new EffectPool())
                using (Effect effect = new Effect(Graphics.GraphicsDevice, compiledEffect.GetEffectCode(), CompilerOptions.None, pool))
                {
                    Register[]      registers = new Register[effect.Parameters.Count];
                    List <Register> textures  = new List <Register>();

                    for (int i = 0; i < registers.Length; i++)
                    {
                        if (effect.Parameters[i].ParameterType == EffectParameterType.Single ||
                            effect.Parameters[i].ParameterType == EffectParameterType.Int32 ||
                            effect.Parameters[i].ParameterType == EffectParameterType.Bool)
                        {
                            registers[i].Name     = effect.Parameters[i].Name;
                            registers[i].Semantic = effect.Parameters[i].Semantic;
                        }

                        if (effect.Parameters[i].ParameterType >= EffectParameterType.Texture &&
                            effect.Parameters[i].ParameterType <= EffectParameterType.TextureCube)
                        {
                            EffectParameterType type = effect.Parameters[i].ParameterType;
                            if (type == EffectParameterType.Texture1D)
                            {
                                type = EffectParameterType.Texture2D;
                            }

                            registers[i].Name     = effect.Parameters[i].Name;
                            registers[i].Semantic = effect.Parameters[i].Semantic;
                            registers[i].Type     = type.ToString();
                            textures.Add(registers[i]);
                        }
                    }

                    this.effectRegisters = new RegisterSet(registers);
                    this.decompiledAsm   = Effect.Disassemble(effect, false);

                    ExtractEffectDefaults(effect, textures, source, platform);
                }
        }