Пример #1
0
        public Skybox(GraphicsDevice device)
        {
            float x = 0.525731f;
            float z = 0.850651f;

            var vertices = new SkyboxVertex[12]
            {
                new SkyboxVertex(-x, 0f, z), new SkyboxVertex(x, 0f, z),
                new SkyboxVertex(-x, 0f, -z), new SkyboxVertex(x, 0f, -z),
                new SkyboxVertex(0f, z, x), new SkyboxVertex(0f, z, -x),
                new SkyboxVertex(0f, -z, x), new SkyboxVertex(0f, -z, -x),
                new SkyboxVertex(z, x, 0f), new SkyboxVertex(-z, x, 0f),
                new SkyboxVertex(z, -x, 0f), new SkyboxVertex(-z, -x, 0f),
            };

            var indices = new int[60]
            {
                1,4,0,  4,9,0,  4,5,9,  8,5,4,  1,8,4,
                1,10,8, 10,3,8, 8,3,5,  3,2,5,  3,7,2,
                3,10,7, 10,6,7, 6,11,7, 6,0,11, 6,1,0,
                10,1,6, 11,0,9, 2,11,9, 5,2,9,  11,2,7
            };

            vertexBuffer = Buffer<SkyboxVertex>.New(device, vertices, BufferFlags.VertexBuffer);
            indexBuffer = Buffer<int>.New(device, indices, BufferFlags.IndexBuffer);
            skyboxEffect = EffectLoader.Load(@"Graphics/Shaders/Skybox.fx");
            skyboxTex = Texture2D.Load(device, @"G:\Users\Athrun\Documents\Stratum\trunk\src\Stratum\WorldEngine\Earth\milkyWay.tif");
        }
 protected virtual void TrackEffect(Effect effect)
 {
     if (!effectsToAlwaysCheck.Contains(effect))
     {
         effectsToAlwaysCheck.Add(effect);
     }
 }
Пример #3
0
        public ParticleSystem(GraphicsDevice device, ContentManager content)
        {
            this.device = device;

            // Create vertex buffer used to spawn new particles
            this.particleStart = Buffer.Vertex.New<ParticleVertex>(device, MAX_NEW);

            // Create vertex buffers to use for updating and drawing the particles alternatively
            var vbFlags = BufferFlags.VertexBuffer | BufferFlags.StreamOutput;
            this.particleDrawFrom = Buffer.New<ParticleVertex>(device, MAX_PARTICLES, vbFlags);
            this.particleStreamTo = Buffer.New<ParticleVertex>(device, MAX_PARTICLES, vbFlags);

            this.layout = VertexInputLayout.FromBuffer(0, this.particleStreamTo);
            this.effect = content.Load<Effect>("ParticleEffect");
            this.texture = content.Load<Texture2D>("Dot");

            this.viewParameter = effect.Parameters["_view"];
            this.projParameter = effect.Parameters["_proj"];
            this.lookAtMatrixParameter = effect.Parameters["_lookAtMatrix"];
            this.elapsedSecondsParameter = effect.Parameters["_elapsedSeconds"];
            this.camDirParameter = effect.Parameters["_camDir"];
            this.gravityParameter = effect.Parameters["_gravity"];
            this.textureParameter = effect.Parameters["_texture"];
            this.samplerParameter = effect.Parameters["_sampler"];
            this.updatePass = effect.Techniques["UpdateTeq"].Passes[0];
            this.renderPass = effect.Techniques["RenderTeq"].Passes[0];
        }
Пример #4
0
        /// <summary>
        /// Draws all of the ModelMeshPart objects in this mesh, using their current Effect settings.
        /// </summary>
        /// <param name="context">The graphics context.</param>
        /// <param name="boneTransforms">The model's bone transforms.</param>
        /// <param name="effectOverride">The effect to use instead of the effect attached to each mesh part. Default is null (use Effect in MeshPart)</param>
        /// <exception cref="System.InvalidOperationException">Model has no effect</exception>
        public void Draw(GraphicsDevice context, Matrix[] boneTransforms, Effect effectOverride = null)
        {
            int count = this.MeshParts.Count;
            for (int i = 0; i < count; i++)
            {
                ModelMeshPart part = MeshParts[i];
                Effect effect = effectOverride ?? part.Effect;
                if (effect == null)
                {
                    throw new InvalidOperationException("ModelMeshPart has no effect and effectOverride is null");
                }

                var skinnedEffect = effect as SkinnedEffect;
                int boneCount = part.SkinnedBones.Count;
                if (skinnedEffect != null && boneCount > 0)
                {
                    var transforms = new Matrix[boneCount];
                    for (int j = 0; j < boneCount; j++)
                    {
                        var skinnedBone = part.SkinnedBones[j];
                        Matrix.Multiply(ref skinnedBone.OffsetMatrix, ref boneTransforms[skinnedBone.Bone.Index], out transforms[j]);
                    }

                    skinnedEffect.SetBoneTransforms(transforms);
                }

                int passCount = effect.CurrentTechnique.Passes.Count;
                for (int j = 0; j < passCount; j++)
                {
                    effect.CurrentTechnique.Passes[j].Apply();
                    part.Draw(context);
                }
            }
        }
        protected virtual void TrackEffect(Effect effect)
        {
            var fileList = compiler.LoadDependency(effect.RawEffectData.Arguments.DependencyFilePath);

            List<FileSystemWatcher> watchers;
            if (!effectsToWatcher.TryGetValue(effect, out watchers))
            {
                watchers = new List<FileSystemWatcher>();
                effectsToWatcher.Add(effect, watchers);
            }

            var dirList = GetDirectoryList(fileList);
            var currentWatchers = new List<FileSystemWatcher>();
            foreach (var dirPath in dirList)
            {
                // Try to find an existing watcher
                var watcher = FindWatcher(watchers, dirPath) ?? FindWatcher(watcherToEffects.Keys, dirPath);

                if (watcher == null)
                {
                    watcher = new FileSystemWatcher(dirPath);
                    var effectPerWatch = new List<Effect> { effect };
                    watcherToEffects.Add(watcher, effectPerWatch);
                    watcher.Changed += watcher_Changed;
                    watcher.EnableRaisingEvents = true;
                }
                else
                {
                    var effectPerWatch = watcherToEffects[watcher];
                    if (!effectPerWatch.Contains(effect))
                    {
                        effectPerWatch.Add(effect);
                    }
                }

                if (!watchers.Contains(watcher))
                {
                    watchers.Add(watcher);
                }

                if (!currentWatchers.Contains(watcher))
                {
                    currentWatchers.Add(watcher);
                }
            }

            // Release any previous watcher allocated that are no longer needed.
            foreach (var watcher in watchers)
            {
                if (!currentWatchers.Contains(watcher))
                {
                    RemoveEffectFromWatcher(effect, watcher);
                }
            }

            // Update the list of watchers for the specified effect
            watchers.Clear();
            watchers.AddRange(currentWatchers);
        }
        protected override void LoadContent()
        {
            base.LoadContent();

            spriteBatch = ToDisposeContent(new SpriteBatch(GraphicsDevice));
            texture = Content.Load<Texture2D>("Input");
            customEffect = Content.Load<Effect>("Effect");
        }
