Пример #1
0
        /// <summary>
        /// Looks up shortcut references to our effect parameters.
        /// </summary>
        void CacheEffectParameters(SkinnedEffect cloneSource)
        {
            textureParam               = Parameters["Texture"];
            diffuseColorParam          = Parameters["DiffuseColor"];
            emissiveColorParam         = Parameters["EmissiveColor"];
            specularColorParam         = Parameters["SpecularColor"];
            specularPowerParam         = Parameters["SpecularPower"];
            eyePositionParam           = Parameters["EyePosition"];
            fogColorParam              = Parameters["FogColor"];
            fogVectorParam             = Parameters["FogVector"];
            worldParam                 = Parameters["World"];
            worldInverseTransposeParam = Parameters["WorldInverseTranspose"];
            worldViewProjParam         = Parameters["WorldViewProj"];
            bonesParam                 = Parameters["Bones"];
            shaderIndexParam           = Parameters["ShaderIndex"];

            light0 = new DirectionalLight(Parameters["DirLight0Direction"],
                                          Parameters["DirLight0DiffuseColor"],
                                          Parameters["DirLight0SpecularColor"],
                                          (cloneSource != null) ? cloneSource.light0 : null);

            light1 = new DirectionalLight(Parameters["DirLight1Direction"],
                                          Parameters["DirLight1DiffuseColor"],
                                          Parameters["DirLight1SpecularColor"],
                                          (cloneSource != null) ? cloneSource.light1 : null);

            light2 = new DirectionalLight(Parameters["DirLight2Direction"],
                                          Parameters["DirLight2DiffuseColor"],
                                          Parameters["DirLight2SpecularColor"],
                                          (cloneSource != null) ? cloneSource.light2 : null);
        }
        public void Draw(ref Matrix[] transformMatrices, ref SkinnedEffect skinnedEffect)
        {
            int totalInstances = transformMatrices.Length;
            BasicEffect effect = (BasicEffect)originalModel.Meshes[0].MeshParts[0].Effect;
            skinnedEffect.Texture = effect.Texture;

            graphicsDevice.SetVertexBuffer(instancedVertexBuffer);
            graphicsDevice.Indices = instancedIndexBuffer;

            for (int i = 0; i < totalInstances; i += maxInstances)
            {
                // How many instances can we fit into this batch?
                int instanceCount = totalInstances - i;

                if (instanceCount > maxInstances)
                    instanceCount = maxInstances;

                // Upload transform matrices as shader constants.
                Array.Copy(transformMatrices, i, tempMatrices, 0, instanceCount);

                // *transformMatrices[i];
                skinnedEffect.SetBoneTransforms(tempMatrices);

                foreach (EffectPass pass in skinnedEffect.CurrentTechnique.Passes)
                {
                    pass.Apply();

                    graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0,
                        instanceCount * originalVertexCount, 0, instanceCount * originalIndexCount / 3);
                }
            }
        }
Пример #3
0
        private static void ApplyMaterial(SkinnedEffect effect, Material material)
        {
            effect.DiffuseColor = material.DiffuseColor;
            effect.EmissiveColor = material.EmissiveColor;
            effect.SpecularColor = material.SpecularColor;
            effect.SpecularPower = material.SpecularPower;

            if (material.Texture.IsNotNull() && effect.Texture.IsNull())
                effect.Texture = material.Texture;
        }
Пример #4
0
 protected SkinnedEffect(SkinnedEffect cloneSource)
     : base((Effect)cloneSource)
 {
     this.CacheEffectParameters(cloneSource);
     this.preferPerPixelLighting = cloneSource.preferPerPixelLighting;
     this.fogEnabled             = cloneSource.fogEnabled;
     this.world             = cloneSource.world;
     this.view              = cloneSource.view;
     this.projection        = cloneSource.projection;
     this.diffuseColor      = cloneSource.diffuseColor;
     this.emissiveColor     = cloneSource.emissiveColor;
     this.ambientLightColor = cloneSource.ambientLightColor;
     this.alpha             = cloneSource.alpha;
     this.fogStart          = cloneSource.fogStart;
     this.fogEnd            = cloneSource.fogEnd;
     this.weightsPerVertex  = cloneSource.weightsPerVertex;
 }
Пример #5
0
        public ExampleModelClass(AnimationModelContent model, SkinnedEffect effect)
        {
            this.model = model;
            this.effect = effect;

            skeleton = model.GetSkeleton();
            animationStates = new List<AnimationState>();

            for (int i = 0; i < model.GetAnimationCount(); i++)
            {
                Animation animation = model.GetAnimation(i);
                AnimationState state = new AnimationState(animation);
                animationStates.Add(state);
            }

            animationTransforms = new Matrix[skeleton.GetBoneCount()];
        }