Пример #7
0
        public virtual void Initialize()
        {
            GraphicsDevice device = Engine.GraphicsContext.Device;

            wireFrame = EffectLoader.Load(@"World/Earth/Shaders/DeferredTerrain.fx");

            vertexBuffer = Buffer<TerrainVertex>.New<TerrainVertex>(device, SharpDX.Utilities.SizeOf<TerrainVertex>() * 4 * 1000, BufferFlags.VertexBuffer, SharpDX.Direct3D11.ResourceUsage.Dynamic);
        }
Пример #8
0
 public Monkey(Project2Game game, Model model, Vector3 position)
     : base(game, model, position)
 {
     // Load custom rainbox monkey effect
     effect = game.Content.Load<Effect>("Shaders\\Cel");
     PhysicsDescription.Mass = 20f;
     //PhysicsDescription.Tag = "player";
 }
Пример #9
0
 public Boid(Project2Game game, Flock flock, Model model, Vector3 position, Flock.BoidType boidType)
     : base(game, model, position)
 {
     this.health = maxHealth;
     this.PhysicsDescription.Mass = 0.25f;
     this.boidType = boidType;
     this.flock = flock;
     this.game.physics.World.CollisionSystem.CollisionDetected += HandleCollision;
     effect = game.Content.Load<Effect>("Shaders\\Cel");
 }
Пример #10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EffectDefaultParameters"/> struct.
 /// </summary>
 /// <param name="effect">The effect.</param>
 public EffectDefaultParameters(Effect effect)
 {
     // Initialize predefined parameters used by Model.Draw (to speedup things internally)
     WorldParameter = effect.Parameters["World"];
     ViewParameter = effect.Parameters["View"];
     ViewInverseParameter = effect.Parameters["ViewInverse"];
     ProjectionParameter = effect.Parameters["Projection"];
     WorldViewParameter = effect.Parameters["WorldView"];
     ViewProjectionParameter = effect.Parameters["ViewProjection"] ?? effect.Parameters["ViewProj"];
     WorldInverseTransposeParameter = effect.Parameters["WorldInverseTranspose"];
     WorldInverseTransposeViewParameter = effect.Parameters["WorldInverseTransposeView"];
     WorldViewProjectionParameter = effect.Parameters["WorldViewProj"] ?? effect.Parameters["WorldViewProjection"];
 }
Пример #11
0
        public GameModel(Model model, Game game, float x, float y, float z)
        {
            this.game = (Project2Game) game;
            this.model = model;
            effect = game.Content.Load<Effect>("ObjectShader");
            this.position = new Vector3(x, y, z);
            World = Matrix.Identity;

            lightPointPositions = new [] {
                new Vector3(0, 180, 0),
                new Vector3(-this.game.landscape.baord_size_public , 180, 0),
                new Vector3(this.game.landscape.baord_size_public, 180, this.game.landscape.baord_size_public)
            };
        }
Пример #12
0
        protected override void LoadContent()
        {
            // Importer for many models
            var importer = new AssimpImporter();

            // Load a specific model
            //string fileName = System.IO.Path.GetFullPath(Content.RootDirectory + "/tower.3ds");
            //Scene scene = importer.ImportFile(fileName, PostProcessSteps.MakeLeftHanded);
            //m_model = new Model(scene, GraphicsDevice, Content);

            // Load shader
            EffectCompilerFlags compilerFlags = EffectCompilerFlags.None;
            EffectCompiler      compiler      = new EffectCompiler();

#if DEBUG
            compilerFlags |= EffectCompilerFlags.Debug;
#endif
            var simpleShaderCompileResult = compiler.CompileFromFile(Content.RootDirectory + "/pointlight.fx", compilerFlags);
            if (simpleShaderCompileResult.HasErrors)
            {
                System.Console.WriteLine(simpleShaderCompileResult.Logger.Messages);
                System.Diagnostics.Debugger.Break();
            }
            m_simpleEffect = new SharpDX.Toolkit.Graphics.Effect(GraphicsDevice, simpleShaderCompileResult.EffectData);
            m_simpleEffect.Parameters["diffuseSampler"].SetResource(m_linearSamplerState);
            base.LoadContent();

            map = new Map(@"Content\map.PNG", new Size2(20, 20));
            map.LoadContent(GraphicsDevice, Content);

            player     = new Player(new Vector3(0.0f, 10.0f, 0.0f), GraphicsDevice);
            player.Map = map;

            spritebatch = new SpriteBatch(GraphicsDevice, 2048);



            compass       = Content.Load <Texture2D>("compass.png");
            torch         = Content.Load <Texture2D>("torchPlaceholder.png");
            compassNeedle = Content.Load <Texture2D>("needle.png");
            particle      = Content.Load <Texture2D>("particle.png");

            gameOver = Content.Load <Texture2D>("gameover.png");

            emitter.position = new Vector2(width - torch.Width / 3, height - torch.Height / 3);
        }
Пример #13
0
        protected override void LoadContent()
        {
            // Loads the effect
            metaTunnelEffect = Content.Load<Effect>("metatunnel.fxo");

            // Prepare a quad buffer
            quadVertices = Buffer.Vertex.New(
                GraphicsDevice,
                new[]
                    {
                        new VertexPositionTexture(new Vector3(-1, 1, 0), new Vector2(0, 0)),
                        new VertexPositionTexture(new Vector3(1, 1, 0), new Vector2(1, 0)),
                        new VertexPositionTexture(new Vector3(-1, -1, 0), new Vector2(0, 1)),
                        new VertexPositionTexture(new Vector3(1, -1, 0), new Vector2(1, 1)),
                    });

            // Create an input layout from the vertices
            inputLayout = VertexInputLayout.FromBuffer(0, quadVertices);
        }
Пример #14
0
        //  DepthStencilState _depthStencilDrawWhereNothing;
        public Background(GraphicsDevice graphicsDevice)
        {
            /*       var depthStencilStateDesc = SharpDX.Direct3D11.DepthStencilStateDescription.Default();
            depthStencilStateDesc.IsDepthEnabled = false;
            depthStencilStateDesc.DepthWriteMask = SharpDX.Direct3D11.DepthWriteMask.Zero;
            _noDepthState = DepthStencilState.New(graphicsDevice, "NoZBuffer", depthStencilStateDesc);*/

            EffectCompilerFlags compilerFlags = EffectCompilerFlags.None;
            #if DEBUG
            compilerFlags |= EffectCompilerFlags.Debug;
            #endif
            var shaderCompileResult = EffectCompiler.CompileFromFile("Content/sky.fx", compilerFlags);
            if (shaderCompileResult.HasErrors)
            {
                System.Console.WriteLine(shaderCompileResult.Logger.Messages);
                System.Diagnostics.Debugger.Break();
            }
            _effect = new SharpDX.Toolkit.Graphics.Effect(graphicsDevice, shaderCompileResult.EffectData);
        }
Пример #15
0
 /// <summary>
 /// Draws all of the ModelMeshPart objects in this mesh, using their current Effect settings.
 /// </summary>
 /// <param name="context">The graphics context.</param>
 /// <param name="effectOverride">The effect to use instead of the effect attached to each mesh part. Default is null (use Effect in MeshPart)</param>
 /// <exception cref="System.InvalidOperationException">Model has no effect</exception>
 public void Draw(GraphicsDevice context, Effect effectOverride = null)
 {
     int count = this.MeshParts.Count;
     for (int i = 0; i < count; i++)
     {
         ModelMeshPart part = MeshParts[i];
         Effect effect = effectOverride ?? part.Effect;
         if (effect == null)
         {
             throw new InvalidOperationException("ModelMeshPart has no effect and effectOverride is null");
         }
         int passCount = effect.CurrentTechnique.Passes.Count;
         for (int j = 0; j < passCount; j++)
         {
             effect.CurrentTechnique.Passes[j].Apply();
             part.Draw(context);
         }
     }
 }
Пример #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PrimitiveQuad" /> class.
        /// </summary>
        /// <param name="graphicsDevice">The graphics device.</param>
        public PrimitiveQuad(GraphicsDevice graphicsDevice)
        {
            GraphicsDevice = graphicsDevice;
            quadEffect = ToDispose(new Effect(GraphicsDevice, effectBytecode));
            quadPass = quadEffect.CurrentTechnique.Passes[0];
            matrixParameter = quadEffect.Parameters["MatrixTransform"];

            textureCopyPass = quadEffect.CurrentTechnique.Passes[1];
            textureParameter = quadEffect.Parameters["Texture"];
            colorParameter = quadEffect.Parameters["Color"];
            textureSamplerParameter = quadEffect.Parameters["TextureSampler"];

            // Default LinearClamp
            textureSamplerParameter.SetResource(GraphicsDevice.SamplerStates.LinearClamp);

            Transform = Matrix.Identity;
            Color = new Color4(1.0f);

            sharedData = GraphicsDevice.GetOrCreateSharedData(SharedDataType.PerDevice, "Toolkit::PrimitiveQuad::VertexBuffer", () => new SharedData(GraphicsDevice));
        }
Пример #17
0
        public static void drawModel(Model model, GraphicsDevice graphicsDevice, SharpDX.Toolkit.Graphics.Effect effect, Matrix transformation, Player player, GameTime gameTime)
        {
            // Fill the one constant buffer. Hint: it is not necessary to set
            // things which did not change each frame. But in our case everything
            // is changing
            var transformCB = effect.ConstantBuffers["Transforms"];

            transformCB.Parameters["worldViewProj"].SetValue(transformation * player.Cam.ViewProjection);
            transformCB.Parameters["world"].SetValue(transformation);
            Matrix worldInvTr = Helpers.CreateInverseTranspose(ref transformation);

            transformCB.Parameters["worldInvTranspose"].SetValue(worldInvTr);

            // Slow rotating light
            double angle = -gameTime.TotalGameTime.TotalMilliseconds / 3000.0;

            //transformCB.Parameters["lightPos"].SetValue(new Vector3((float)Math.Sin(angle) * 50.0f, 30.0f, (float)Math.Cos(angle) * 50.0f));
            //transformCB.Parameters["lightPos"].SetValue(player.Position);

            // Draw model
            //effect.CurrentTechnique.Passes[0].Apply();
            model.Draw(graphicsDevice, effect);
        }