Пример #6
0
 private void CacheEffectParameters(SkinnedEffect cloneSource)
 {
     this.textureParam               = this.Parameters["Texture"];
     this.diffuseColorParam          = this.Parameters["DiffuseColor"];
     this.emissiveColorParam         = this.Parameters["EmissiveColor"];
     this.specularColorParam         = this.Parameters["SpecularColor"];
     this.specularPowerParam         = this.Parameters["SpecularPower"];
     this.eyePositionParam           = this.Parameters["EyePosition"];
     this.fogColorParam              = this.Parameters["FogColor"];
     this.fogVectorParam             = this.Parameters["FogVector"];
     this.worldParam                 = this.Parameters["World"];
     this.worldInverseTransposeParam = this.Parameters["WorldInverseTranspose"];
     this.worldViewProjParam         = this.Parameters["WorldViewProj"];
     this.bonesParam                 = this.Parameters["Bones"];
     this.light0 = new DirectionalLight(this.Parameters["DirLight0Direction"], this.Parameters["DirLight0DiffuseColor"], this.Parameters["DirLight0SpecularColor"], cloneSource != null ? cloneSource.light0 : (DirectionalLight)null);
     this.light1 = new DirectionalLight(this.Parameters["DirLight1Direction"], this.Parameters["DirLight1DiffuseColor"], this.Parameters["DirLight1SpecularColor"], cloneSource != null ? cloneSource.light1 : (DirectionalLight)null);
     this.light2 = new DirectionalLight(this.Parameters["DirLight2Direction"], this.Parameters["DirLight2DiffuseColor"], this.Parameters["DirLight2SpecularColor"], cloneSource != null ? cloneSource.light2 : (DirectionalLight)null);
 }
Пример #7
0
        /// <summary>
        /// Creates a new SkinnedEffect by cloning parameter settings from an existing instance.
        /// </summary>
        protected SkinnedEffect(SkinnedEffect cloneSource)
            : base(cloneSource)
        {
            CacheEffectParameters(cloneSource);

            preferPerPixelLighting = cloneSource.preferPerPixelLighting;
            fogEnabled             = cloneSource.fogEnabled;

            world      = cloneSource.world;
            view       = cloneSource.view;
            projection = cloneSource.projection;

            diffuseColor      = cloneSource.diffuseColor;
            emissiveColor     = cloneSource.emissiveColor;
            ambientLightColor = cloneSource.ambientLightColor;

            alpha = cloneSource.alpha;

            fogStart = cloneSource.fogStart;
            fogEnd   = cloneSource.fogEnd;

            weightsPerVertex = cloneSource.weightsPerVertex;
        }
Пример #8
0
        /// <summary>
        /// Creates a new SkinnedEffect by cloning parameter settings from an existing instance.
        /// </summary>
        protected CustomSkinnedEffect(SkinnedEffect cloneSource)
            : base(cloneSource)
        {
            CacheEffectParameters(cloneSource);

            preferPerPixelLighting = cloneSource.PreferPerPixelLighting;
            fogEnabled = cloneSource.FogEnabled;

            world = cloneSource.World;
            view = cloneSource.View;
            projection = cloneSource.Projection;

            diffuseColor = cloneSource.DiffuseColor;
            emissiveColor = cloneSource.EmissiveColor;
            ambientLightColor = cloneSource.AmbientLightColor;

            alpha = cloneSource.Alpha;

            fogStart = cloneSource.FogStart;
            fogEnd = cloneSource.FogEnd;

            weightsPerVertex = cloneSource.WeightsPerVertex;
        }
Пример #9
0
        public void Draw(Matrix[] transformMatrices, int totalInstances, SkinnedEffect skinnedEffect, Matrix view, Matrix proj, Texture2D skin)
        {
            skinnedEffect.EnableDefaultLighting();
            skinnedEffect.Texture = skin;
            skinnedEffect.View = view;
            skinnedEffect.Projection = proj;

            graphicsDevice.SetVertexBuffer(instancedVertexBuffer);
            graphicsDevice.Indices = instancedIndexBuffer;

            for (int i = 0; i < totalInstances; i += maxInstances)
            {
                // How many instances can we fit into this batch?
                int instanceCount = totalInstances - i;

                if (instanceCount > maxInstances)
                    instanceCount = maxInstances;

                // Upload transform matrices as shader constants.
                for (int copyIndex = 0; copyIndex < instanceCount; copyIndex++)
                    Utilities.CopyMatrix(ref transformMatrices[i + copyIndex], ref tempMatrices[copyIndex]);

                skinnedEffect.SetBoneTransforms(tempMatrices);

                foreach (EffectPass pass in skinnedEffect.CurrentTechnique.Passes)
                {
                    pass.Apply();
                    graphicsDevice.DrawIndexedPrimitives(
                        PrimitiveType.TriangleList,
                        0,
                        0,
                        instanceCount * originalVertexCount,
                        0,
                        instanceCount * originalIndexCount / 3);
                }
            }
        }