Пример #18
0
        public VisionEffect(Effect effect, SamplerState samplerState = null)
        {
            GraphicsDevice = effect.GraphicsDevice;
            Effect = effect;
            Name = effect.Name;

            _epTextureSampler = effect.Parameters["TextureSampler"];
            if(_epTextureSampler!=null)
                Sampler = samplerState ?? GraphicsDevice.SamplerStates.LinearWrap;

            _epWorld = effect.Parameters["World"];
            _epWorldInverseTranspose = effect.Parameters["WorldInverseTranspose"];
            _epView = effect.Parameters["View"];
            _epProjection = effect.Parameters["Projection"];
            _epCameraPosition = effect.Parameters["CameraPosition"];
            _epClipPlane = effect.Parameters["ClipPlane"];
            _epSunlightDirection = effect.Parameters["SunlightDirection"];
            _epTexture = effect.Parameters["Texture"];
            _epDiffuseColor = effect.Parameters["DiffuseColor"];

            _epDoShadowMapping = effect.Parameters["DoShadowMapping"];
            _epShadowMap = effect.Parameters["ShadowMap"];
            _epShadowViewProjection = effect.Parameters["ShadowViewProjection"];
            _epShadowFarPlane = effect.Parameters["ShadowFarPlane"];
            _epShadowMult = effect.Parameters["ShadowMult"];

            _techStandard = effect.Techniques["TechStandard"];
            _techClipPlane = effect.Techniques["TechClipPlane"];
            _techDepthMap = effect.Techniques["TechDepthMap"];

            //Debug.Assert( _epView != null );
            //Debug.Assert(_techDepthMap != null);

            if ( _epSunlightDirection != null)
                _epSunlightDirection.SetValue(VisionContent.SunlightDirection);
        }
Пример #19
0
 private void RemoveEffect(Effect effect)
 {
     if (effect.IsSupportingDynamicCompilation)
     {
         lock (effectsCompilable)
         {
             effectsCompilable.Remove(effect);
             UnTrackEffect(effect);
         }
     }
 }
Пример #20
0
 private void AddEffect(Effect effect)
 {
     if (effect.IsSupportingDynamicCompilation)
     {
         lock (effectsCompilable)
         {
             effectsCompilable.Add(effect);
             TrackEffect(effect);
         }
     }
 }
 protected virtual void UnTrackEffect(Effect effect)
 {
     effectsToAlwaysCheck.Remove(effect);
 }
Пример #22
0
        /// <summary>
        /// Render a model after applying the matrix transformations.
        /// </summary>
        /// <param name="context">The <see cref="GraphicsDevice"/> context.</param>
        /// <param name="world">A world transformation matrix.</param>
        /// <param name="view">A view transformation matrix.</param>
        /// <param name="projection">A projection transformation matrix.</param>
        /// <param name="effectOverride">An effect instance that will override all effects attached to this model. Null by default (no override)</param>
        /// <exception cref="System.InvalidOperationException">Mesh has no effect and effectOverride is null</exception>
        public unsafe void Draw(GraphicsDevice context, Matrix world, Matrix view, Matrix projection, Effect effectOverride = null)
        {
            int     count     = Meshes.Count;
            int     boneCount = Bones.Count;
            Matrix *localSharedDrawBoneMatrices = stackalloc Matrix[boneCount]; // TODO use a global cache as BoneCount could generate a StackOverflow

            CopyAbsoluteBoneTransformsTo(new IntPtr(localSharedDrawBoneMatrices));

            var defaultParametersContext = default(EffectDefaultParametersContext);

            for (int i = 0; i < count; i++)
            {
                var mesh        = Meshes[i];
                int index       = mesh.ParentBone.Index;
                int effectCount = mesh.Effects.Count;

                if (effectOverride != null)
                {
                    Matrix worldTranformed;
                    Matrix.Multiply(ref localSharedDrawBoneMatrices[index], ref world, out worldTranformed);

                    effectOverride.DefaultParameters.Apply(ref defaultParametersContext, ref worldTranformed, ref view, ref projection);
                }
                else
                {
                    for (int j = 0; j < effectCount; j++)
                    {
                        var effect = mesh.Effects[j];
                        if (effect == null)
                        {
                            throw new InvalidOperationException("Mesh has no effect and effectOverride is null");
                        }

                        Matrix worldTranformed;
                        Matrix.Multiply(ref localSharedDrawBoneMatrices[index], ref world, out worldTranformed);

                        var matrices = effect as IEffectMatrices;
                        if (matrices == null)
                        {
                            effect.DefaultParameters.Apply(ref defaultParametersContext, ref worldTranformed, ref view, ref projection);
                        }
                        else
                        {
                            matrices.World      = worldTranformed;
                            matrices.View       = view;
                            matrices.Projection = projection;
                        }
                    }
                }

                mesh.Draw(context, effectOverride);
            }
        }
Пример #23
0
 // Updates the parameters
 public void SetLighting(Effect effect)
 {
     effect.Parameters["lightAmbCol"].SetValue(ambientCol);
     effect.Parameters["lights"].SetValue(packedLights);
 }
Пример #24
0
        /// <summary>
        /// Draws the specified effect onto the quad. The effect must have a pixel shader with the signature float2:TEXCOORD.
        /// </summary>
        /// <param name="effect">The effect.</param>
        /// <param name="fullScreenTriangle">if set to <c>true</c> to draw an optimized full screen triangle as a full screen quad.</param>
        public void Draw(Effect effect, bool fullScreenTriangle = false)
        {
            GraphicsDevice.SetVertexBuffer(fullScreenTriangle ? sharedData.VertexBufferFullQuad : sharedData.VertexBuffer);
            GraphicsDevice.SetVertexInputLayout(sharedData.VertexInputLayout);
            ResetShaderStages();

            foreach (var pass in effect.CurrentTechnique.Passes)
            {
                // Apply the Effect pass
                pass.Apply();

                // Make sure that we are using our vertex shader
                quadPass.Apply();

                GraphicsDevice.Draw(PrimitiveType.TriangleStrip, fullScreenTriangle ? 3 : 4);

                // Reset the quadPass and custom pass
                quadPass.UnApply();
                pass.UnApply();
            }

            // Reset the vertex buffer
            GraphicsDevice.SetVertexBuffer(0, null, 0);
            GraphicsDevice.InputAssemblerStage.SetInputLayout(null);
        }
Пример #25
0
        protected override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            // check if data needs to be recreated
            if (_data.IsDirty)
            {
                // dispose old effect
                Utilities.Dispose(ref _effect);

                // rebuild the effect
                var effectData = _builder.Rebuild();
                if (effectData != null)
                    // instantiate new effect from the built data
                    _effect = ToDispose(new Effect(GraphicsDevice, effectData));
            }
        }
Пример #26
0
        /// <summary>
        /// Binds the specified effect data to this instance.
        /// </summary>
        /// <param name="effectDataArg">The effect data arg.</param>
        /// <param name="cloneFromEffect">The clone from effect.</param>
        /// <exception cref="System.InvalidOperationException">If no techniques found in this effect.</exception>
        /// <exception cref="System.ArgumentException">If unable to find effect [effectName] from the EffectPool.</exception>
        internal void InitializeFrom(EffectData.Effect effectDataArg, Effect cloneFromEffect)
        {
            RawEffectData = effectDataArg;

            // Clean any previously allocated resources
            if (DisposeCollector != null)
            {
                DisposeCollector.DisposeAndClear();
            }
            ConstantBuffers.Clear();
            Parameters.Clear();
            Techniques.Clear();
            ResourceLinker = ToDispose(new EffectResourceLinker());
            if (effectConstantBuffersCache != null)
            {
                effectConstantBuffersCache.Clear();
            }

            // Copy data
            IsSupportingDynamicCompilation = RawEffectData.Arguments != null;
            ShareConstantBuffers = RawEffectData.ShareConstantBuffers;

            // Create the local effect constant buffers cache
            if (!ShareConstantBuffers)
                effectConstantBuffersCache = new Dictionary<EffectConstantBufferKey, EffectConstantBuffer>();

            var logger = new Logger();
            int techniqueIndex = 0;
            int totalPassCount = 0;
            EffectPass parentPass = null;
            foreach (var techniqueRaw in RawEffectData.Techniques)
            {
                var name = techniqueRaw.Name;
                if (string.IsNullOrEmpty(name))
                    name = string.Format("${0}", techniqueIndex++);

                var technique = new EffectTechnique(this, name);
                Techniques.Add(technique);

                int passIndex = 0;
                foreach (var passRaw in techniqueRaw.Passes)
                {
                    name = passRaw.Name;
                    if (string.IsNullOrEmpty(name))
                        name = string.Format("${0}", passIndex++);

                    var pass = new EffectPass(logger, this, technique, passRaw, name);

                    pass.Initialize(logger);

                    // If this is a subpass, add it to the parent pass
                    if (passRaw.IsSubPass)
                    {
                        if (parentPass == null)
                        {
                            logger.Error("Pass [{0}] is declared as a subpass but has no parent.");
                        }
                        else
                        {
                            parentPass.SubPasses.Add(pass);
                        }
                    }
                    else
                    {
                        technique.Passes.Add(pass);
                        parentPass = pass;
                    }
                }

                // Count the number of passes
                totalPassCount += technique.Passes.Count;
            }

            if (totalPassCount == 0)
                throw new InvalidOperationException("No passes found in this effect.");

            // Log all the exception in a single throw
            if (logger.HasErrors)
                throw new InvalidOperationException(Utilities.Join("\n", logger.Messages));

            // Initialize the resource linker when we are done with all pass/parameters
            ResourceLinker.Initialize();

            //// Sort all parameters by their resource types
            //// in order to achieve better local cache coherency in resource linker
            Parameters.Items.Sort((left, right) =>
                {
                    // First, order first all value types, then resource type
                    var comparison = left.IsValueType != right.IsValueType ? left.IsValueType ? -1 : 1 : 0;

                    // If same type
                    if (comparison == 0)
                    {
                        // Order by resource type
                        comparison = ((int)left.ResourceType).CompareTo((int)right.ResourceType);

                        // If same, order by resource index
                        if (comparison == 0)
                        {
                            comparison = left.Offset.CompareTo(right.Offset);
                        }
                    }
                    return comparison;
                });

            // Prelink constant buffers
            int resourceIndex = 0;
            foreach (var parameter in Parameters)
            {
                // Recalculate parameter resource index
                if (!parameter.IsValueType)
                {
                    parameter.Offset = resourceIndex++;
                }

                // Set the default values 
                parameter.SetDefaultValue();

                if (parameter.ResourceType == EffectResourceType.ConstantBuffer)
                    parameter.SetResource(ConstantBuffers[parameter.Name]);
            }

            // Compute slot links
            foreach (var technique in Techniques)
            {
                foreach (var pass in technique.Passes)
                {
                    foreach (var subPass in pass.SubPasses)
                    {
                        subPass.ComputeSlotLinks();
                    }
                    pass.ComputeSlotLinks();
                }
            }

            // Setup the first Current Technique.
            CurrentTechnique = this.Techniques[0];

            // Initialize predefined parameters used by Model.Draw (to speedup things internally)
            DefaultParameters = new EffectDefaultParameters(this);

            // If this is a clone, we need to 
            if (cloneFromEffect != null)
            {
                // Copy the content of the constant buffers to the new instance.
                for (int i = 0; i < ConstantBuffers.Count; i++)
                {
                    cloneFromEffect.ConstantBuffers[i].CopyTo(ConstantBuffers[i]);
                }

                // Copy back all bound resources except constant buffers
                // that are already initialized with InitializeFrom method.
                for (int i = 0; i < cloneFromEffect.ResourceLinker.Count; i++)
                {
                    if (cloneFromEffect.ResourceLinker.BoundResources[i] is EffectConstantBuffer)
                        continue;

                    ResourceLinker.BoundResources[i] = cloneFromEffect.ResourceLinker.BoundResources[i];
                    unsafe
                    {
                        ResourceLinker.Pointers[i] = cloneFromEffect.ResourceLinker.Pointers[i];
                    }
                }

                // If everything was fine, then we can register it into the pool
                Pool.AddEffect(this);
            }

            // Allow subclasses to complete initialization.
            Initialize();
        }