Пример #10
0
		/// <summary>
		/// Creates a new render window.
		/// </summary>
		/// <remarks>
		/// This method creates a new rendering window as specified
		/// by the paramteters. The rendering system could be
		/// responible for only a single window (e.g. in the case
		/// of a game), or could be in charge of multiple ones (in the
		/// case of a level editor). The option to create the window
		/// as a child of another is therefore given.
		/// This method will create an appropriate subclass of
		/// RenderWindow depending on the API and platform implementation.
		/// </remarks>
		/// <param name="name"></param>
		/// <param name="width"></param>
		/// <param name="height"></param>
		/// <param name="isFullScreen"></param>
		/// <param name="miscParams">
		/// A collection of addition rendersystem specific options.
		/// </param>
		public override RenderWindow CreateRenderWindow(string name, int width, int height, bool isFullScreen, NamedParameterList miscParams)
		{
			// Check we're not creating a secondary window when the primary
			// was fullscreen
			if (_primaryWindow != null && _primaryWindow.IsFullScreen)
				throw new Exception("Cannot create secondary windows when the primary is full screen.");

			if (_primaryWindow != null && isFullScreen)
				throw new ArgumentException("Cannot create full screen secondary windows.");

			// Log a message
			var strParams = new StringBuilder();
			if (miscParams != null)
			{
				foreach (var entry in miscParams)
				{
					strParams.AppendFormat("{0} = {1}; ", entry.Key, entry.Value);
				}
			}
			LogManager.Instance.Write("[XNA] : Creating RenderWindow \"{0}\", {1}x{2} {3} miscParams: {4}",
									   name, width, height, isFullScreen ? "fullscreen" : "windowed",
									   strParams.ToString());

			// Make sure we don't already have a render target of the 
			// same name as the one supplied
			if (renderTargets.ContainsKey(name))
			{
				throw new Exception(String.Format("A render target of the same name '{0}' already exists." +
													"You cannot create a new window with this name.", name));
			}

			RenderWindow window = new XnaRenderWindow(_activeDriver, _primaryWindow != null ? _device : null);

			// create the window
			window.Create(name, width, height, isFullScreen, miscParams);

			// add the new render target
			AttachRenderTarget(window);
			// If this is the first window, get the D3D device and create the texture manager
			if (_primaryWindow == null)
			{
				_primaryWindow = (XnaRenderWindow)window;
				_device = (GraphicsDevice)window["XNADEVICE"];

				basicEffect = new BasicEffect(_device);
				skinnedEffect = new SkinnedEffect(_device);
				// Create the texture manager for use by others
				textureManager = new XnaTextureManager(_device);
				// Also create hardware buffer manager
				_hardwareBufferManager = new XnaHardwareBufferManager( _device );

				// Create the GPU program manager
				gpuProgramMgr = new XnaGpuProgramManager(_device);
				// create & register HLSL factory
				//gpuProgramMgr.PushSyntaxCode("hlsl"));

				realCapabilities = new RenderSystemCapabilities();
				// use real capabilities if custom capabilities are not available
				if (!useCustomCapabilities)
				{
					currentCapabilities = realCapabilities;
				}

				FireEvent("RenderSystemCapabilitiesCreated");

				InitializeFromRenderSystemCapabilities(currentCapabilities, window);

				// Initialize the capabilities structures
				_checkHardwareCapabilities( _primaryWindow );
			}
			else
			{
				_secondaryWindows.Add((XnaRenderWindow)window);
			}

#if !SILVERLIGHT // Can only work on _device inside the Draw callback
			StateManager.ResetState( _device );
#endif
			return window;
		}
Пример #11
0
        public GenericEffect( Effect effectToAssimilate )
            :this()
        {
            /*
            DefaultShaderType type = DetermineEffect( false, effectToAssimilate );
            if( type == DefaultShaderType.Basic )
            {
                mBasicEffect = (BasicEffect)effectToAssimilate;
            }
            else if( type == DefaultShaderType.DualTexture )
            {
                mDualTextureEffect = (DualTextureEffect)effectToAssimilate;
            }
            else if( type == DefaultShaderType.EnvironmentMapped )
            {
                mEnvironmentMapEffect = (EnvironmentMapEffect)effectToAssimilate;
            }
            else if( type == DefaultShaderType.Skinned )
            {
                mSkinnedEffect = (SkinnedEffect)effectToAssimilate;
            }
            */
            if ( effectToAssimilate is BasicEffect )
            {
                mBasicEffect = effectToAssimilate as BasicEffect;
            }
            else if (effectToAssimilate is AlphaTestEffect)
            {
                mAlphaTestEffect = effectToAssimilate as AlphaTestEffect;
            }
#if !MONOGAME

            else if (effectToAssimilate is DualTextureEffect)
            {
                mDualTextureEffect = effectToAssimilate as DualTextureEffect;
            }
            else if (effectToAssimilate is EnvironmentMapEffect)
            {
                mEnvironmentMapEffect = effectToAssimilate as EnvironmentMapEffect;
            }
            else if (effectToAssimilate is SkinnedEffect)
            {
                mSkinnedEffect = effectToAssimilate as SkinnedEffect;
            }
#endif
        }
Пример #12
0
        protected override void LoadContent()
        {
            ResourceLibrary.Load(content, device);

            spritebatch = new SpriteBatch(device);

            skinnedeffect = new SkinnedEffect(device);
            skinnedeffect.EnableDefaultLighting();
            skinnedeffect.FogEnabled = false;
            skinnedeffect.PreferPerPixelLighting = true;

            dude = new ExampleModelClass(ResourceLibrary.dude, skinnedeffect);
            dude.SetWorld(Matrix.CreateScale(0.05f));
            dude.PlayAnimation(0, -1.0f, true);
        }
Пример #13
0
 protected SkinnedEffect(SkinnedEffect cloneSource)
   : base((Effect) cloneSource)
 {
   this.CacheEffectParameters(cloneSource);
   this.preferPerPixelLighting = cloneSource.preferPerPixelLighting;
   this.fogEnabled = cloneSource.fogEnabled;
   this.world = cloneSource.world;
   this.view = cloneSource.view;
   this.projection = cloneSource.projection;
   this.diffuseColor = cloneSource.diffuseColor;
   this.emissiveColor = cloneSource.emissiveColor;
   this.ambientLightColor = cloneSource.ambientLightColor;
   this.alpha = cloneSource.alpha;
   this.fogStart = cloneSource.fogStart;
   this.fogEnd = cloneSource.fogEnd;
   this.weightsPerVertex = cloneSource.weightsPerVertex;
 }
        protected override void LoadContent()
        {
            this.colorStream = new ColorStreamRenderer(Game, new Vector2(GraphicsDevice.Viewport.Width - 5 - 160, 5),
                new Vector2(160, 100));

            this.currentModel = Game.Content.Load<Model>("MODELS/ninja2/ninja/ninja2");
            if (null == this.currentModel)
            {
                throw new InvalidOperationException("Cannot load 3D avatar model");
            }

            effect = new SkinnedEffect(GraphicsDevice);

            effect.Texture = Game.Content.Load<Texture2D>("MODELS/ninja2/ninja/texture");

            foreach (ModelMesh mesh in currentModel.Meshes)
            {
                foreach (ModelMeshPart part in mesh.MeshParts)
                {
                    part.Effect = effect;
                }
            }

            this.animator.AvatarModel = this.currentModel;
            this.animator.AvatarHipCenterHeight = this.avatarHipCenterDrawHeight;

            this.BuildJointHierarchy();

            base.LoadContent();
        }
Пример #15
0
 /// <summary>
 /// Looks up shortcut references to our effect parameters.
 /// </summary>
 void CacheEffectParameters(SkinnedEffect cloneSource)
 {
     textureParam = Parameters["Texture"];
     diffuseColorParam = Parameters["DiffuseColor"];
     emissiveColorParam = Parameters["EmissiveColor"];
     specularColorParam = Parameters["SpecularColor"];
     specularPowerParam = Parameters["SpecularPower"];
     eyePositionParam = Parameters["EyePosition"];
     fogColorParam = Parameters["FogColor"];
     fogVectorParam = Parameters["FogVector"];
     worldParam = Parameters["World"];
     worldInverseTransposeParam = Parameters["WorldInverseTranspose"];
     worldViewProjParam = Parameters["WorldViewProj"];
     bonesParam = Parameters["Bones"];
     shaderIndexParam = Parameters["ShaderIndex"];
     lightPositionsParam = Parameters["lightPositions"];
     lightColorsParam = Parameters["lightColors"];
 }