Пример #27
0
        /// <summary>
        /// Render a model after applying the matrix transformations.
        /// </summary>
        /// <param name="context">The <see cref="GraphicsDevice"/> context.</param>
        /// <param name="world">A world transformation matrix.</param>
        /// <param name="view">A view transformation matrix.</param>
        /// <param name="projection">A projection transformation matrix.</param>
        /// <param name="effectOverride">An effect instance that will override all effects attached to this model. Null by default (no override)</param>
        /// <exception cref="System.InvalidOperationException">Mesh has no effect and effectOverride is null</exception>
        public unsafe void Draw(GraphicsDevice context, Matrix world, Matrix view, Matrix projection, Effect effectOverride = null)
        {
            int count     = Meshes.Count;
            int boneCount = Bones.Count;

            if (sharedDrawBones == null || sharedDrawBones.Length < boneCount)
            {
                sharedDrawBones = new Matrix[boneCount];
            }

            CopyAbsoluteBoneTransformsTo(sharedDrawBones);

            var defaultParametersContext = default(EffectDefaultParametersContext);

            for (int i = 0; i < count; i++)
            {
                var mesh        = Meshes[i];
                int index       = mesh.ParentBone.Index;
                int effectCount = mesh.Effects.Count;

                if (effectOverride != null)
                {
                    if (effectOverride is SkinnedEffect)
                    {
                        effectOverride.DefaultParameters.Apply(ref defaultParametersContext, ref world, ref view, ref projection);
                    }
                    else
                    {
                        Matrix worldTranformed;
                        Matrix.Multiply(ref sharedDrawBones[index], ref world, out worldTranformed);
                        effectOverride.DefaultParameters.Apply(ref defaultParametersContext, ref worldTranformed, ref view, ref projection);
                    }
                }
                else
                {
                    for (int j = 0; j < effectCount; j++)
                    {
                        var effect = mesh.Effects[j];
                        if (effect == null)
                        {
                            throw new InvalidOperationException("Mesh has no effect and effectOverride is null");
                        }

                        Matrix worldTranformed;
                        Matrix.Multiply(ref sharedDrawBones[index], ref world, out worldTranformed);

                        var matrices = effect as IEffectMatrices;
                        if (matrices == null)
                        {
                            effect.DefaultParameters.Apply(ref defaultParametersContext, ref world, ref view, ref projection);
                        }
                        else
                        {
                            matrices.World      = effect is SkinnedEffect ? world : worldTranformed;
                            matrices.View       = view;
                            matrices.Projection = projection;
                        }
                    }
                }

                mesh.Draw(context, sharedDrawBones, effectOverride);
            }
        }