Пример #16
0
        public void CopyFromSkinnedEffect(SkinnedEffect cloneSource)
        {
            CacheEffectParameters(cloneSource);

            preferPerPixelLighting = cloneSource.PreferPerPixelLighting;
            fogEnabled = cloneSource.FogEnabled;

            world = cloneSource.World;
            view = cloneSource.View;
            projection = cloneSource.Projection;

            diffuseColor = cloneSource.DiffuseColor;
            emissiveColor = cloneSource.EmissiveColor;
            ambientLightColor = cloneSource.AmbientLightColor;

            alpha = cloneSource.Alpha;

            fogStart = cloneSource.FogStart;
            fogEnd = cloneSource.FogEnd;

            weightsPerVertex = cloneSource.WeightsPerVertex;

            Texture = cloneSource.Texture;
            SpecularColor = cloneSource.SpecularColor;
            SpecularPower = cloneSource.SpecularPower;

            eyePositionParam.SetValue(cloneSource.Parameters["EyePosition"].GetValueVector3());
            fogVectorParam.SetValue(cloneSource.Parameters["FogVector"].GetValueVector4());
            worldInverseTransposeParam.SetValue(cloneSource.Parameters["WorldInverseTranspose"].GetValueMatrix());
            bonesParam.SetValue(cloneSource.Parameters["Bones"].GetValueMatrixArray(MaxBones));
        }
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here

            string[] textures = {
                                    "New Game",
                                    "Option",
                                    "Exit"
                                };
            Vector3[] positions = {
                                     new Vector3(0, -10, 0),
                                     new Vector3(0, -45, 0),
                                     new Vector3(0, -80, 0),
                                 };

            string texturePrefix = "MainMenu\\";
            Vector2[] sizes = {
                                  new Vector2(130, 60/2),
                                  new Vector2(130, 60/2),
                                  new Vector2(130, 60/2)
                              };

            _MainMenu = new MainMenu(Content, texturePrefix, textures, positions, sizes);

            string[] textures1 = {
                                    "Option",
                                    "SoundVolume",
                                    "Difficuty",
                                    "Back",
                                    "Ball"
                                };
            Vector3[] positions1 = {
                                     new Vector3(0, 60, 0),
                                     new Vector3(-40, 0, 0),
                                     new Vector3(-40, -40, 0),
                                     new Vector3(0, -80, 0),
                                     new Vector3(35, 0, 0),
                                 };

            string texturePrefix1 = "OptionMenu\\";
            Vector2[] sizes1 = {
                                  new Vector2(260/2, 52/2),
                                  new Vector2(220/2, 52/2),
                                  new Vector2(220/2, 52/2),
                                  new Vector2(260/2, 52/2),
                                  new Vector2(20, 30)
                              };
            this._OptionMenus = new OptionMenu(Content, texturePrefix1, textures1, positions1, sizes1);
            this._camera = new PerspectiveCamera(
                this.CAMERAPOSITION,
                this.CAMERATARGET,
                this.CAMERAUPVECTOR,
                this.NEARPLANEDISTANCE,
                this.FARPLANEDISTANCE,
                this.FIELDOFVIEW,
                this.ASPECTRATIO);

            this._SkinnedEffect = new SkinnedEffect(GraphicsDevice);
        }
        internal static SkinnedEffect Read(ContentReader input)
        {
            IGraphicsDeviceService graphicsDeviceService = (IGraphicsDeviceService)
                    input.ContentManager.ServiceProvider.GetService(typeof(IGraphicsDeviceService));

            GraphicsDevice graphicsDevice = graphicsDeviceService.GraphicsDevice;

            SkinnedEffect basicEffect = new SkinnedEffect(graphicsDevice);


            input.ReadVector3();
            input.ReadVector3();
            input.ReadVector3();
            input.ReadSingle();

            input.ReadBoolean();
            input.ReadBoolean();
            input.ReadBoolean();
            input.ReadObject<Texture2D>(); 
            input.ReadObject<Texture2D>(); 
            input.ReadObject<Texture2D>(); 

            return basicEffect;
        }
 /// <summary>
 /// Initializes this instance.
 /// </summary>
 /// <param name="ginfo"></param>
 /// <param name="factory"></param>
 /// <param name="obj"></param>
 public override void Initialize(GraphicInfo ginfo, GraphicFactory factory, IObject obj)
 {
     effect = factory.GetSkinnedEffect();
     base.Initialize(ginfo,factory,obj);            
 }
Пример #20
0
        public BatchRenderedAnimatedModel(GraphicsDevice graphics, Model model)
        {
            _graphicsDevice = graphics;
            _originalModel = model;
            _originalBoneCount = model.Bones.Count;

            _skinnedEffect = new SkinnedEffect(_graphicsDevice);
            _skinnedEffect.EnableDefaultLighting();
            _skinnedEffect.AmbientLightColor = Color.Gray.ToVector3();
            _skinnedEffect.SpecularColor = Color.Black.ToVector3();
            _skinnedEffect.PreferPerPixelLighting = false;

            SetupInstancedVertexData();
        }
Пример #21
0
 private void CacheEffectParameters(SkinnedEffect cloneSource)
 {
   this.textureParam = this.Parameters["Texture"];
   this.diffuseColorParam = this.Parameters["DiffuseColor"];
   this.emissiveColorParam = this.Parameters["EmissiveColor"];
   this.specularColorParam = this.Parameters["SpecularColor"];
   this.specularPowerParam = this.Parameters["SpecularPower"];
   this.eyePositionParam = this.Parameters["EyePosition"];
   this.fogColorParam = this.Parameters["FogColor"];
   this.fogVectorParam = this.Parameters["FogVector"];
   this.worldParam = this.Parameters["World"];
   this.worldInverseTransposeParam = this.Parameters["WorldInverseTranspose"];
   this.worldViewProjParam = this.Parameters["WorldViewProj"];
   this.bonesParam = this.Parameters["Bones"];
   this.light0 = new DirectionalLight(this.Parameters["DirLight0Direction"], this.Parameters["DirLight0DiffuseColor"], this.Parameters["DirLight0SpecularColor"], cloneSource != null ? cloneSource.light0 : (DirectionalLight) null);
   this.light1 = new DirectionalLight(this.Parameters["DirLight1Direction"], this.Parameters["DirLight1DiffuseColor"], this.Parameters["DirLight1SpecularColor"], cloneSource != null ? cloneSource.light1 : (DirectionalLight) null);
   this.light2 = new DirectionalLight(this.Parameters["DirLight2Direction"], this.Parameters["DirLight2DiffuseColor"], this.Parameters["DirLight2SpecularColor"], cloneSource != null ? cloneSource.light2 : (DirectionalLight) null);
 }
Пример #22
0
        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// </summary>
        public override void Initialize()
        {
            // register elements
            IObjectBuilder objectBuilder = Game.Services.GetService(typeof(IObjectBuilder)) as IObjectBuilder;
            if (objectBuilder != null)
            {
                registerElements(objectBuilder);
            }

            // performance
            PerformanceMonitor perfMon = Game.Services.GetService(typeof(PerformanceMonitor)) as PerformanceMonitor;
            if (perfMon != null)
            {
                m_mainTimer = perfMon.addPerformanceMeter(new XnaScrapId("CBeroRenderManager"));
                m_sceneTimer = m_mainTimer.addSubTimer("Scene");
                m_overlayTimer = m_mainTimer.addSubTimer("Overlays");
            }

            #if WINDOWS
            // register REST stuff
            NetCtrlService netCtrlService = Game.Services.GetService(typeof(NetCtrlService)) as NetCtrlService;
            if (netCtrlService != null)
            {
                netCtrlService.AddServiceNode(new RenderManagerNode(this), this);
            }
            #endif
            base.Initialize();
            m_spriteBatch = new SpriteBatch(GraphicsDevice);
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;

            #region materials
            BasicEffect basicEffect = new BasicEffect(GraphicsDevice);
            basicEffect.EnableDefaultLighting();
            basicEffect.PreferPerPixelLighting = true;
            m_basicEffectMaterial.Effect = basicEffect;
            m_basicEffectMaterial.Technique = basicEffect.Techniques.First().Name;
            Material.ParameterMapping worldviewprojection = new Material.ParameterMapping();
            worldviewprojection.name = "WorldViewProj";
            worldviewprojection.perInstance = true;
            worldviewprojection.semantic = Material.ShaderParameterSemantic.MODEL_VIEW_PROJECTION_MATRIX;
            m_basicEffectMaterial.ParameterMappings.Add(worldviewprojection);

            SkinnedEffect skinnedEffect = new SkinnedEffect(GraphicsDevice);
            skinnedEffect.EnableDefaultLighting();
            m_skinnedEffectMaterial.Effect = skinnedEffect;
            m_skinnedEffectMaterial.Technique = skinnedEffect.Techniques.First().Name;

            RenderState.PushMaterial(m_basicEffectMaterial);
            #endregion

            #region effects
            m_defaultEffect = new CBeroEffect(this);
            m_defaultCollection = new RenderTargetCollection(DefaultRenderTarget.GetInstance().Id, new IRenderTarget[] { DefaultRenderTarget.GetInstance() });
            m_defaultCollection.Effect = m_defaultEffect;
            m_defaultEffect.AddPass(new RenderSceneWithMaterialsPass(this, m_defaultCollection));
            m_defaultEffect.AddPass(new RenderOverlaysPass(this, m_defaultCollection));

            // add DefaultRenderTarget
            m_renderTargets.Add(DefaultRenderTarget.GetInstance().Id, m_defaultCollection);
            #endregion
        }
Пример #23
0
        /// <summary>
        /// Creates a new SkinnedEffect by cloning parameter settings from an existing instance.
        /// </summary>
        protected SkinnedEffect(SkinnedEffect cloneSource)
            : base(cloneSource)
        {
            CacheEffectParameters(cloneSource);

            preferPerPixelLighting = cloneSource.preferPerPixelLighting;
            fogEnabled = cloneSource.fogEnabled;

            world = cloneSource.world;
            view = cloneSource.view;
            projection = cloneSource.projection;

            diffuseColor = cloneSource.diffuseColor;
            emissiveColor = cloneSource.emissiveColor;
            ambientLightColor = cloneSource.ambientLightColor;

            alpha = cloneSource.alpha;

            fogStart = cloneSource.fogStart;
            fogEnd = cloneSource.fogEnd;
            
            weightsPerVertex = cloneSource.weightsPerVertex;
        }