Пример #28
0
        public void Draw(Player player, GraphicsDevice graphicsDevice, SharpDX.Toolkit.Graphics.Effect effect, GameTime gameTime)
        {
            Matrix transformation = Matrix.Identity;

            if (player.IsMoving)
            {
                player.Height = (float)Math.Pow(Math.Sin(player.MovingTime.TotalSeconds * 5), 2) * 0.8f + 15;
            }
            else
            {
                player.Height = Math.Max(player.Height - 3f * (float)gameTime.ElapsedGameTime.TotalSeconds, 15);
            }
            var transformCB = effect.ConstantBuffers["Transforms"];

            transformCB.Parameters["worldViewProj"].SetValue(player.Cam.viewProjection);
            transformCB.Parameters["world"].SetValue(ref player.Cam.view);
            Matrix worldInvTr = Helpers.CreateInverseTranspose(ref player.Cam.view);

            transformCB.Parameters["worldInvTranspose"].SetValue(ref worldInvTr);
            transformCB.Parameters["cameraPos"].SetValue(player.Position);

            var lightCB = effect.ConstantBuffers["Lights"];

            lightCB.Parameters["lightDir"].SetValue(new Vector3(0));
            lightCB.Parameters["specularPower"].SetValue(0);
            lightCB.Parameters["dirLightColor"].SetValue(new Vector3(0.0f));
            lightCB.Parameters["numPointLights"].SetValue(1);

            PointLight[] pointLights = new PointLight[1];

            pointLights[0].Set(10.0f, 60.0f + 7.5f + (player.IsMoving ? 2 : 1) * 2 * (float)Math.Pow(Math.Sin(gameTime.TotalGameTime.TotalMilliseconds / 150), 1) * 2);
            pointLights[0].pos = player.Position;
            //pointLights[0].color = (Vector3.Lerp(Color.White.ToVector3(), Vector3.Lerp(Color.DarkOrange.ToVector3(), Color.Yellow.ToVector3(), (float)(Math.Pow(Math.Sin(gameTime.TotalGameTime.TotalMilliseconds / 600), 2f)) * 0.5f), 0.5f));
            pointLights[0].color = Color.White.ToVector3() * 0.5f;

            lightCB.Parameters["lights"].SetValue(pointLights);

            Point     playerTilePosition = worldToTileCoordinates(player.Position);
            const int DRAWING_RANGE      = 5;

            for (int x = playerTilePosition.X - DRAWING_RANGE; x <= playerTilePosition.X + DRAWING_RANGE; ++x)
            {
                for (int y = playerTilePosition.Y - DRAWING_RANGE; y <= playerTilePosition.Y + DRAWING_RANGE; ++y)
                {
                    transformation = Matrix.Translation((x + 0.5f) * tileSize.Width, -player.Height, (y + 0.5f) * tileSize.Height);
                    if (x >= 0 && y >= 0 && x <= tiles.GetUpperBound(0) && y <= tiles.GetUpperBound(1))
                    {
                        switch (tiles[x, y])
                        {
                        case TileType.Wall:
                            Helpers.drawModel(wallModel, graphicsDevice, effect, transformation, player, gameTime);
                            break;
                        }
                    }
                    else
                    {
                        Helpers.drawModel(wallModel, graphicsDevice, effect, transformation, player, gameTime);
                    }
                    transformation *= Matrix.Translation(0, 25, 0);
                    Helpers.drawModel(ceilingModel, graphicsDevice, effect, transformation, player, gameTime);
                }
            }
            for (int x = playerTilePosition.X - DRAWING_RANGE; x <= playerTilePosition.X + DRAWING_RANGE; ++x)
            {
                for (int y = playerTilePosition.Y - DRAWING_RANGE; y <= playerTilePosition.Y + DRAWING_RANGE; ++y)
                {
                    if (x >= 0 && y >= 0 && x <= tiles.GetUpperBound(0) && y <= tiles.GetUpperBound(1))
                    {
                        switch (tiles[x, y])
                        {
                        case TileType.Wall:
                            transformation = Matrix.Translation((x + 0.5f) * tileSize.Width, -player.Height, (y + 0.5f) * tileSize.Height);
                            Helpers.drawModel(wallModel, graphicsDevice, effect, transformation, player, gameTime);
                            break;
                        }
                    }
                }
            }
            for (int x = playerTilePosition.X - DRAWING_RANGE; x <= playerTilePosition.X + DRAWING_RANGE; ++x)
            {
                for (int y = playerTilePosition.Y - DRAWING_RANGE; y <= playerTilePosition.Y + DRAWING_RANGE; ++y)
                {
                    if (x >= 0 && y >= 0 && x <= tiles.GetUpperBound(0) && y <= tiles.GetUpperBound(1))
                    {
                        switch (tiles[x, y])
                        {
                        case TileType.Floor_With_Key:
                            transformation = Matrix.Translation((x + 0.5f) * tileSize.Width, -player.Height, (y + 0.5f) * tileSize.Height);
                            Helpers.drawModel(floorKeyModel, graphicsDevice, effect, transformation, player, gameTime);
                            Helpers.drawModel(floorModel, graphicsDevice, effect, transformation, player, gameTime);
                            break;
                        }
                    }
                }
            }
            for (int x = playerTilePosition.X - DRAWING_RANGE; x <= playerTilePosition.X + DRAWING_RANGE; ++x)
            {
                for (int y = playerTilePosition.Y - DRAWING_RANGE; y <= playerTilePosition.Y + DRAWING_RANGE; ++y)
                {
                    if (x >= 0 && y >= 0 && x <= tiles.GetUpperBound(0) && y <= tiles.GetUpperBound(1))
                    {
                        switch (tiles[x, y])
                        {
                        case TileType.Door:
                            transformation = Matrix.Translation((x + 0.5f) * tileSize.Width, -player.Height, (y + 0.5f) * tileSize.Height);
                            Helpers.drawModel(doorModel, graphicsDevice, effect, transformation, player, gameTime);
                            break;
                        }
                    }
                }
            }
            for (int x = playerTilePosition.X - DRAWING_RANGE; x <= playerTilePosition.X + DRAWING_RANGE; ++x)
            {
                for (int y = playerTilePosition.Y - DRAWING_RANGE; y <= playerTilePosition.Y + DRAWING_RANGE; ++y)
                {
                    if (x >= 0 && y >= 0 && x <= tiles.GetUpperBound(0) && y <= tiles.GetUpperBound(1))
                    {
                        switch (tiles[x, y])
                        {
                        case TileType.Floor:
                            transformation = Matrix.Translation((x + 0.5f) * tileSize.Width, -player.Height, (y + 0.5f) * tileSize.Height);
                            Helpers.drawModel(floorModel, graphicsDevice, effect, transformation, player, gameTime);
                            break;
                        }
                    }
                }
            }
            for (int x = playerTilePosition.X - DRAWING_RANGE; x <= playerTilePosition.X + DRAWING_RANGE; ++x)
            {
                for (int y = playerTilePosition.Y - DRAWING_RANGE; y <= playerTilePosition.Y + DRAWING_RANGE; ++y)
                {
                    if (x >= 0 && y >= 0 && x <= tiles.GetUpperBound(0) && y <= tiles.GetUpperBound(1))
                    {
                        switch (tiles[x, y])
                        {
                        case TileType.Goal:
                            transformation = Matrix.Translation((x + 0.5f) * tileSize.Width, -player.Height, (y + 0.5f) * tileSize.Height);
                            Helpers.drawModel(floorModel, graphicsDevice, effect, transformation, player, gameTime);
                            break;
                        }
                    }
                }
            }
        }
Пример #29
0
 protected override void LoadContent()
 {
     _genGBuffer = new Effect(GraphicsDevice, VectorUtils.CompileEffect("shaders/genGBuffer.hlsl"));
     _genShadowBuffer = new Effect(GraphicsDevice, VectorUtils.CompileEffect("shaders/genShadowBuffer.hlsl"));
     _shadeGBuffer = new ShadeGBufferEffect(GraphicsDevice);
     _sponzaMeshes = ToGfxMeshes(LoadObj(@"assets/obj/crytek-sponza/sponza.obj"));
     _headMesh = ToGfxMeshes(LoadObj(@"assets/obj/head/head.obj"));
     base.LoadContent();
 }
        private void RemoveEffectFromWatcher(Effect effect, FileSystemWatcher watcher)
        {
            var listOfEffect = watcherToEffects[watcher];
            listOfEffect.Remove(effect);

            if (listOfEffect.Count == 0)
            {
                watcher.EnableRaisingEvents = false;
                watcher.Changed -= watcher_Changed;
                watcher.Dispose();
                watcherToEffects.Remove(watcher);
            }
        }
Пример #31
0
 public EffectToRebind(Effect effect, EffectData effectData)
 {
     Effect = effect;
     EffectData = effectData;
 }