Пример #24
0
        private DefaultShaderType DetermineEffect( bool createNewEffect, Effect effectToTest )
        {
            #region Determine precendence between effects
            float skinningPrecedence = mPrecedenceTable["SkinnedEffect"];
            float dualTexturePrecedence = mPrecedenceTable["DualTextureEffect"];
            float environmentMappingPrecedence = mPrecedenceTable["EnvironmentMapEffect"];
            float basicEffectPrecedence = mPrecedenceTable["BasicEffect"];
            #endregion

            #region Determining the possible types of Effect

            #region Check for key information for determining possible effect types
            Texture2D tex = Texture2;
            Matrix[] transforms = BoneTransforms;
#if !MONOGAME
            TextureCube cube = CubeMap;
#endif
            if (tex == null)
            {
                dualTexturePrecedence = float.MinValue;
            }

#if !MONOGAME
            if (cube == null)
            {
                environmentMappingPrecedence = float.MinValue;
            }
#endif

            if (transforms == null)
            {
                skinningPrecedence = float.MinValue;
            }
            #endregion
                

            // Three possible outcomes. If its a lower precedence than any
            // of it's competitors, it will lose out.
            // If it's greater than the others, it will win,
            // If it's equal to one another, well in technical terms, we guess.
            // ...
            // WELCOME TO IF STATEMENT HELL
#if !MONOGAME
            #region Skinning Shader determination... Don't look. Ever.
            //... I said don't look. Sigh
            if( skinningPrecedence >= environmentMappingPrecedence )
            {
                if( skinningPrecedence >= dualTexturePrecedence )
                {
                    if( skinningPrecedence > basicEffectPrecedence )
                    {
                        if( createNewEffect )
                        {
                            // Create a skinning shader
                            mSkinnedEffect = new SkinnedEffect( FlatRedBallServices.GraphicsDevice );
                            SetSkinningEffectParameters();
                        }

                        return DefaultShaderType.Skinned;
                    }
                }
            }
            #endregion

            #region Environment Mapping Determination
            if( environmentMappingPrecedence >= dualTexturePrecedence )
            {
                if( environmentMappingPrecedence >= basicEffectPrecedence )
                {
                    if( createNewEffect )
                    {
                        // Create Environment map
                        mEnvironmentMapEffect = new EnvironmentMapEffect(FlatRedBallServices.GraphicsDevice);
                        SetEnvironmentMapEffectParameters();
                    }
                    return DefaultShaderType.EnvironmentMapped;
                }
            }
            #endregion

            #region Dual Texture determination
            if( dualTexturePrecedence >= basicEffectPrecedence )
            {
                // Create Dual Texture
                if( createNewEffect )
                {
                    mDualTextureEffect = new DualTextureEffect( FlatRedBallServices.GraphicsDevice );
                    SetDualTextureEffectParameters();
                }
                return DefaultShaderType.DualTexture;
            }
            #endregion
#endif

            #region Basic Shader determination
             // Create a basic Shader
            if( createNewEffect )
            {
                mBasicEffect = new BasicEffect(FlatRedBallServices.GraphicsDevice);
                SetBasicEffectParameters();
            }

            return DefaultShaderType.Basic;

            #endregion
        #endregion
        }
Пример #25
0
        /// <summary>
        /// Looks up shortcut references to our effect parameters.
        /// </summary>
        void CacheEffectParameters(SkinnedEffect cloneSource)
        {
            textureParam                = Parameters["Texture"];
            diffuseColorParam           = Parameters["DiffuseColor"];
            emissiveColorParam          = Parameters["EmissiveColor"];
            specularColorParam          = Parameters["SpecularColor"];
            specularPowerParam          = Parameters["SpecularPower"];
            eyePositionParam            = Parameters["EyePosition"];
            fogColorParam               = Parameters["FogColor"];
            fogVectorParam              = Parameters["FogVector"];
            worldParam                  = Parameters["World"];
            worldInverseTransposeParam  = Parameters["WorldInverseTranspose"];
            worldViewProjParam          = Parameters["WorldViewProj"];
            bonesParam                  = Parameters["Bones"];
            shaderIndexParam            = Parameters["ShaderIndex"];

            light0 = new DirectionalLight(Parameters["DirLight0Direction"],
                                          Parameters["DirLight0DiffuseColor"],
                                          Parameters["DirLight0SpecularColor"],
                                          (cloneSource != null) ? cloneSource.light0 : null);

            light1 = new DirectionalLight(Parameters["DirLight1Direction"],
                                          Parameters["DirLight1DiffuseColor"],
                                          Parameters["DirLight1SpecularColor"],
                                          (cloneSource != null) ? cloneSource.light1 : null);

            light2 = new DirectionalLight(Parameters["DirLight2Direction"],
                                          Parameters["DirLight2DiffuseColor"],
                                          Parameters["DirLight2SpecularColor"],
                                          (cloneSource != null) ? cloneSource.light2 : null);
        }