Пример #32
0
        public Platform(ProjectGame game)
        {
            // Avoid null reference, it changes on the first update
            if (standing_platform == null)
            {
                standing_platform = this;
                next_standing_platform = this;
            }

            // Less tiles if the difficulty is higher
            min_extra_tiles = (int)(max_extra_tiles - game.difficulty);
            type = GameObjectType.Platform;

            //Load textures
            textureName = "Platform_Textures";
            texture = game.Content.Load<Texture2D>(textureName);

            // Store information of the platform and create information for the next one
            platform = next_platform;
            next_platform = create_platform(platform);

            // Create the vertices based on the platform information
            VertexPositionNormalTexture[] platform_vertices = create_vertices(platform, last_platform, next_platform);
            last_platform = platform;

            // Set the platform Z position of the intance and uptade the new Z position for the next one
            z_position_start = z_position;
            z_position -= tile_depth;
            z_position_end = z_position;

            // Calculates midpoint and base
            platfom_midpoint = (platform.GetLength(0) * tile_width) - tile_width/2;
            platform_base = Levels[0] - base_offset;

            //Load effects
            effect = game.Content.Load<Effect>("Phong");
            lightManager = new LightManager(game);
            lightManager.SetLighting(effect);

            // Pass the vertices data
            vertices = Buffer.Vertex.New(game.GraphicsDevice, platform_vertices);
            inputLayout = VertexInputLayout.FromBuffer(0, vertices);
            this.game = game;
        }
Пример #33
0
 /// <summary>
 /// Draws this <see cref="GeometricPrimitive" /> using an optional effect. See remarks.
 /// </summary>
 /// <param name="effect">The effect. Null by default.</param>
 /// <remarks>If an effect is passed to this method, a draw will be issued for each passes defined in the current technique of the effect.
 /// If no effect are passed, it is expected that an <see cref="EffectPass"/> was previously applied.
 /// </remarks>
 public void Draw(Effect effect = null)
 {
     Draw(GraphicsDevice, effect);
 }
Пример #34
0
        public void Initialize()
        {
            cube = GeometricPrimitive.Cube.New(graphicsDevice);
             var cubeBounds = new OrientedBoundingBox(new Vector3(-0.5f, -0.5f, -0.5f), new Vector3(0.5f, 0.5f, 0.5f));
             cubeMesh = new RenderMesh {
            BoundingBox = cubeBounds,
            IndexBuffer = cube.IndexBuffer,
            IsIndex32Bits = cube.IsIndex32Bits,
            InputLayout = VertexInputLayout.New<VertexPositionNormalTexture>(0),
            ModelTransform = Matrix.Identity,
            VertexBuffer = cube.VertexBuffer
             };

             basicEffect = new BasicEffect(graphicsDevice);
             basicEffect.EnableDefaultLighting(); // enable default lightning, useful for quick prototyping

             var debugEffectCompilerResult = new EffectCompiler().CompileFromFile("shaders/debug_solid.hlsl", EffectCompilerFlags.Debug);
             debugEffect = new Effect(graphicsDevice, debugEffectCompilerResult.EffectData, graphicsDevice.DefaultEffectPool);
             debugBatch = new PrimitiveBatch<VertexPositionColor>(graphicsDevice);
        }
Пример #35
0
        /// <summary>
        /// Render a model after applying the matrix transformations.
        /// </summary>
        /// <param name="context">The <see cref="GraphicsDevice"/> context.</param>
        /// <param name="world">A world transformation matrix.</param>
        /// <param name="view">A view transformation matrix.</param>
        /// <param name="projection">A projection transformation matrix.</param>
        /// <param name="effectOverride">An effect instance that will override all effects attached to this model. Null by default (no override)</param>
        /// <exception cref="System.InvalidOperationException">Mesh has no effect and effectOverride is null</exception>
        public unsafe void Draw(GraphicsDevice context, Matrix world, Matrix view, Matrix projection, Effect effectOverride = null)
        {
            int count = Meshes.Count;
            int boneCount = Bones.Count;

            if (sharedDrawBones == null || sharedDrawBones.Length < boneCount)
            {
                sharedDrawBones = new Matrix[boneCount];
            }

            CopyAbsoluteBoneTransformsTo(sharedDrawBones);

            var defaultParametersContext = default(EffectDefaultParametersContext);

            for (int i = 0; i < count; i++)
            {
                var mesh = Meshes[i];
                int index = mesh.ParentBone.Index;
                int effectCount = mesh.Effects.Count;

                if (effectOverride != null)
                {
                    if (effectOverride is SkinnedEffect)
                    {
                        effectOverride.DefaultParameters.Apply(ref defaultParametersContext, ref world, ref view, ref projection);
                    }
                    else
                    {
                        Matrix worldTranformed;
                        Matrix.Multiply(ref sharedDrawBones[index], ref world, out worldTranformed);
                        effectOverride.DefaultParameters.Apply(ref defaultParametersContext, ref worldTranformed, ref view, ref projection);
                    }
                }
                else
                {
                    for (int j = 0; j < effectCount; j++)
                    {
                        var effect = mesh.Effects[j];
                        if (effect == null)
                        {
                            throw new InvalidOperationException("Mesh has no effect and effectOverride is null");
                        }

                        Matrix worldTranformed;
                        Matrix.Multiply(ref sharedDrawBones[index], ref world, out worldTranformed);

                        var matrices = effect as IEffectMatrices;
                        if (matrices == null)
                        {
                            effect.DefaultParameters.Apply(ref defaultParametersContext, ref world, ref view, ref projection);
                        }
                        else
                        {
                            matrices.World = effect is SkinnedEffect ? world : worldTranformed;
                            matrices.View = view;
                            matrices.Projection = projection;
                        }
                    }
                }

                mesh.Draw(context, sharedDrawBones, effectOverride);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="EffectCompilerEventArgs" /> class.
 /// </summary>
 /// <param name="effect">The effect.</param>
 /// <param name="messages">The log messages.</param>
 public EffectCompilerEventArgs(Effect effect, IList<LogMessage> messages = null)
 {
     Effect = effect;
     Messages = new ReadOnlyCollection<LogMessage>(messages ?? EmptyLogMessages);
 }