Пример #26
0
		/// <summary>
		/// Binds a given GpuProgram (but not the parameters). 
		/// </summary>
		/// <remarks>
		/// Only one GpuProgram of each type can be bound at once, binding another
		/// one will simply replace the existing one.
		/// </remarks>
		public override void BindGpuProgram(GpuProgram program)
		{
			if (program == null)
				return;
			// TODO: Set shaders
			switch (program.Type)
			{
				case GpuProgramType.Vertex:
					if (program.IsSkeletalAnimationIncluded)
					{
						useSkinnedEffect = true;
						//LogManager.Instance.Write("Using Skinning Effect.");
						var fx1 = ((XnaVertexProgram)program).Effect as SkinnedEffect;
						if (fx1 == null)
							LogManager.Instance.Write(LogMessageLevel.Normal, false, "Can't get a SkinnedEffect from XnaVertexProgram");
						else
							skinnedEffect = fx1;
					}
					else                       
					{
						useSkinnedEffect = false;
						var fx2 = ((XnaVertexProgram)program).Effect as BasicEffect;
						if (fx2 == null)
							LogManager.Instance.Write(LogMessageLevel.Normal, false, "Can't get a BasicEffect from XnaVertexProgram");
						else
							basicEffect = fx2;
					}
#if SILVERLIGHT
					_device.SetPixelShader(((XnaVertexProgram)program).Effect.PixelShader());
#else
#endif
					break;
				case GpuProgramType.Fragment:
					var fx3 = ((XnaFragmentProgram)program).Effect as BasicEffect;
					if (fx3 == null)
						LogManager.Instance.Write(LogMessageLevel.Normal, false, "Can't get a BasicEffect from XnaFragmentProgram");
					else
						basicEffect = fx3;
#if SILVERLIGHT
					_device.SetVertexShader(((XnaFragmentProgram)program).Effect.VertexShader());
#else
#endif
					break;
				case GpuProgramType.Geometry:
					throw new AxiomException("Geometry shaders not supported with XNA");
			}

			/*
			switch ( program.Type )
			{
				case GpuProgramType.Vertex:
					_device.VertexShader = ( (XnaVertexProgram)program ).VertexShader;
					VertexShaderIsSet = true;
					break;

				case GpuProgramType.Fragment:
					_device.PixelShader = ( (XnaFragmentProgram)program ).PixelShader;
					PixelShaderIsSet = true;
					break;
			}
			 */
			base.BindGpuProgram(program);
		}
Пример #27
0
 private void ApplyPerInstanceSkinned(SkinnedRenderable3D r, SkinnedEffect effect)
 {
     if (r.GetSkinTransforms() != null)
     {
         Matrix[] bones = r.GetSkinTransforms();
         effect.SetBoneTransforms(bones);
     }
     effect.View = RenderState.m_currentView.Peek();
     effect.Projection = RenderState.m_currentProj.Peek();
 }
Пример #28
0
        public GenericEffect( DefaultShaderType type )
            :this()
        {
            if( type != DefaultShaderType.Determine )
            {
                if( type == DefaultShaderType.Basic )
                {
                    mBasicEffect = new BasicEffect( FlatRedBallServices.GraphicsDevice );
                }

                else if (type == DefaultShaderType.AlphaTest)
                {
                    mAlphaTestEffect = new AlphaTestEffect(FlatRedBallServices.GraphicsDevice);
                }

                else if (type == DefaultShaderType.DualTexture)
                {
#if MONOGAME
                    throw new NotImplementedException();
#else
                    mDualTextureEffect = new DualTextureEffect(FlatRedBallServices.GraphicsDevice);
#endif
                }

                else if (type == DefaultShaderType.EnvironmentMapped)
                {
#if MONOGAME
                    throw new NotImplementedException();
#else
                    mEnvironmentMapEffect = new EnvironmentMapEffect(FlatRedBallServices.GraphicsDevice);
#endif
                }

                else if (type == DefaultShaderType.Skinned)
                {
#if MONOGAME
                    throw new NotImplementedException();
#else
                    mSkinnedEffect = new SkinnedEffect(FlatRedBallServices.GraphicsDevice);
#endif
                }
            }
        }