Esempio n. 1
0
        public LightSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new StaticSkyObject(Services));
            GameObjectService.Objects.Add(new GroundObject(Services));

            // Disable the main lights (of the StaticSkyObject) and add some test lights instead.
            _graphicsScreen.Scene.GetSceneNode("Sunlight").IsEnabled = false;
            _graphicsScreen.Scene.GetSceneNode("Ambient").IsEnabled  = false;
            GameObjectService.Objects.Add(new TestLightsObject(Services));

            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            GameObjectService.Objects.Add(new LavaBallsObject(Services));
            GameObjectService.Objects.Add(new FogObject(Services));

            GameObjectService.Objects.Add(new OptionsObject(Services));
        }
Esempio n. 2
0
    public CascadedShadowSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;
      _graphicsScreen = new DeferredGraphicsScreen(Services)
      {
        // For debugging: Disable materials and only show light buffer.
        DebugMode = DeferredGraphicsDebugMode.VisualizeDiffuseLightBuffer
      };
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);

      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      GameObjectService.Objects.Add(new GrabObject(Services));

      ShadowSample.CreateScene(Services, ContentManager, _graphicsScreen);

      // Get the cascaded shadow of the sunlight (which was created by the DynamicSkyObject).
      _cascadedShadow = (CascadedShadow)((LightNode)_graphicsScreen.Scene.GetSceneNode("Sunlight")).Shadow;

      CreateGuiControls();
    }
Esempio n. 3
0
    public LightSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new StaticSkyObject(Services));
      GameObjectService.Objects.Add(new GroundObject(Services));

      // Disable the main lights (of the StaticSkyObject) and add some test lights instead.
      _graphicsScreen.Scene.GetSceneNode("Sunlight").IsEnabled = false;
      _graphicsScreen.Scene.GetSceneNode("Ambient").IsEnabled = false;
      GameObjectService.Objects.Add(new TestLightsObject(Services));

      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new LavaBallsObject(Services));
      GameObjectService.Objects.Add(new FogObject(Services));
    }
Esempio n. 4
0
        public MyGameComponent(Microsoft.Xna.Framework.Game game, IServiceLocator services)
            : base(game)
        {
            // Get the services that this component needs regularly.
            _services          = services;
            _inputService      = services.GetInstance <IInputService>();
            _simulation        = services.GetInstance <Simulation>();
            _graphicsService   = services.GetInstance <IGraphicsService>();
            _gameObjectService = services.GetInstance <IGameObjectService>();
            _uiService         = services.GetInstance <IUIService>();

            // Add gravity and damping to the physics simulation.
            _simulation.ForceEffects.Add(new Gravity());
            _simulation.ForceEffects.Add(new Damping());

            // Create the DeferredGraphicsScreen and some 3D objects.
            _deferredGraphicsScreen             = new DeferredGraphicsScreen(services);
            _deferredGraphicsScreen.DrawReticle = true;
            _graphicsService.Screens.Insert(0, _deferredGraphicsScreen);

            // The GameObjects below expect try to retrieve DebugRenderer and Scene via
            // service container.
            var serviceContainer = (ServiceContainer)services;

            serviceContainer.Register(typeof(DebugRenderer), null, _deferredGraphicsScreen.DebugRenderer);
            serviceContainer.Register(typeof(IScene), null, _deferredGraphicsScreen.Scene);

            _cameraGameObject = new CameraObject(services);
            _gameObjectService.Objects.Add(_cameraGameObject);
            _deferredGraphicsScreen.ActiveCameraNode = _cameraGameObject.CameraNode;
            _gameObjectService.Objects.Add(new GrabObject(services));
            _gameObjectService.Objects.Add(new StaticSkyObject(services));
            _gameObjectService.Objects.Add(new GroundObject(services));
            for (int i = 0; i < 10; i++)
            {
                _gameObjectService.Objects.Add(new DynamicObject(services, 1));
            }

            // Get the "SampleUI" screen that was created by the StartScreenComponent.
            _uiScreen = _uiService.Screens["SampleUI"];

            // Add a second GraphicsScreen. This time it is a DelegateGraphicsScreen that
            // draws the UI over DeferredGraphicsScreen.
            _delegateGraphicsScreen = new DelegateGraphicsScreen(_graphicsService)
            {
                RenderCallback = context => _uiScreen.Draw(context.DeltaTime)
            };
            _graphicsService.Screens.Insert(1, _delegateGraphicsScreen);

            // Create the game menu window. But do not display it yet.
            _gameMenuWindow = new GameMenuWindow
            {
                // If the menu is opened and closed a lot, it is more efficient when _gameMenuWindow.Close()
                // makes the window invisible but does not remove it from the screen.
                HideOnClose = true,
            };
        }
Esempio n. 5
0
    public TerrainSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);

      var scene = _graphicsScreen.Scene;
      Services.Register(typeof(IScene), null, scene);

      // Add gravity and damping to the physics simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services, 5000);
      cameraGameObject.ResetPose(new Vector3F(0, 2, 5), 0, 0);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      // Add standard game objects.
      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new LavaBallsObject(Services));
      GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true)
      {
        EnableCloudShadows = false,
        FogSampleAngle = 0.1f,
        FogSaturation = 1,
      });

      var fogObject = new FogObject(Services) { AttachToCamera = true };
      GameObjectService.Objects.Add(fogObject);

      // Set nice fog values.
      // (Note: If we change the fog values here, the GUI in the Options window is not
      // automatically updated.)
      fogObject.FogNode.IsEnabled = true;
      fogObject.FogNode.Fog.Start = 100;
      fogObject.FogNode.Fog.End = 2500;
      fogObject.FogNode.Fog.Start = 100;
      fogObject.FogNode.Fog.HeightFalloff = 0.25f;

      // Add an ocean at height 0.
      GameObjectService.Objects.Add(new OceanObject(Services));

      // Add the terrain.
      var terrainObject = new TerrainObject(Services);
      GameObjectService.Objects.Add(terrainObject);

      SampleFramework.ShowOptionsWindow();
    }
Esempio n. 6
0
        public SkySample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics Simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new GroundObject(Services));
            GameObjectService.Objects.Add(new DudeObject(Services));
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            GameObjectService.Objects.Add(new LavaBallsObject(Services));
            GameObjectService.Objects.Add(new FogObject(Services));
            GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Barrier", 0.9f, new Pose(new Vector3(0, 0, -2))));
            GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Cylinder", 0.9f, new Pose(new Vector3(3, 0, 0), Quaternion.CreateRotationY(MathHelper.ToRadians(-20)))));

            // The DynamicSkyObject creates the dynamic sky and lights.
            GameObjectService.Objects.Add(new DynamicSkyObject(Services));

            // Add a few palm trees.
            Random random = new Random(12345);

            for (int i = 0; i < 10; i++)
            {
                Vector3 position    = new Vector3(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
                Matrix  orientation = Matrix.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                float   scale       = random.NextFloat(0.5f, 1.2f);
                GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
            }

            // Add a grain filter to add some noise in the night.
            _graphicsScreen.PostProcessors.Add(new GrainFilter(GraphicsService)
            {
                IsAnimated         = true,
                LuminanceThreshold = 0.3f,
                ScaleWithLuminance = true,
                Strength           = 0.04f,
                GrainScale         = 1.5f,
            });
        }
Esempio n. 7
0
    public FogSphereSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      // Create a graphics screen. This screen has to call the FogSphereRenderer
      // to handle the FogSphereNode!
      _graphicsScreen = new DeferredGraphicsScreen(Services) { DrawReticle = true };
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics Simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      // More standard objects.
      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true));
      GameObjectService.Objects.Add(new GroundObject(Services));
      GameObjectService.Objects.Add(new DudeObject(Services));
      GameObjectService.Objects.Add(new DynamicObject(Services, 1));
      GameObjectService.Objects.Add(new DynamicObject(Services, 2));
      GameObjectService.Objects.Add(new DynamicObject(Services, 5));
      GameObjectService.Objects.Add(new DynamicObject(Services, 6));
      GameObjectService.Objects.Add(new DynamicObject(Services, 7));
      GameObjectService.Objects.Add(new FogObject(Services));
      GameObjectService.Objects.Add(new LavaBallsObject(Services));

      // Add a few palm trees.
      Random random = new Random(12345);
      for (int i = 0; i < 10; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.5f, 1.2f);
        GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
      }

      // ----- Add a FogSphereNode to scene.
      var fogSphereNode = new FogSphereNode
      {
        Name = "FogSphere",
        ScaleLocal = new Vector3F(5, 3, 5),
        PoseWorld = new Pose(new Vector3F(0, 0, -3)),
      };
      _graphicsScreen.Scene.Children.Add(fogSphereNode);
    }
Esempio n. 8
0
    public SkySample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics Simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new GroundObject(Services));
      GameObjectService.Objects.Add(new DudeObject(Services));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new LavaBallsObject(Services));
      GameObjectService.Objects.Add(new FogObject(Services));
      GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Barrier", 0.9f, new Pose(new Vector3F(0, 0, -2))));
      GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Cylinder", 0.9f, new Pose(new Vector3F(3, 0, 0), QuaternionF.CreateRotationY(MathHelper.ToRadians(-20)))));

      // The DynamicSkyObject creates the dynamic sky and lights.
      GameObjectService.Objects.Add(new DynamicSkyObject(Services));

      // Add a few palm trees.
      Random random = new Random(12345);
      for (int i = 0; i < 10; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.5f, 1.2f);
        GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
      }

      // Add a grain filter to add some noise in the night.
      _graphicsScreen.PostProcessors.Add(new GrainFilter(GraphicsService)
      {
        IsAnimated = true,
        LuminanceThreshold = 0.3f,
        ScaleWithLuminance = true,
        Strength = 0.04f,
        GrainScale = 1.5f,
      });
    }
Esempio n. 9
0
    public MyGameComponent(Microsoft.Xna.Framework.Game game, IServiceLocator services)
      : base(game)
    {
      // Get the services that this component needs regularly.
      _services = services;
      _inputService = services.GetInstance<IInputService>();
      _simulation = services.GetInstance<Simulation>();
      _graphicsService = services.GetInstance<IGraphicsService>();
      _gameObjectService = services.GetInstance<IGameObjectService>();
      _uiService = services.GetInstance<IUIService>();

      // Add gravity and damping to the physics simulation.
      _simulation.ForceEffects.Add(new Gravity());
      _simulation.ForceEffects.Add(new Damping());

      // Create the DeferredGraphicsScreen and some 3D objects.
      _deferredGraphicsScreen = new DeferredGraphicsScreen(services);
      _deferredGraphicsScreen.DrawReticle = true;
      _graphicsService.Screens.Insert(0, _deferredGraphicsScreen);

      // The GameObjects below expect try to retrieve DebugRenderer and Scene via
      // service container.
      var serviceContainer = (ServiceContainer)services;
      serviceContainer.Register(typeof(DebugRenderer), null, _deferredGraphicsScreen.DebugRenderer);
      serviceContainer.Register(typeof(IScene), null, _deferredGraphicsScreen.Scene);

      _cameraGameObject = new CameraObject(services);
      _gameObjectService.Objects.Add(_cameraGameObject);
      _deferredGraphicsScreen.ActiveCameraNode = _cameraGameObject.CameraNode;
      _gameObjectService.Objects.Add(new GrabObject(services));
      _gameObjectService.Objects.Add(new StaticSkyObject(services));
      _gameObjectService.Objects.Add(new GroundObject(services));
      for (int i = 0; i < 10; i++)
        _gameObjectService.Objects.Add(new DynamicObject(services, 1));

      // Get the "SampleUI" screen that was created by the StartScreenComponent.
      _uiScreen = _uiService.Screens["SampleUI"];

      // Add a second GraphicsScreen. This time it is a DelegateGraphicsScreen that
      // draws the UI over DeferredGraphicsScreen.
      _delegateGraphicsScreen = new DelegateGraphicsScreen(_graphicsService)
      {
        RenderCallback = context => _uiScreen.Draw(context.DeltaTime)
      };
      _graphicsService.Screens.Insert(1, _delegateGraphicsScreen);

      // Create the game menu window. But do not display it yet.
      _gameMenuWindow = new GameMenuWindow
      {
        // If the menu is opened and closed a lot, it is more efficient when _gameMenuWindow.Close()
        // makes the window invisible but does not remove it from the screen.
        HideOnClose = true,
      };
    }
Esempio n. 10
0
        public VarianceShadowSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;
            _graphicsScreen = new DeferredGraphicsScreen(Services)
            {
                // For debugging: Disable materials and only show light buffer.
                DebugMode = DeferredGraphicsDebugMode.VisualizeDiffuseLightBuffer
            };
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);

            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            GameObjectService.Objects.Add(new GrabObject(Services));

            // Create test scene.
            ShadowSample.CreateScene(Services, ContentManager, _graphicsScreen);

            // Get directional light created by the DynamicSkyObject and replace the default
            // shadow with our custom VSM shadow.
            _lightNode      = _graphicsScreen.Scene.GetDescendants().OfType <LightNode>().First(n => n.Shadow is CascadedShadow);
            _varianceShadow = new VarianceShadow
            {
                // If a target area is set, the VSM covers the given area.
                // If no target area is set, the VSM covers the area in front of the camera.
                TargetArea = new Aabb(new Vector3(-100, 0, -100), new Vector3(100, 50, 100)),
            };
            _lightNode.Shadow = _varianceShadow;

            // Apply a blur filter to the shadow map.
            _varianceShadow.Filter = new Blur(GraphicsService);
            _varianceShadow.Filter.InitializeGaussianBlur(11, 3, false);

            // Register our custom shadow map and shadow mask renderers.
            _graphicsScreen.ShadowMapRenderer.Renderers.Add(new VarianceShadowMapRenderer(_graphicsScreen.ShadowMapRenderer.RenderCallback));
            _graphicsScreen.ShadowMaskRenderer.Renderers.Add(new VarianceShadowMaskRenderer(GraphicsService));

            CreateGuiControls();
        }
Esempio n. 11
0
    public VarianceShadowSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;
      _graphicsScreen = new DeferredGraphicsScreen(Services)
      {
        // For debugging: Disable materials and only show light buffer.
        DebugMode = DeferredGraphicsDebugMode.VisualizeDiffuseLightBuffer
      };
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);

      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      GameObjectService.Objects.Add(new GrabObject(Services));

      // Create test scene.
      ShadowSample.CreateScene(Services, ContentManager, _graphicsScreen);

      // Get directional light created by the DynamicSkyObject and replace the default 
      // shadow with our custom VSM shadow.
      _lightNode = _graphicsScreen.Scene.GetDescendants().OfType<LightNode>().First(n => n.Shadow is CascadedShadow);
      _varianceShadow = new VarianceShadow
      {
        // If a target area is set, the VSM covers the given area.
        // If no target area is set, the VSM covers the area in front of the camera.
        TargetArea = new Aabb(new Vector3F(-100, 0, -100), new Vector3F(100, 50, 100)),
      };
      _lightNode.Shadow = _varianceShadow;

      // Apply a blur filter to the shadow map.
      _varianceShadow.Filter = new Blur(GraphicsService);
      _varianceShadow.Filter.InitializeGaussianBlur(11, 3, false);

      // Register our custom shadow map and shadow mask renderers.
      _graphicsScreen.ShadowMapRenderer.Renderers.Add(new VarianceShadowMapRenderer(_graphicsScreen.ShadowMapRenderer.RenderCallback));
      _graphicsScreen.ShadowMaskRenderer.Renderers.Add(new VarianceShadowMaskRenderer(GraphicsService));

      CreateGuiControls();
    }
Esempio n. 12
0
        public VolumetricCloudSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            GameObjectService.Objects.Add(new GrabObject(Services));
            _dynamicSkyObject = new DynamicSkyObject(Services, false, false, true);
            GameObjectService.Objects.Add(_dynamicSkyObject);
            GameObjectService.Objects.Add(new GroundObject(Services));
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            GameObjectService.Objects.Add(new LavaBallsObject(Services));

            _particleCloud0 = new ParticleSystemNode(CreateParticleCloud(ContentManager))
            {
                PoseLocal = new Pose(new Vector3(-0, 100, -400)),
            };
            ParticleSystemService.ParticleSystems.Add(_particleCloud0.ParticleSystem);
            _graphicsScreen.Scene.Children.Add(_particleCloud0);

            _particleCloud1 = new ParticleSystemNode(CreateParticleCloud(ContentManager))
            {
                PoseLocal = new Pose(new Vector3(-200, 100, -200)),
            };
            ParticleSystemService.ParticleSystems.Add(_particleCloud1.ParticleSystem);
            _graphicsScreen.Scene.Children.Add(_particleCloud1);

            _particleCloud2 = new ParticleSystemNode(CreateParticleCloud(ContentManager))
            {
                PoseLocal = new Pose(new Vector3(400, 400, -400)),
            };
            ParticleSystemService.ParticleSystems.Add(_particleCloud2.ParticleSystem);
            _graphicsScreen.Scene.Children.Add(_particleCloud2);
        }
Esempio n. 13
0
    public VolumetricCloudSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      GameObjectService.Objects.Add(new GrabObject(Services));
      _dynamicSkyObject = new DynamicSkyObject(Services, false, false, true);
      GameObjectService.Objects.Add(_dynamicSkyObject);
      GameObjectService.Objects.Add(new GroundObject(Services));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new LavaBallsObject(Services));

      _particleCloud0 = new ParticleSystemNode(CreateParticleCloud(ContentManager))
      {
        PoseLocal = new Pose(new Vector3F(-0, 100, -400)),
      };
      ParticleSystemService.ParticleSystems.Add(_particleCloud0.ParticleSystem);
      _graphicsScreen.Scene.Children.Add(_particleCloud0);

      _particleCloud1 = new ParticleSystemNode(CreateParticleCloud(ContentManager))
      {
        PoseLocal = new Pose(new Vector3F(-200, 100, -200)),
      };
      ParticleSystemService.ParticleSystems.Add(_particleCloud1.ParticleSystem);
      _graphicsScreen.Scene.Children.Add(_particleCloud1);

      _particleCloud2 = new ParticleSystemNode(CreateParticleCloud(ContentManager))
      {
        PoseLocal = new Pose(new Vector3F(400, 400, -400)),
      };
      ParticleSystemService.ParticleSystems.Add(_particleCloud2.ParticleSystem);
      _graphicsScreen.Scene.Children.Add(_particleCloud2);
    }
        public TechniqueBindingSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics Simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            // More standard objects.
            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            GameObjectService.Objects.Add(new StaticSkyObject(Services));
            GameObjectService.Objects.Add(new GroundObject(Services));

            // Tell the graphics service how to treat effect techniques which use
            // the "RepeatParameter" annotation.
            _repeatTechniqueInterpreter = new RepeatTechniqueInterpreter();
            GraphicsService.EffectInterpreters.Insert(0, _repeatTechniqueInterpreter);
            _repeatTechniqueBinder = new RepeatTechniqueBinder();
            GraphicsService.EffectBinders.Insert(0, _repeatTechniqueBinder);

            // Load model.
            _modelNode = ContentManager.Load <ModelNode>("Fur2/FurBall").Clone();
            _rigidBody = new RigidBody(new SphereShape(0.5f));

            // Set a random pose.
            _rigidBody.Pose      = new Pose(new Vector3F(0, 1, 0), RandomHelper.Random.NextQuaternionF());
            _modelNode.PoseWorld = _rigidBody.Pose;

            // Add rigid body to physics simulation and model to scene.
            Simulation.RigidBodies.Add(_rigidBody);
            _graphicsScreen.Scene.Children.Add(_modelNode);
        }
Esempio n. 15
0
    public TechniqueBindingSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics Simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      // More standard objects.
      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new StaticSkyObject(Services));
      GameObjectService.Objects.Add(new GroundObject(Services));

      // Tell the graphics service how to treat effect techniques which use
      // the "RepeatParameter" annotation.
      _repeatTechniqueInterpreter = new RepeatTechniqueInterpreter();
      GraphicsService.EffectInterpreters.Insert(0, _repeatTechniqueInterpreter);
      _repeatTechniqueBinder = new RepeatTechniqueBinder();
      GraphicsService.EffectBinders.Insert(0, _repeatTechniqueBinder);

      // Load model.
      _modelNode = ContentManager.Load<ModelNode>("Fur2/FurBall").Clone();
      _rigidBody = new RigidBody(new SphereShape(0.5f));

      // Set a random pose.
      _rigidBody.Pose = new Pose(new Vector3F(0, 1, 0), RandomHelper.Random.NextQuaternionF());
      _modelNode.PoseWorld = _rigidBody.Pose;

      // Add rigid body to physics simulation and model to scene.
      Simulation.RigidBodies.Add(_rigidBody);
      _graphicsScreen.Scene.Children.Add(_modelNode);
    }
Esempio n. 16
0
        public BatchingSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);

            var scene = _graphicsScreen.Scene;

            Services.Register(typeof(IScene), null, scene);

            // Add gravity and damping to the physics simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            // Add standard game objects.
            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true));
            GameObjectService.Objects.Add(new GroundObject(Services));
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            GameObjectService.Objects.Add(new LavaBallsObject(Services));

            // Create the scene data for the different batching strategies.
            CreateScene();

            // Choose the initially selected batching strategy.
            SetBatchingType(BatchingType.StaticBatching);

            CreateGuiControls();
        }
Esempio n. 17
0
        public DecalSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new StaticSkyObject(Services));
            GameObjectService.Objects.Add(new GroundObject(Services));
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            GameObjectService.Objects.Add(new LavaBallsObject(Services));
            GameObjectService.Objects.Add(new FogObject(Services));

            // Add some static objects.
            GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Barrier", 1, Pose.Identity));
            GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Cylinder", 1, new Pose(new Vector3F(3, 0, 1), QuaternionF.CreateRotationY(MathHelper.ToRadians(-20)))));

            // Add a dynamic object.
            GameObjectService.Objects.Add(new DynamicObject(Services, 1));

            // Add some predefined decals.
            GameObjectService.Objects.Add(new EnvironmentDecalsObject(Services));
        }
Esempio n. 18
0
        public TerrainHoleSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);

            var scene = _graphicsScreen.Scene;

            Services.Register(typeof(IScene), null, scene);

            // Add standard game objects.
            var cameraGameObject = new CameraObject(Services, 5000);

            cameraGameObject.ResetPose(new Vector3(0, 2, 0), 0, 0);
            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());
            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true)
            {
                EnableCloudShadows = false,
            });
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));

            // Create terrain.
            _terrainObject = new TerrainObject(Services);
            GameObjectService.Objects.Add(_terrainObject);

            UpdateHoleTexture();

            CreateGuiControls();
        }
Esempio n. 19
0
    public DecalSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new StaticSkyObject(Services));
      GameObjectService.Objects.Add(new GroundObject(Services));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new LavaBallsObject(Services));
      GameObjectService.Objects.Add(new FogObject(Services));

      // Add some static objects.
      GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Barrier", 1, Pose.Identity));
      GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Cylinder", 1, new Pose(new Vector3F(3, 0, 1), QuaternionF.CreateRotationY(MathHelper.ToRadians(-20)))));

      // Add a dynamic object.
      GameObjectService.Objects.Add(new DynamicObject(Services, 1));

      // Add some predefined decals.
      GameObjectService.Objects.Add(new EnvironmentDecalsObject(Services));
    }
Esempio n. 20
0
    public TerrainHoleSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);

      var scene = _graphicsScreen.Scene;
      Services.Register(typeof(IScene), null, scene);

      // Add standard game objects.
      var cameraGameObject = new CameraObject(Services, 5000);
      cameraGameObject.ResetPose(new Vector3F(0, 2, 0), 0, 0);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());
      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true)
      {
        EnableCloudShadows = false,
      });
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));

      // Create terrain.
      _terrainObject = new TerrainObject(Services);
      GameObjectService.Objects.Add(_terrainObject);

      UpdateHoleTexture();

      CreateGuiControls();
    }
Esempio n. 21
0
        public CascadedShadowSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;
            _graphicsScreen = new DeferredGraphicsScreen(Services)
            {
                // For debugging: Disable materials and only show light buffer.
                DebugMode = DeferredGraphicsDebugMode.VisualizeDiffuseLightBuffer
            };
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);

            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            GameObjectService.Objects.Add(new GrabObject(Services));

            ShadowSample.CreateScene(Services, ContentManager, _graphicsScreen);

            // Get the cascaded shadow of the sunlight (which was created by the DynamicSkyObject).
            _cascadedShadow = (CascadedShadow)((LightNode)_graphicsScreen.Scene.GetSceneNode("Sunlight")).Shadow;

            CreateGuiControls();
        }
Esempio n. 22
0
    public TerrainDecalSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);

      var scene = _graphicsScreen.Scene;
      Services.Register(typeof(IScene), null, scene);

      // Add gravity and damping to the physics simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraObject = new CameraObject(Services, 5000);
      cameraObject.ResetPose(new Vector3F(0, 2, 5), 0, 0);
      GameObjectService.Objects.Add(cameraObject);
      _graphicsScreen.ActiveCameraNode = cameraObject.CameraNode;

      // Add standard game objects.
      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new LavaBallsObject(Services));
      GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true)
      {
        EnableCloudShadows = false,
      });
      GameObjectService.Objects.Add(new FogObject(Services));

      // Create terrain.
      _terrainObject = new TerrainObject(Services);
      GameObjectService.Objects.Add(_terrainObject);

      // Add a blood decal to the terrain.
      var decal0 = new TerrainDecalLayer(GraphicsService)
      {
        Pose = GetRandomPose(),
        Width = 2,
        Height = 2,
        DiffuseColor = new Vector3F(0.08f),
        SpecularColor = new Vector3F(0.2f),
        SpecularPower = 100,
        DiffuseTexture = ContentManager.Load<Texture2D>("Decals/Decal_diffuse_mask"), // Original: "Decals/Blood_diffuse_mask",
        NormalTexture =  GraphicsService.GetDefaultNormalTexture(),   // Original: ContentManager.Load<Texture2D>("Decals/Blood_normal"),
        SpecularTexture = GraphicsService.GetDefaultTexture2DWhite(), // Original: ContentManager.Load<Texture2D>("Decals/Blood_specular"),
        FadeOutStart = 3,
        FadeOutEnd = 5,
        Alpha = 0.9f,
      };
      AddDecal(decal0);

      // Add a black blood decal (oil spill?)
      var decal1 = new TerrainDecalLayer(GraphicsService)
      {
        Pose = GetRandomPose(),
        Width = 2,
        Height = 2,
        DiffuseColor = new Vector3F(0.0f),
        SpecularColor = new Vector3F(0.5f),
        SpecularPower = 100,
        DiffuseTexture = ContentManager.Load<Texture2D>("Decals/Decal_diffuse_mask"), // Original: "Decals/Blood_diffuse_mask",
        NormalTexture = GraphicsService.GetDefaultNormalTexture(),   // Original: ContentManager.Load<Texture2D>("Decals/Blood_normal"),
        SpecularTexture = GraphicsService.GetDefaultTexture2DWhite(), // Original: ContentManager.Load<Texture2D>("Decals/Blood_specular"),
        FadeOutStart = 3,
        FadeOutEnd = 5,
      };
      AddDecal(decal1);

      // Add more random decals. The decals can share materials!
      var decal0Material = decal0.Material;
      for (int i = 0; i < 50; i++)
      {
        var decal = new TerrainDecalLayer(decal0Material)
        {
          Pose = GetRandomPose(),
          Width = 2,
          Height = 2,
        };
        AddDecal(decal);
      }
    }
Esempio n. 23
0
    public PlanarReflectionSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      // Create a graphics screen. This screen has to call the PlanarReflectionRenderer
      // to handle the PlanarReflectionNodes!
      _graphicsScreen = new DeferredGraphicsScreen(Services) { DrawReticle = true };
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics Simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      // More standard objects.
      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new StaticSkyObject(Services));
      GameObjectService.Objects.Add(new GroundObject(Services));
      GameObjectService.Objects.Add(new DudeObject(Services));
      GameObjectService.Objects.Add(new DynamicObject(Services, 1));
      GameObjectService.Objects.Add(new DynamicObject(Services, 2));
      GameObjectService.Objects.Add(new DynamicObject(Services, 5));
      GameObjectService.Objects.Add(new DynamicObject(Services, 6));
      GameObjectService.Objects.Add(new DynamicObject(Services, 7));
      GameObjectService.Objects.Add(new FogObject(Services));
      GameObjectService.Objects.Add(new LavaBallsObject(Services));

      // Add a few palm trees.
      Random random = new Random(12345);
      for (int i = 0; i < 10; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.5f, 1.2f);
        GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
      }

#if MONOGAME
      // ----- Workaround for missing effect parameter semantics in MonoGame.
      // The effect used by the reflecting ground object defines some new effect
      // parameters and sets the EffectParameterHint to "PerInstance", e.g.:
      //   texture ReflectionTexture < string Hint = "PerInstance"; >;
      // "PerInstance" means that each mesh instance which uses the effect can 
      // have an individual parameter value, i.e. if there are two instances
      // each instance needs a different ReflectionTexture.
      // MonoGame does not yet support effect parameter annotations in shader 
      // code. But we can add the necessary effect parameter descriptions here:
      var effectInterpreter = GraphicsService.EffectInterpreters.OfType<DefaultEffectInterpreter>().First();
      if (!effectInterpreter.ParameterDescriptions.ContainsKey("ReflectionTexture"))
      {
        effectInterpreter.ParameterDescriptions.Add("ReflectionTexture", (parameter, index) => new EffectParameterDescription(parameter, "ReflectionTexture", index, EffectParameterHint.PerInstance));
        effectInterpreter.ParameterDescriptions.Add("ReflectionTextureSize", (parameter, index) => new EffectParameterDescription(parameter, "ReflectionTextureSize", index, EffectParameterHint.PerInstance));
        effectInterpreter.ParameterDescriptions.Add("ReflectionMatrix", (parameter, index) => new EffectParameterDescription(parameter, "ReflectionMatrix", index, EffectParameterHint.PerInstance));
        effectInterpreter.ParameterDescriptions.Add("ReflectionNormal", (parameter, index) => new EffectParameterDescription(parameter, "ReflectionNormal", index, EffectParameterHint.PerInstance));
      }
#endif

      // Get a ground model which can render a planar reflection. See 
      // GroundReflective/MaterialReflective.fx.
      var groundModel = ContentManager.Load<ModelNode>("GroundReflective/Ground");

      // Use the reflective mesh as the ground.
      var groundMesh = groundModel.GetSubtree().OfType<MeshNode>().First().Clone();
      groundMesh.PoseWorld = new Pose(new Vector3F(0, 0.01f, 0));  // Small y offset to draw above the default ground model from GroundObject.
      _graphicsScreen.Scene.Children.Add(groundMesh);

      // Use another instance of the mesh as a wall.
      var wallMesh = groundMesh.Clone();
      wallMesh.ScaleLocal = new Vector3F(0.2f, 1, 0.1f);
      wallMesh.PoseWorld = new Pose(new Vector3F(5, 2, -5), Matrix33F.CreateRotationY(-0.7f) * Matrix33F.CreateRotationX(ConstantsF.PiOver2));
      _graphicsScreen.Scene.Children.Add(wallMesh);

      // Create a PlanarReflectionNode and add it to the children of the first ground mesh.
      // The RenderToTexture class defines the render target for the reflection.
      var renderToTexture0 = new RenderToTexture
      {
        Texture = new RenderTarget2D(
          GraphicsService.GraphicsDevice, 
          1024, 1024, 
          false,  // No mipmaps. Mipmaps can reduce reflection quality.
          SurfaceFormat.HdrBlendable, DepthFormat.Depth24Stencil8),
      };
      _planarReflectionNode0 = new PlanarReflectionNode(renderToTexture0)
      {
        // The reflection is limited to the bounding shape of the ground mesh.
        Shape = groundMesh.Shape,

        // The normal of the reflection plane.
        NormalLocal = new Vector3F(0, 1, 0),
      };
      groundMesh.Children = new SceneNodeCollection(1) { _planarReflectionNode0 };

      // Add another PlanarReflectionNode to the wall.
      var renderToTexture1 = new RenderToTexture
      {
        Texture = new RenderTarget2D(
          GraphicsService.GraphicsDevice,
          1024, 1024, false, 
          SurfaceFormat.HdrBlendable, DepthFormat.Depth24Stencil8),
      };
      _planarReflectionNode1 = new PlanarReflectionNode(renderToTexture1)
      {
        Shape = groundMesh.Shape,
        NormalLocal = new Vector3F(0, 1, 0),
      };
      wallMesh.Children = new SceneNodeCollection(1) { _planarReflectionNode1 };
      
      // Now we have to use the texture that contains the reflection.
      // We use effect parameter bindings to use the reflection texture in the shader of the meshes.
      SetReflectionEffectParameters(groundMesh, _planarReflectionNode0);
      SetReflectionEffectParameters(wallMesh, _planarReflectionNode1);
    }
Esempio n. 24
0
    public ParallaxMappingSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics Simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new DynamicSkyObject(Services, false, false, true));
      GameObjectService.Objects.Add(new DynamicObject(Services, 1));
      GameObjectService.Objects.Add(new DynamicObject(Services, 1));
      GameObjectService.Objects.Add(new DynamicObject(Services, 1));
      GameObjectService.Objects.Add(new DynamicObject(Services, 2));
      GameObjectService.Objects.Add(new DynamicObject(Services, 2));
      GameObjectService.Objects.Add(new DynamicObject(Services, 2));

      // Add a few palm trees.
      Random random = new Random(12345);
      for (int i = 0; i < 10; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.5f, 1.2f);
        GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
      }

      // Load ground model which uses normal mapping.
      var modelNode = ContentManager.Load<ModelNode>("Parallax/Ground");
      _meshNode = modelNode.Children.OfType<MeshNode>().First().Clone();
      _meshNode.ScaleLocal = new Vector3F(0.1f);
      _meshNode.IsStatic = true;

      Debug.Assert(_meshNode.Mesh.Materials.Count == 1, "Mesh should have only one material.");

      // Load materials with normal mapping, parallax mapping and parallax occlusion mapping.
      _normalMaterial = ContentManager.Load<Material>("Parallax/Normal").Clone();
      _parallaxMappingMaterial = ContentManager.Load<Material>("Parallax/PM").Clone();
      _parallaxOcclusionMappingMaterial = ContentManager.Load<Material>("Parallax/POM").Clone();

      // Get default values from materials.
      var parameterBindings = _parallaxOcclusionMappingMaterial["Material"].ParameterBindings;
      _heightScale = ((ConstParameterBinding<float>)parameterBindings["HeightScale"]).Value;
      _heightBias = ((ConstParameterBinding<float>)parameterBindings["HeightBias"]).Value;
      _lodThreshold = ((ConstParameterBinding<int>)parameterBindings["LodThreshold"]).Value;
      _maxSamples = ((ConstParameterBinding<int>)parameterBindings["MaxSamples"]).Value;
      _shadowStrength = ((ConstParameterBinding<float>)parameterBindings["ShadowStrength"]).Value;

      // Start test with POM material.
      _currentMaterialIndex = 2;
      UpdateMesh();

      // Add nodes to scene graph.
      _graphicsScreen.Scene.Children.Add(_meshNode);

      // Create rigid body for ground plane.
      Simulation.RigidBodies.Add(new RigidBody(new PlaneShape(Vector3F.UnitY, 0))
      {
        MotionType = MotionType.Static,
      });
    }
Esempio n. 25
0
        public SceneCapture2DSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            // Create a graphics screen. This screen has to call the SceneCaptureRenderer
            // to handle the SceneCaptureNodes!
            _graphicsScreen = new DeferredGraphicsScreen(Services)
            {
                DrawReticle = true
            };
            GraphicsService.Screens.Insert(0, _graphicsScreen);

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // We are going to modify the material of the TV mesh. These changes should not
            // affect other samples. Therefore, we add a new content manager, which is only
            // used in this sample.
            _contentManager = new ContentManager(Services, ContentManager.RootDirectory);
            Services.Register(typeof(ContentManager), null, _contentManager);

            // Add gravity and damping to the physics Simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            // More standard objects.
            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            GameObjectService.Objects.Add(new StaticSkyObject(Services));
            GameObjectService.Objects.Add(new GroundObject(Services));
            GameObjectService.Objects.Add(new DudeObject(Services));
            GameObjectService.Objects.Add(new DynamicObject(Services, 1));
            GameObjectService.Objects.Add(new DynamicObject(Services, 2));
            GameObjectService.Objects.Add(new DynamicObject(Services, 4));
            GameObjectService.Objects.Add(new DynamicObject(Services, 5));
            GameObjectService.Objects.Add(new DynamicObject(Services, 6));
            GameObjectService.Objects.Add(new DynamicObject(Services, 7));
            GameObjectService.Objects.Add(new FogObject(Services));
            GameObjectService.Objects.Add(new LavaBallsObject(Services));

            // Add a few palm trees.
            Random random = new Random(12345);

            for (int i = 0; i < 10; i++)
            {
                Vector3F  position    = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
                Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                float     scale       = random.NextFloat(0.5f, 1.2f);
                GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
            }

            // Add an options window.
            GameObjectService.Objects.Add(new OptionsObject(Services));

            // Create another camera which defines the view that should be captured.
            _sceneCaptureCameraNode = cameraGameObject.CameraNode.Clone();

            // Define the target for the render-to-texture operations.
            _renderToTexture = new RenderToTexture
            {
                Texture = new RenderTarget2D(
                    GraphicsService.GraphicsDevice,
                    1280 / 2, 720 / 2,
#if !MONOGAME && !XBOX
                    true,
#else
                    false, // MonoGame has not yet implemented render target mipmap support.
#endif
                    SurfaceFormat.Color,
                    DepthFormat.Depth24Stencil8)
            };

            // Add a few TV objects.
            for (int i = 0; i < 10; i++)
            {
                GameObjectService.Objects.Add(new DynamicObject(Services, 3));
            }

            // Attach a SceneCaptureNode to each TV mesh. The SceneCaptureNodes share the
            // same RenderToTexture instance, which means that all TVs show the same image.
            // The SceneCaptureNode has the same bounding shape as the TV mesh. This shape
            // is used for culling: The texture is only updated when at least one TV is
            // within the player's view.
            foreach (var meshNode in _graphicsScreen.Scene.GetDescendants().OfType <MeshNode>().Where(n => n.Name == "TV"))
            {
                if (meshNode.Children == null)
                {
                    meshNode.Children = new SceneNodeCollection();
                }

                meshNode.Children.Add(new SceneCaptureNode(_renderToTexture)
                {
                    CameraNode = _sceneCaptureCameraNode,

                    // For culling: Assign TV shape to SceneCaptureNode.
                    Shape = meshNode.Shape,
                });
            }

            // Get the material of the TV mesh.
            var tvModel = _graphicsScreen.Scene
                          .GetDescendants()
                          .OfType <ModelNode>()
                          .First(n => n.Name == "TVBox");
            var tvMesh           = (MeshNode)tvModel.Children[0];
            var tvScreenMaterial = tvMesh.Mesh
                                   .Materials
                                   .First(m => m.Name == "TestCard");

            // Use the texture on the TV screen.
            tvScreenMaterial["Material"].Set("EmissiveTexture", _renderToTexture.Texture);
            tvScreenMaterial["Material"].Set("Exposure", 0.5f);

            // Also assign the texture to the light projected by the TV screen.
            var lightNode      = (LightNode)tvModel.Children[1];
            var projectorLight = (ProjectorLight)lightNode.Light;
            projectorLight.Texture = (Texture2D)_renderToTexture.Texture;
        }
Esempio n. 26
0
    public OceanSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;
      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics Simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      // More standard objects.
      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      //GameObjectService.Objects.Add(new StaticSkyObject(Services));
      var dynamicSkyObject = new DynamicSkyObject(Services, true, false, true);
      GameObjectService.Objects.Add(dynamicSkyObject);

      // Add an island model.
      GameObjectService.Objects.Add(new StaticObject(Services, "Island/Island", new Vector3F(30), new Pose(new Vector3F(0, 0.75f, 0)), true, true));

      GameObjectService.Objects.Add(new DynamicObject(Services, 1));
      GameObjectService.Objects.Add(new DynamicObject(Services, 2));
      GameObjectService.Objects.Add(new DynamicObject(Services, 5));
      GameObjectService.Objects.Add(new DynamicObject(Services, 6));
      GameObjectService.Objects.Add(new DynamicObject(Services, 7));
      GameObjectService.Objects.Add(new FogObject(Services) { AttachToCamera = true });

      // The LavaBalls class controls all lava ball instances.
      var lavaBalls = new LavaBallsObject(Services);
      GameObjectService.Objects.Add(lavaBalls);

      // Add a few palm trees.
      Random random = new Random(12345);
      for (int i = 0; i < 20; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-7, 4), 0, random.NextFloat(13, 18));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.8f, 1.2f);
        GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
      }

      // Define the appearance of the water.
      var waterOcean = new Water
      {
        SpecularColor = new Vector3F(20f),
        SpecularPower = 500,

        NormalMap0 = null,
        NormalMap1 = null,

        RefractionDistortion = 0.1f,
        ReflectionColor = new Vector3F(0.2f),
        RefractionColor = new Vector3F(0.6f),

        // Water is scattered in high waves and this makes the wave crests brighter.
        // ScatterColor defines the intensity of this effect.
        ScatterColor = new Vector3F(0.05f, 0.1f, 0.1f),

        // Foam is automatically rendered where the water intersects geometry and
        // where wave are high.
        FoamMap = ContentManager.Load<Texture2D>("Water/Foam"),
        FoamMapScale = 5,
        FoamColor = new Vector3F(1),
        FoamCrestMin = 0.3f,
        FoamCrestMax = 0.8f,

        // Approximate underwater caustics are computed in real-time from the waves.
        CausticsSampleCount = 3,
        CausticsIntensity = 3,
        CausticsPower = 100,
      };

      // If we do not specify a shape in the WaterNode constructor, we get an infinite
      // water plane.
      _waterNode = new WaterNode(waterOcean, null)
      {
        PoseWorld = new Pose(new Vector3F(0, 0.5f, 0)),
        SkyboxReflection = _graphicsScreen.Scene.GetDescendants().OfType<SkyboxNode>().First(),

        // ExtraHeight must be set to a value greater than the max. wave height. 
        ExtraHeight = 2,
      };
      _graphicsScreen.Scene.Children.Add(_waterNode);

      // OceanWaves can be set to displace water surface using a displacement map.
      // The displacement map is computed by the WaterWaveRenderer (see DeferredGraphicsScreen)
      // using FFT and a statistical ocean model.
      _waterNode.Waves = new OceanWaves
      {
        TextureSize = 256,
        HeightScale = 0.004f,
        Wind = new Vector3F(10, 0, 10),
        Directionality = 1,
        Choppiness = 1,
        TileSize = 20,

        // If we enable CPU queries, we can call OceanWaves.GetDisplacement()
        // (see Update() method below).
        EnableCpuQueries = true,
      };

      // Optional: Use a planar reflection instead of the skybox reflection.
      // We add a PlanarReflectionNode as a child of the WaterNode.
      var renderToTexture = new RenderToTexture
      {
        Texture = new RenderTarget2D(GraphicsService.GraphicsDevice, 512, 512, false, SurfaceFormat.HdrBlendable, DepthFormat.None),
      };
      var planarReflectionNode = new PlanarReflectionNode(renderToTexture)
      {
        Shape = _waterNode.Shape,
        NormalLocal = new Vector3F(0, 1, 0),
        IsEnabled = false,
      };
      _waterNode.PlanarReflection = planarReflectionNode;
      _waterNode.Children = new SceneNodeCollection(1) { planarReflectionNode };

      // To let rigid bodies swim, we add a Buoyancy force effect. This force effect
      // computes buoyancy of a flat water surface.
      Simulation.ForceEffects.Add(new Buoyancy
      {
        Surface = new Plane(new Vector3F(0, 1, 0), _waterNode.PoseWorld.Position.Y),
        Density = 1500,
        AngularDrag = 0.3f,
        LinearDrag = 3,
      });
    }
Esempio n. 27
0
    public VegetationSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);

      var scene = _graphicsScreen.Scene;
      Services.Register(typeof(IScene), null, scene);

      // Add gravity and damping to the physics simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      // Add standard game objects.
      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true));
      GameObjectService.Objects.Add(new GroundObject(Services));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new LavaBallsObject(Services));

      // Add a new game object which controls the wind velocity and "Wind" parameters in effects.
      GameObjectService.Objects.Add(new WindObject(Services));

#if MONOGAME    // TODO: Test if MonoGame supports effect annotations.
      // The vegetation effects use an effect parameter named "LodDistances". By default all
      // effect parameters are shared per "Material". However, we want to change the parameter
      // per instance. Therefore, the effect declares the parameter like this:
      // float3 LodDistances < string Hint = "PerInstance"; >;
      // However, MonoGame does not yet support effect annotations. Therefore, we tell the
      // graphics service that the "LodDistances" parameter should be stored per instance by
      // adding a new entry to the default effect interpreter.
      var defaultEffectInterpreter = GraphicsService.EffectInterpreters.OfType<DefaultEffectInterpreter>().First();
      if (!defaultEffectInterpreter.ParameterDescriptions.ContainsKey("LodDistances"))
        defaultEffectInterpreter.ParameterDescriptions.Add(
          "LodDistances",
          (parameter, i) => new EffectParameterDescription(parameter, "LodDistances", i, EffectParameterHint.PerInstance));
#endif

      // Load three different plant models.
      // The palm tree consists of a single mesh. It uses the *Vegetation.fx effects.
      ModelNode palmModelNode = ContentManager.Load<ModelNode>("Vegetation/PalmTree/palm_tree");
      Mesh palmMesh = ((MeshNode)palmModelNode.Children[0]).Mesh;

      // The bird's nest plant consists of 2 LODs. It uses the *Vegetation.fx effects.
      ModelNode plantModelNode = ContentManager.Load<ModelNode>("Vegetation/BirdnestPlant/BirdnestPlant");
      LodGroupNode plantLodGroupNode = plantModelNode.GetDescendants().OfType<LodGroupNode>().First().Clone();

      // The grass model consists of one mesh. It uses the *Grass.fx effects.
      ModelNode grassModelNode = ContentManager.Load<ModelNode>("Vegetation/Grass/grass");
      Mesh grassMesh = ((MeshNode)grassModelNode.Children[0]).Mesh;

      // Store all used meshes in a list for use in UpdateMaterialEffectParameters.
      _meshes.Add(palmMesh);
      foreach (var meshNode in plantLodGroupNode.Levels.Select(lodEntry => lodEntry.Node).OfType<MeshNode>())
        _meshes.Add(meshNode.Mesh);
      _meshes.Add(grassMesh);

      // We can add individual plant instances to the scene like this:
      // (However, this is inefficient for large amounts of plants.)
      _graphicsScreen.Scene.Children.Add(new MeshNode(palmMesh)
      {
        PoseLocal = new Pose(new Vector3F(-2, 0, 0))
      });
      plantLodGroupNode.PoseLocal = Pose.Identity;
      _graphicsScreen.Scene.Children.Add(plantLodGroupNode);
      _graphicsScreen.Scene.Children.Add(new MeshNode(grassMesh)
      {
        PoseLocal = new Pose(new Vector3F(2, 0, 0))
      });

#if WINDOWS
      int numberOfInstancesPerCell = 100;
#else
      int numberOfInstancesPerCell = 10;
#endif

      // It is more efficient to group instances in batches and render them using mesh instancing.
      // This is handled by the VegetationObject class.
      GameObjectService.Objects.Add(new VegetationObject(Services, palmMesh, numberOfInstancesPerCell, 20, 10, 10, 1)
      {
        Name = "PalmTrees"
      });

      // The bird's nest plant has 2 LODs. We create two VegetationObjects. One displays the
      // detailed meshes near the camera. The second displays the low-poly meshes in the distance.
      var plantMeshLod0 = ((MeshNode)plantLodGroupNode.Levels[0].Node).Mesh;
      _meshes.Add(plantMeshLod0);
      GameObjectService.Objects.Add(new VegetationObject(Services, plantMeshLod0, numberOfInstancesPerCell, 20, 10, 10, 2)
      {
        Name = "PlantLOD0",
        MaxDistance = plantLodGroupNode.Levels[1].Distance,
      });

      var plantMeshLod1 = ((MeshNode)plantLodGroupNode.Levels[1].Node).Mesh;
      _meshes.Add(plantMeshLod1);
      GameObjectService.Objects.Add(new VegetationObject(Services, plantMeshLod1, numberOfInstancesPerCell, 20, 10, 10, 2)
      {
        Name = "PlantLOD1",
        MinDistance = plantLodGroupNode.Levels[1].Distance,
        MaxDistance = plantLodGroupNode.MaxDistance,
        CastsShadows = false,  // No shadows in the distance.
      });

      // Grass, lots of it...
      GameObjectService.Objects.Add(new VegetationObject(Services, grassMesh, numberOfInstancesPerCell * 10, 10, 20, 20, 3)
      {
        Name = "Grass",
        MaxDistance = 30,
        CastsShadows = false,
      });

      CreateGuiControls();
    }
Esempio n. 28
0
    public ImageBasedLightingSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      // Add standard game objects.
      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true));
      GameObjectService.Objects.Add(new GroundObject(Services));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new DudeObject(Services) { Pose = new Pose(new Vector3F(-4, 0, 4)) });
      GameObjectService.Objects.Add(new LavaBallsObject(Services));

      // Create 3 image-based lights.
      for (int i = 0; i < 3; i++)
      {
        _imageBasedLights[i] = new ImageBasedLight
        {
          DiffuseIntensity = 1f,
          SpecularIntensity = 1f,
          FalloffRange = 0.2f,
          BlendMode = 1,    // 0 = add to ambient light, 1 = replace ambient light
        };
      }

      // The first IBL is infinite.
      _imageBasedLights[0].Shape = Shape.Infinite;

      // The other 2 IBLs have a box shape and use specify an AABB which is 
      // aligned to the with scene objects (walls, barrels, palm tree line).
      _imageBasedLights[1].Shape = new BoxShape(7.5f, 10, 7);
      _imageBasedLights[1].EnableLocalizedReflection = true;
      _imageBasedLights[1].LocalizedReflectionBox = new Aabb(new Vector3F(-100, -2, -100), new Vector3F(3.5f, 2, 100));

      _imageBasedLights[2].Shape = new BoxShape(7.5f, 10, 7);
      _imageBasedLights[2].EnableLocalizedReflection = true;
      _imageBasedLights[2].LocalizedReflectionBox = new Aabb(new Vector3F(-3, -2, -100), new Vector3F(3.5f, 2, 100));

      // Add 3 light nodes to add the IBL to the scene.
      for (int i = 0; i < 3; i++)
      {
        _lightNodes[i] = new LightNode(_imageBasedLights[i]);
        _graphicsScreen.Scene.Children.Add(_lightNodes[i]);
      }

      _lightNodes[0].PoseLocal = _globalRotation * new Pose(new Vector3F(-5, 5, 5));
      _lightNodes[1].PoseLocal = _globalRotation * new Pose(new Vector3F(0, 2, 0));
      _lightNodes[2].PoseLocal = _globalRotation * new Pose(new Vector3F(0, 2, -4));

      // Increase specular power of ground to create sharper reflections.
      var groundModelNode = (ModelNode)_graphicsScreen.Scene.GetSceneNode("Ground");
      var groundMaterial = ((MeshNode)groundModelNode.Children[0]).Mesh.Materials[0];
      groundMaterial["GBuffer"].Set("SpecularPower", 1000000.0f);

      // Add more test objects to the scenes.
      AddLightProbes();
      AddTestSpheres();
      AddTestObjects();

      CreateGuiControls();
    }
Esempio n. 29
0
    protected override void OnLoad()
    {
      // Get common services and game objects.
      _graphicsService = _services.GetInstance<IGraphicsService>();
      _graphicsScreen = _graphicsService.Screens.OfType<DeferredGraphicsScreen>().First();
      var content = _services.GetInstance<ContentManager>();
      var scene = _services.GetInstance<IScene>();
      _simulation = _services.GetInstance<Simulation>();
      var gameObjectService = _services.GetInstance<IGameObjectService>();
      _cameraObject = gameObjectService.Objects.OfType<CameraObject>().First();
      _previousCameraFar = _cameraObject.CameraNode.Camera.Projection.Far;

      // Create a new terrain.
      var terrain = new Terrain();

      // The terrain is made up of terrain tiles which can be loaded independently. 
      // Each terrain tile consists of height and normal textures which define the terrain
      // geometry and terrain layers which define the material (detail textures).
      // In this sample we create 2x2 tiles.
      _tiles = new Tile[2, 2];
      for (int row = 0; row < 2; row++)
      {
        for (int column = 0; column < 2; column++)
        {
          // Create a tile and add it to the terrain.
          // (The tile content is loaded later.)
          var terrainTile = new TerrainTile(_graphicsService)
          {
            CellSize = 1,   // The terrain has a resolution of 1 height sample per world space unit.
          };
          terrain.Tiles.Add(terrainTile);

          // Create a rigid body with a height field for collision detection and add
          // it to the simulation. (The height data is loaded later.)
          var heightField = new HeightField
          {
            Depth = 1,
            UseFastCollisionApproximation = false,
          };
          var rigidBody = new RigidBody(heightField, new MassFrame(), null)
          {
            MotionType = MotionType.Static,
            UserData = terrainTile,
          };
          _simulation.RigidBodies.Add(rigidBody);

          // Store the tile for use later in this sample.
          _tiles[row, column] = new Tile
          {
            TerrainTile = terrainTile,
            RigidBody = rigidBody,
          };
        }
      }

      // Create a terrain node which represents the terrain in the scene graph.
      // The terrain node is rendered by the TerrainRenderer (see DeferredGraphicsScreen).
      // The material used to render the terrain is customizable.  The material must specify 
      // the effects for the different render passes which we use in the DeferredGraphicsScreen 
      // ("ShadowMap", "GBuffer", "Material").
      // The prebuilt DigitalRune content contains standard terrain effects. However, you could
      // change the effects to change how the material is rendered.
      // We can create the material by loading a .drmat file. Or we can create the material in
      // code like this:
      var shadowMapEffect = content.Load<Effect>("DigitalRune/Terrain/TerrainShadowMap");
      var gBufferEffect = content.Load<Effect>("DigitalRune/Terrain/TerrainGBuffer");
      var materialEffect = content.Load<Effect>("DigitalRune/Terrain/TerrainMaterial");
      var material = new Material
      {
        { "ShadowMap", new EffectBinding(_graphicsService, shadowMapEffect, null, EffectParameterHint.Material) },
        { "GBuffer", new EffectBinding(_graphicsService, gBufferEffect, null, EffectParameterHint.Material) },
        { "Material", new EffectBinding(_graphicsService, materialEffect, null, EffectParameterHint.Material) }
      };
      TerrainNode = new TerrainNode(terrain, material)
      {
        // The terrain rendering uses clipmaps.
        // The clipmaps are updated by the TerrainClipmapRenderer (see DeferredGraphicsScreen)
        // when the camera moves.
        // The base clipmap contains the basic geometry info (height, normals, hole info).
        // It also determines the terrain mesh resolution.
        BaseClipmap =
        {
          CellsPerLevel = 128,
          NumberOfLevels = 6
        },
        // The detail clipmap contains the splatted detail textures (e.g. grass, rock, ...).
        // (The max texture size in XNA is 4096x4096. That means we can fit 9 clipmap levels
        // into a single texture.)
        DetailClipmap =
        {
          CellsPerLevel = 1365,
          NumberOfLevels = 9,
        },
      };
      scene.Children.Add(TerrainNode);

      // Load the height and normal maps which define the terrain geometry.
      InitializeHeightsAndNormals();

      // Set the clipmap cell sizes.
      InitializeClipmapCellSizes();

      // Create the terrain layers which define the detail textures (e.g. grass, rock, ...)
      InitializeTerrainLayers(content);

      // Special note for AMD GPUs:
      // If we want anisotropic filtering for the terrain, then we need to enable mipmaps for
      // AMD GPUs. NVIDIA and Intel can do anisotropic filtering without mipmaps.
      //TerrainNode.DetailClipmap.EnableMipMap = true;

      CreateGuiControls();
    }
Esempio n. 30
0
        public RoadSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);

            var scene = _graphicsScreen.Scene;

            Services.Register(typeof(IScene), null, scene);

            // Add gravity and damping to the physics simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services, 5000);

            cameraGameObject.ResetPose(new Vector3(0, 2, 5), 0, 0);
            GameObjectService.Objects.Add(cameraGameObject);

            // Add the vehicle object from the vehicle sample.
            var vehicleObject = new ConstraintVehicleObject(Services);

            GameObjectService.Objects.Add(vehicleObject);

            // Add the car-follow-camera from the vehicle sample.
            var vehicleCameraObject = new VehicleCameraObject(vehicleObject.Vehicle.Chassis, Services);

            GameObjectService.Objects.Add(vehicleCameraObject);

            // Now, we have two CameraNodes. The graphics screen uses the camera node of the CameraObject,
            // as usual.
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;
            // The CameraObject should not react to input.
            cameraGameObject.IsEnabled = false;
            // The CameraNode of the VehicleCameraObject controls the other CameraNode.
            vehicleCameraObject.CameraNode.SceneChanged += (s, e) =>
            {
                cameraGameObject.CameraNode.SetLastPose(false);
                cameraGameObject.CameraNode.PoseWorld = vehicleCameraObject.CameraNode.PoseWorld;
            };

            // Add standard game objects.
            GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true)
            {
                EnableCloudShadows = false,
                FogSampleAngle     = 0.1f,
                FogSaturation      = 1,
            });

            var fogObject = new FogObject(Services)
            {
                AttachToCamera = true
            };

            GameObjectService.Objects.Add(fogObject);

            // Set nice default fog values.
            // (Note: If we change the fog values here, the GUI in the options window is not
            // automatically updated.)
            fogObject.FogNode.IsEnabled         = true;
            fogObject.FogNode.Fog.Start         = 100;
            fogObject.FogNode.Fog.End           = 2500;
            fogObject.FogNode.Fog.Start         = 100;
            fogObject.FogNode.Fog.HeightFalloff = 0.25f;

            // Add the terrain
            _terrainObject = new TerrainObject(Services);
            GameObjectService.Objects.Add(_terrainObject);

            // Add the TerrainRoadLayer to the terrain.
            CreateRoad();

            // Modify the terrain height values.
            ClampTerrainToRoad();
        }
Esempio n. 31
0
    public SceneCaptureCubeSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      // Create a graphics screen. This screen has to call the SceneCaptureRenderer 
      // to handle the SceneCaptureNodes!
      _graphicsScreen = new DeferredGraphicsScreen(Services) { DrawReticle = true };
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));
      
      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics Simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      // More standard objects.
      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      //GameObjectService.Objects.Add(new StaticSkyObject(Services));
      GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true));
      GameObjectService.Objects.Add(new GroundObject(Services));
      GameObjectService.Objects.Add(new DudeObject(Services));
      GameObjectService.Objects.Add(new DynamicObject(Services, 1));
      GameObjectService.Objects.Add(new DynamicObject(Services, 2));
      GameObjectService.Objects.Add(new DynamicObject(Services, 5));
      GameObjectService.Objects.Add(new DynamicObject(Services, 6));
      GameObjectService.Objects.Add(new DynamicObject(Services, 7));
      GameObjectService.Objects.Add(new FogObject(Services) { AttachToCamera = true });
      GameObjectService.Objects.Add(new LavaBallsObject(Services));

      // Add a few palm trees.
      Random random = new Random(12345);
      for (int i = 0; i < 10; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.5f, 1.2f);
        GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
      }

      // Load the "Bubble" mesh and place it at a fixed position in the scene.
      var modelNode = ContentManager.Load<ModelNode>("Bubble/Bubble");
      var meshNode = modelNode.GetDescendants().OfType<MeshNode>().First().Clone();
      meshNode.PoseWorld = new Pose(new Vector3F(0, 1, 0));
      _graphicsScreen.Scene.Children.Add(meshNode);

      // Surface of the mesh should reflect the scene in real-time. Reflections are
      // created using environment mapping: The scene is rendered into a cube map,
      // which is then applied to the mesh.
      // To render the scene into a cube map, we need to define a CameraNode and a
      // SceneCaptureNode: The CameraNode defines the point from where the scene is
      // captured. The SceneCaptureNode defines where and in which format the captured
      // image is needed.

      // Attach a camera to the center of the mesh.
      var projection = new PerspectiveProjection();
      projection.SetFieldOfView(ConstantsF.PiOver2, 1, 0.1f, 20);
      var captureCameraNode = new CameraNode(new Camera(projection));
      meshNode.Children = new SceneNodeCollection { captureCameraNode };

      // Attach a SceneCaptureNode with a cube map render target to the mesh.
      var renderToTexture = new RenderToTexture
      {
        Texture = new RenderTargetCube(
          GraphicsService.GraphicsDevice,
          256,
          true,
          SurfaceFormat.Color,
          DepthFormat.None),
      };
      var sceneCaptureNode = new SceneCaptureNode(renderToTexture)
      {
        Shape = meshNode.Shape,
        CameraNode = captureCameraNode,
      };
      meshNode.Children.Add(sceneCaptureNode);

      // The bubble model uses a special effect and is rendered in the "AlphaBlend"
      // render pass. Let's modify the effect parameters to use the created cube map
      // as the reflection map of the bubble.
      var effectBinding = meshNode.Mesh.Materials[0]["AlphaBlend"];
      effectBinding.Set("ReflectionStrength", 0.5f);
      effectBinding.Set("RefractionStrength", 0.0f);
      effectBinding.Set("FresnelBias", 1.0f);
      effectBinding.Set("BlendMode", 1.0f);
      effectBinding.Set("Alpha", 1.0f);
      effectBinding.Set("CustomEnvironmentMap", (TextureCube)renderToTexture.Texture);
    }
Esempio n. 32
0
        public CloudQuadSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics Simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new GroundObject(Services));
            GameObjectService.Objects.Add(new DudeObject(Services));
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            GameObjectService.Objects.Add(new LavaBallsObject(Services));
            GameObjectService.Objects.Add(new FogObject(Services));
            GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Barrier", 0.9f, new Pose(new Vector3F(0, 0, -2))));
            GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Cylinder", 0.9f, new Pose(new Vector3F(3, 0, 0), QuaternionF.CreateRotationY(MathHelper.ToRadians(-20)))));

            // The DynamicSkyObject creates the dynamic sky and lights but no clouds.
            var dynamicSkyObject = new DynamicSkyObject(Services, false, false, false);

            GameObjectService.Objects.Add(dynamicSkyObject);

            // Add a few palm trees.
            Random random = new Random(12345);

            for (int i = 0; i < 10; i++)
            {
                Vector3F  position    = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
                Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                float     scale       = random.NextFloat(0.5f, 1.2f);
                GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
            }

            // The model CloudQuad.fbx consists of a textured quad with a custom effect
            // "Cloud.fx". The effect uses several effect parameters. Constant effect
            // parameters are set in the Cloud.drmat material file.
            // The effect parameters, like "World", "WorldViewProjection", "CameraPosition",
            // are automatically updated by the graphics service. But the effect
            // contains 3 new effect parameters which must be set at runtime:
            // "SunDirection", "SunLight" and "SkyLight".
            // Therefore we add a custom effect interpreter and a custom effect binder
            // which tell the graphics manager what it should do with these parameters.
            // The effect interpreter and binder must be registered before the CloudQuad
            // model is loaded!
            _skyEffectInterpreter = GraphicsService.EffectInterpreters.OfType <SkyEffectInterpreter>().FirstOrDefault();
            if (_skyEffectInterpreter == null)
            {
                _skyEffectInterpreter = new SkyEffectInterpreter();
                GraphicsService.EffectInterpreters.Add(_skyEffectInterpreter);
            }

            _skyEffectBinder = GraphicsService.EffectBinders.OfType <SkyEffectBinder>().FirstOrDefault();
            if (_skyEffectBinder == null)
            {
                _skyEffectBinder = new SkyEffectBinder();
                GraphicsService.EffectBinders.Add(_skyEffectBinder);
            }

            // The effect binder defines several delegates which update the effect parameters
            // using values which are computed by the DynamicSkyObject.
            _skyEffectBinder.DynamicSkyObject = dynamicSkyObject;

            // Add several CloudQuad models in the sky with random scales and poses.
            for (int i = 0; i < 20; i++)
            {
                var scale = new Vector3F(
                    RandomHelper.Random.NextFloat(100, 200),
                    0,
                    RandomHelper.Random.NextFloat(100, 200));

                var position = new Vector3F(
                    RandomHelper.Random.NextFloat(-500, 500),
                    RandomHelper.Random.NextFloat(100, 200),
                    RandomHelper.Random.NextFloat(-500, 500));

                var orientation = Matrix33F.CreateRotationY(RandomHelper.Random.NextFloat(0, ConstantsF.TwoPi));
                GameObjectService.Objects.Add(new StaticObject(Services, "CloudQuad/CloudQuad", scale, new Pose(position, orientation), false, false));
            }
        }
Esempio n. 33
0
    public ParallaxTerrainSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);

      var scene = _graphicsScreen.Scene;
      Services.Register(typeof(IScene), null, scene);

      // Add standard game objects.
      var cameraGameObject = new CameraObject(Services, 5000);
      cameraGameObject.ResetPose(new Vector3F(0, 2, 0), 0, 0);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());
      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true)
      {
        EnableCloudShadows = false,
      });
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));

      // Create terrain.
      _terrainObject = new TerrainObject(Services);
      GameObjectService.Objects.Add(_terrainObject);

      // To see parallax occlusion mapping, we need a detail texture with a height map.
      // In this sample we reuse the pavement texture of the ParallaxMappingSample and 
      // add it to the terrain.
      for (int row = 0; row < 2; row++)
      {
        for (int column = 0; column < 2; column++)
        {
          var terrainTile = _terrainObject.TerrainNode.Terrain.Tiles[row * 2 + column];
          string tilePostfix = "-" + row + "-" + column; // e.g. "-0-1"

          var materialPavement = new TerrainMaterialLayer(GraphicsService)
          {
            DiffuseColor = new Vector3F(1),
            SpecularColor = new Vector3F(5),
            SpecularPower = 20,
            DiffuseTexture = ContentManager.Load<Texture2D>("Parallax/AgedPavement_diffuse"),
            NormalTexture = ContentManager.Load<Texture2D>("Parallax/AgedPavement_normal"),
            SpecularTexture = ContentManager.Load<Texture2D>("Parallax/AgedPavement_specular"),
            HeightTexture = ContentManager.Load<Texture2D>("Parallax/AgedPavement_height"),
            TileSize = 0.005f * 512,
            BlendTexture = ContentManager.Load<Texture2D>("Terrain/Terrain001-Blend-Grass" + tilePostfix),
            BlendTextureChannel = 0,
            BlendHeightInfluence = 0.5f,
            BlendThreshold = 0.5f,
            BlendRange = 0.5f,
          };

          terrainTile.Layers.Add(materialPavement);
        }
      }

      // Replace the terrain effects with effects which support parallax occlusion mapping.
      UpdateTerrainMaterial(true);

      CreateGuiControls();
    }
Esempio n. 34
0
    public BatchingSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);

      var scene = _graphicsScreen.Scene;
      Services.Register(typeof(IScene), null, scene);

      // Add gravity and damping to the physics simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      // Add standard game objects.
      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true));
      GameObjectService.Objects.Add(new GroundObject(Services));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new LavaBallsObject(Services));

      // Create the scene data for the different batching strategies.
      CreateScene();

      // Choose the initially selected batching strategy.
      SetBatchingType(BatchingType.StaticBatching);

      CreateGuiControls();
    }
        public ProceduralTerrainSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);

            var scene = _graphicsScreen.Scene;

            Services.Register(typeof(IScene), null, scene);

            // Add gravity and damping to the physics simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services, 5000);

            cameraGameObject.ResetPose(new Vector3(0, 2, 5), 0, 0);
            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            // Add standard game objects.
            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            GameObjectService.Objects.Add(new LavaBallsObject(Services));
            GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true)
            {
                EnableCloudShadows = false,
                FogSampleAngle     = 0.1f,
                FogSaturation      = 1,
            });

            var fogObject = new FogObject(Services)
            {
                AttachToCamera = true
            };

            GameObjectService.Objects.Add(fogObject);

            // Set nice default fog values.
            // (Note: If we change the fog values here, the GUI in the options window is not
            // automatically updated.)
            fogObject.FogNode.IsEnabled         = true;
            fogObject.FogNode.Fog.Start         = 100;
            fogObject.FogNode.Fog.End           = 2500;
            fogObject.FogNode.Fog.Start         = 100;
            fogObject.FogNode.Fog.HeightFalloff = 0.25f;

            // Add a procedural terrain.
            var terrainObject = new ProceduralTerrainObject(Services);

            GameObjectService.Objects.Add(terrainObject);

            SampleFramework.ShowOptionsWindow();
        }
        public ImageBasedLightingSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            // Add standard game objects.
            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true));
            GameObjectService.Objects.Add(new GroundObject(Services));
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            GameObjectService.Objects.Add(new DudeObject(Services)
            {
                Pose = new Pose(new Vector3F(-4, 0, 4))
            });
            GameObjectService.Objects.Add(new LavaBallsObject(Services));

            // Create 3 image-based lights.
            for (int i = 0; i < 3; i++)
            {
                _imageBasedLights[i] = new ImageBasedLight
                {
                    DiffuseIntensity  = 1f,
                    SpecularIntensity = 1f,
                    FalloffRange      = 0.2f,
                    BlendMode         = 1, // 0 = add to ambient light, 1 = replace ambient light
                };
            }

            // The first IBL is infinite.
            _imageBasedLights[0].Shape = Shape.Infinite;

            // The other 2 IBLs have a box shape and use specify an AABB which is
            // aligned to the with scene objects (walls, barrels, palm tree line).
            _imageBasedLights[1].Shape = new BoxShape(7.5f, 10, 7);
            _imageBasedLights[1].EnableLocalizedReflection = true;
            _imageBasedLights[1].LocalizedReflectionBox    = new Aabb(new Vector3F(-100, -2, -100), new Vector3F(3.5f, 2, 100));

            _imageBasedLights[2].Shape = new BoxShape(7.5f, 10, 7);
            _imageBasedLights[2].EnableLocalizedReflection = true;
            _imageBasedLights[2].LocalizedReflectionBox    = new Aabb(new Vector3F(-3, -2, -100), new Vector3F(3.5f, 2, 100));

            // Add 3 light nodes to add the IBL to the scene.
            for (int i = 0; i < 3; i++)
            {
                _lightNodes[i] = new LightNode(_imageBasedLights[i]);
                _graphicsScreen.Scene.Children.Add(_lightNodes[i]);
            }

            _lightNodes[0].PoseLocal = _globalRotation * new Pose(new Vector3F(-5, 5, 5));
            _lightNodes[1].PoseLocal = _globalRotation * new Pose(new Vector3F(0, 2, 0));
            _lightNodes[2].PoseLocal = _globalRotation * new Pose(new Vector3F(0, 2, -4));

            // Increase specular power of ground to create sharper reflections.
            var groundModelNode = (ModelNode)_graphicsScreen.Scene.GetSceneNode("Ground");
            var groundMaterial  = ((MeshNode)groundModelNode.Children[0]).Mesh.Materials[0];

            groundMaterial["GBuffer"].Set("SpecularPower", 1000000.0f);

            // Add more test objects to the scenes.
            AddLightProbes();
            AddTestSpheres();
            AddTestObjects();

            CreateGuiControls();
        }
Esempio n. 37
0
    public CloudQuadSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics Simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new GroundObject(Services));
      GameObjectService.Objects.Add(new DudeObject(Services));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new LavaBallsObject(Services));
      GameObjectService.Objects.Add(new FogObject(Services));
      GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Barrier", 0.9f, new Pose(new Vector3F(0, 0, -2))));
      GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Cylinder", 0.9f, new Pose(new Vector3F(3, 0, 0), QuaternionF.CreateRotationY(MathHelper.ToRadians(-20)))));

      // The DynamicSkyObject creates the dynamic sky and lights but no clouds.
      var dynamicSkyObject = new DynamicSkyObject(Services, false, false, false);
      GameObjectService.Objects.Add(dynamicSkyObject);

      // Add a few palm trees.
      Random random = new Random(12345);
      for (int i = 0; i < 10; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.5f, 1.2f);
        GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
      }

      // The model CloudQuad.fbx consists of a textured quad with a custom effect 
      // "Cloud.fx". The effect uses several effect parameters. Constant effect 
      // parameters are set in the Cloud.drmat material file. 
      // The effect parameters, like "World", "WorldViewProjection", "CameraPosition",
      // are automatically updated by the graphics service. But the effect 
      // contains 3 new effect parameters which must be set at runtime: 
      // "SunDirection", "SunLight" and "SkyLight".
      // Therefore we add a custom effect interpreter and a custom effect binder 
      // which tell the graphics manager what it should do with these parameters.
      // The effect interpreter and binder must be registered before the CloudQuad
      // model is loaded!
      _skyEffectInterpreter = GraphicsService.EffectInterpreters.OfType<SkyEffectInterpreter>().FirstOrDefault();
      if (_skyEffectInterpreter == null)
      {
        _skyEffectInterpreter = new SkyEffectInterpreter();
        GraphicsService.EffectInterpreters.Add(_skyEffectInterpreter);
      }

      _skyEffectBinder = GraphicsService.EffectBinders.OfType<SkyEffectBinder>().FirstOrDefault();
      if (_skyEffectBinder == null)
      {
        _skyEffectBinder = new SkyEffectBinder();
        GraphicsService.EffectBinders.Add(_skyEffectBinder);
      }

      // The effect binder defines several delegates which update the effect parameters
      // using values which are computed by the DynamicSkyObject.
      _skyEffectBinder.DynamicSkyObject = dynamicSkyObject;

      // Add several CloudQuad models in the sky with random scales and poses.
      for (int i = 0; i < 20; i++)
      {
        var scale = new Vector3F(
          RandomHelper.Random.NextFloat(100, 200),
          0,
          RandomHelper.Random.NextFloat(100, 200));

        var position = new Vector3F(
          RandomHelper.Random.NextFloat(-500, 500),
          RandomHelper.Random.NextFloat(100, 200),
          RandomHelper.Random.NextFloat(-500, 500));

        var orientation = Matrix33F.CreateRotationY(RandomHelper.Random.NextFloat(0, ConstantsF.TwoPi));
        GameObjectService.Objects.Add(new StaticObject(Services, "CloudQuad/CloudQuad", scale, new Pose(position, orientation), false, false));
      }
    }
Esempio n. 38
0
        public WaterSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;
            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics Simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            // More standard objects.
            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            //GameObjectService.Objects.Add(new StaticSkyObject(Services));
            var dynamicSkyObject = new DynamicSkyObject(Services, true, false, true);

            GameObjectService.Objects.Add(dynamicSkyObject);

            // Add a ground plane with some detail to see the water refractions.
            Simulation.RigidBodies.Add(new RigidBody(new PlaneShape(new Vector3(0, 1, 0), 0)));
            GameObjectService.Objects.Add(new StaticObject(Services, "Gravel/Gravel", 1, new Pose(new Vector3(0, 0.001f, 0))));

            GameObjectService.Objects.Add(new DudeObject(Services));
            GameObjectService.Objects.Add(new DynamicObject(Services, 1));
            GameObjectService.Objects.Add(new DynamicObject(Services, 2));
            GameObjectService.Objects.Add(new DynamicObject(Services, 5));
            GameObjectService.Objects.Add(new DynamicObject(Services, 6));
            GameObjectService.Objects.Add(new DynamicObject(Services, 7));
            GameObjectService.Objects.Add(new FogObject(Services)
            {
                AttachToCamera = true
            });

            // The LavaBalls class controls all lava ball instances.
            var lavaBalls = new LavaBallsObject(Services);

            GameObjectService.Objects.Add(lavaBalls);

            // Add a few palm trees.
            var random = new Random(12345);

            for (int i = 0; i < 10; i++)
            {
                Vector3 position    = new Vector3(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
                Matrix  orientation = Matrix.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                float   scale       = random.NextFloat(0.5f, 1.2f);
                GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
            }

            // Define the appearance of the water.
            var water = new Water
            {
                SpecularColor = new Vector3(10f),

                // Small water ripples/waves are created using scrolling normal maps.
                NormalMap0         = ContentManager.Load <Texture2D>("Water/Wave0"),
                NormalMap1         = ContentManager.Load <Texture2D>("Water/Wave1"),
                NormalMap0Scale    = 1.8f,
                NormalMap1Scale    = 2.2f,
                NormalMap0Velocity = new Vector3(-0.02f, 0, 0.03f),
                NormalMap1Velocity = new Vector3(0.02f, 0, -0.03f),
                NormalMap0Strength = 0.5f,
                NormalMap1Strength = 0.5f,

                ReflectionDistortion = 0.2f,
                ReflectionColor      = new Vector3(0.7f),
                RefractionDistortion = 0.05f,
            };

            // Create a box-shaped body of water.
            // We use a TransformedShape containing a BoxShape because the top of the
            // water body must be at height 0.
            var shape = new TransformedShape(new GeometricObject(
                                                 new BoxShape(10, 1, 20),
                                                 new Pose(new Vector3(0, -0.5f, 0))));

            _waterNode0 = new WaterNode(water, shape)
            {
                PoseWorld              = new Pose(new Vector3(-1, 0.5f, 0), Matrix.CreateRotationY(0.1f)),
                SkyboxReflection       = _graphicsScreen.Scene.GetDescendants().OfType <SkyboxNode>().First(),
                DepthBufferWriteEnable = true,
            };
            _graphicsScreen.Scene.Children.Add(_waterNode0);

            // Optional: Create a WaterFlow to move the water using a flow texture.
            _waterFlow0 = new WaterFlow
            {
                FlowMapSpeed     = 0.5f,
                FlowMap          = GenerateFlowMap(),
                CycleDuration    = 3f,
                NoiseMapStrength = 0.1f,
                NoiseMapScale    = 0.5f,
            };
            _waterNode0.Flow = _waterFlow0;

            // Optional: Use a planar reflection instead of the skybox reflection.
            // We add a PlanarReflectionNode as a child of the WaterNode.
            var renderToTexture = new RenderToTexture
            {
                Texture = new RenderTarget2D(GraphicsService.GraphicsDevice, 512, 512, false, SurfaceFormat.HdrBlendable, DepthFormat.None),
            };
            var planarReflectionNode = new PlanarReflectionNode(renderToTexture)
            {
                // Same shape as WaterNode.
                Shape = _waterNode0.Shape,

                // Reflection plane is horizontal.
                NormalLocal = new Vector3(0, 1, 0),
            };

            _waterNode0.PlanarReflection = planarReflectionNode;
            _waterNode0.Children         = new SceneNodeCollection(1)
            {
                planarReflectionNode
            };

            // Create a short river with an inclined water surface.
            // Using a WaterFlow with a SurfaceSlopeSpeed, the water automatically flows
            // down the inclined surface.
            _waterNode1 = new WaterNode(water, GetSpiralShape())
            {
                PoseWorld = new Pose(new Vector3(10, 1.5f, 0), Matrix.CreateRotationY(0.1f)),
                EnableUnderwaterEffect = false,
                SkyboxReflection       = _graphicsScreen.Scene.GetDescendants().OfType <SkyboxNode>().First(),
                Flow = new WaterFlow
                {
                    SurfaceSlopeSpeed = 0.5f,
                    CycleDuration     = 2f,
                    NoiseMapStrength  = 0.1f,
                    NoiseMapScale     = 1,
                }
            };
            _graphicsScreen.Scene.Children.Add(_waterNode1);
        }
Esempio n. 39
0
        public InGameUISample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            // Add gravity and damping to the physics simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Create the DeferredGraphicsScreen.
            var graphicsScreen = new DeferredGraphicsScreen(Services);

            graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, graphicsScreen);

            Services.Register(typeof(DebugRenderer), null, graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, graphicsScreen.Scene);

            // some 3D objects
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;
            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new StaticSkyObject(Services));
            GameObjectService.Objects.Add(new GroundObject(Services));
            for (int i = 0; i < 10; i++)
            {
                GameObjectService.Objects.Add(new DynamicObject(Services, 3));
            }

            // Create the UIScreen which is rendered into the back buffer.
            Theme      theme    = ContentManager.Load <Theme>("UI Themes/Aero/Theme");
            UIRenderer renderer = new UIRenderer(Game, theme);

            _normalUIScreen = new NormalUIScreen(renderer);
            UIService.Screens.Add(_normalUIScreen);

            // Handle the InputProcessed event of the Image control.
            _normalUIScreen.Image.InputProcessed += OnGameViewControlInputProcessed;

            // Create the DelegateGraphicsScreen. This graphics screen is on top of the
            // DeferredGraphicsScreen and instructs the graphics service to render the
            // previous screen into an off-screen render target.
            var delegateGraphicsScreen = new DelegateGraphicsScreen(GraphicsService)
            {
                RenderCallback = Render,
                RenderPreviousScreensToTexture = true,
                SourceTextureFormat            = new RenderTargetFormat(
                    (int)_normalUIScreen.Image.Width,
                    (int)_normalUIScreen.Image.Height,
                    false,
                    SurfaceFormat.Color,
                    DepthFormat.Depth24),
            };

            GraphicsService.Screens.Insert(1, delegateGraphicsScreen);

            // Create the UIScreen that is rendered into a render target and mapped onto the 3D game objects.
            _inGameUIScreenRenderTarget = new RenderTarget2D(GraphicsService.GraphicsDevice, 600, 250, false, SurfaceFormat.Color, DepthFormat.None);
            _inGameScreen = new InGameUIScreen(Services, renderer)
            {
                InputEnabled = false,
                Width        = _inGameUIScreenRenderTarget.Width,
                Height       = _inGameUIScreenRenderTarget.Height,
            };
            UIService.Screens.Add(_inGameScreen);

            // We can use the off-screen render target anywhere in the 3D scene. Here, we
            // use it to replace the normal "TestCard" texture of the TV objects and the ProjectorLights.
            foreach (var node in graphicsScreen.Scene.GetDescendants())
            {
                var meshNode = node as MeshNode;
                if (meshNode != null)
                {
                    foreach (var material in meshNode.Mesh.Materials)
                    {
                        if (material.Name == "TestCard")
                        {
                            material["Material"].Set("EmissiveTexture", (Texture)_inGameUIScreenRenderTarget);
                            material["Material"].Set("Exposure", 0.1f);
                        }
                    }
                    continue;
                }

                var lightNode = node as LightNode;
                if (lightNode != null && lightNode.Light is ProjectorLight)
                {
                    ((ProjectorLight)lightNode.Light).Texture = _inGameUIScreenRenderTarget;
                }
            }
        }
        public EnvironmentLightSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics Simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new GroundObject(Services));
            GameObjectService.Objects.Add(new DudeObject(Services));
            var lavaBallsObject = new LavaBallsObject(Services);

            GameObjectService.Objects.Add(lavaBallsObject);
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            GameObjectService.Objects.Add(new FogObject(Services));
            GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Barrier", 0.9f, new Pose(new Vector3(0, 0, -2))));
            GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Cylinder", 0.9f, new Pose(new Vector3(3, 0, 0), Quaternion.CreateRotationY(MathHelper.ToRadians(-20)))));
            GameObjectService.Objects.Add(new StaticSkyObject(Services));

            // Add a few palm trees.
            Random random = new Random(12345);

            for (int i = 0; i < 10; i++)
            {
                Vector3 position    = new Vector3(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
                Matrix  orientation = Matrix.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                float   scale       = random.NextFloat(0.5f, 1.2f);
                GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
            }

            // Add some more dynamic objects.
            for (int i = 0; i < 5; i++)
            {
                lavaBallsObject.Spawn();
                GameObjectService.Objects.Add(new ProceduralObject(Services));
                GameObjectService.Objects.Add(new DynamicObject(Services, 7));
            }

            // To show the effect of the EnvironmentLight in isolation, disable all other light sources.
            //foreach (var light in _graphicsScreen.Scene.GetDescendants().OfType<LightNode>())
            //  light.IsEnabled = false;

            // Add the environment light.
            var environmentLight = new EnvironmentLight
            {
                Color             = new Vector3(0.1f),
                DiffuseIntensity  = 0,
                SpecularIntensity = 1,
                EnvironmentMap    = ContentManager.Load <TextureCube>("Sky2"),
            };
            var environmentLightNode = new LightNode(environmentLight)
            {
                Name = "Environment",
            };

            _graphicsScreen.Scene.Children.Add(environmentLightNode);

            // The EnvironmentLight is a new light type. We have to register a light renderer
            // for this light in the LightRenderer of the DeferredGraphicsScreen.
            _graphicsScreen.LightBufferRenderer.LightRenderer.Renderers.Add(new EnvironmentLightRenderer(GraphicsService));

            // EnvironmentLight.fx uses the specular power of the materials to determine
            // which mip map level of the cube is reflected.
            // In reality, a high specular power is necessary to reflect the cube map
            // with all its detail. To reflect a cube map level with 512 texels size, we
            // need a specular power of ~200000.
            // To make the reflection effects more obvious, let's change some material properties
            // and make the more reflective.

            // ProceduralObject:
            var proceduralObjects = _graphicsScreen.Scene
                                    .GetDescendants()
                                    .OfType <MeshNode>()
                                    .Where(mn => mn.Mesh.Name == "ProceduralObject")
                                    .Select(mn => mn.Mesh);

            foreach (var mesh in proceduralObjects)
            {
                foreach (var material in mesh.Materials)
                {
                    material["GBuffer"].Set("SpecularPower", 10000f);
                    material["Material"].Set("DiffuseColor", new Vector3(0.01f));
                    material["Material"].Set("SpecularColor", new Vector3(1));
                }
            }

            // Frame of GlassBox:
            var glassBoxes = _graphicsScreen.Scene
                             .GetDescendants()
                             .OfType <ModelNode>()
                             .Where(mn => mn.Name == "GlassBox")
                             .Select(mn => ((MeshNode)mn.Children[0]).Mesh);

            foreach (var mesh in glassBoxes)
            {
                foreach (var material in mesh.Materials.Where(m => m.Contains("GBuffer")))
                {
                    material["GBuffer"].Set("SpecularPower", 100000f);
                    material["Material"].Set("DiffuseColor", new Vector3(0.0f));
                    material["Material"].Set("SpecularColor", new Vector3(1));
                }
            }

            // LavaBall:
            var lavaBalls = _graphicsScreen.Scene
                            .GetDescendants()
                            .OfType <ModelNode>()
                            .Where(mn => mn.Name == "LavaBall")
                            .Select(mn => ((MeshNode)mn.Children[0]).Mesh);

            foreach (var mesh in lavaBalls)
            {
                foreach (var material in mesh.Materials.Where(m => m.Contains("GBuffer")))
                {
                    material["GBuffer"].Set("SpecularPower", 10000f);
                    material["Material"].Set("DiffuseColor", new Vector3(0.0f));
                    material["Material"].Set("SpecularColor", new Vector3(10));
                    material["Material"].Set("EmissiveColor", new Vector3(0.0f));
                }
            }

            // Ground plane:
            var groundPlanes = _graphicsScreen.Scene
                               .GetDescendants()
                               .OfType <ModelNode>()
                               .Where(mn => mn.Name == "Ground")
                               .Select(mn => ((MeshNode)mn.Children[0]).Mesh);

            foreach (var mesh in groundPlanes)
            {
                foreach (var material in mesh.Materials.Where(m => m.Contains("GBuffer")))
                {
                    material["GBuffer"].Set("SpecularPower", 200000.0f);
                    material["Material"].Set("DiffuseColor", new Vector3(0.5f));
                    material["Material"].Set("SpecularColor", new Vector3(0.4f));
                }
            }

            // Please note, XNA does not filter cube maps over cube map borders. Therefore, reflections
            // of low resolution mip map levels might show obvious borders between the cube map
            // sides. In this case you can change the EnvironmentLight.fx effect to always reflect
            // the mip map level 0.
            // This is not a problem with MonoGame because DirectX automatically filters cube map borders.
        }
Esempio n. 41
0
        // Creates a test scene with a lot of randomly placed objects.
        internal static void CreateScene(ServiceContainer services, ContentManager content, DeferredGraphicsScreen graphicsScreen)
        {
            var gameObjectService = services.GetInstance <IGameObjectService>();
            var graphicsService   = services.GetInstance <IGraphicsService>();

            gameObjectService.Objects.Add(new DynamicSkyObject(services, true, false, true)
            {
                EnableAmbientLight = false, // Disable ambient light of sky to make shadows more visible.
                EnableCloudShadows = false
            });

            gameObjectService.Objects.Add(new GroundObject(services));
            gameObjectService.Objects.Add(new DynamicObject(services, 1));
            gameObjectService.Objects.Add(new DynamicObject(services, 2));
            gameObjectService.Objects.Add(new DynamicObject(services, 3));
            gameObjectService.Objects.Add(new DynamicObject(services, 5));
            gameObjectService.Objects.Add(new DynamicObject(services, 6));
            gameObjectService.Objects.Add(new DynamicObject(services, 7));
            gameObjectService.Objects.Add(new ObjectCreatorObject(services));
            gameObjectService.Objects.Add(new LavaBallsObject(services));

            var random = new Random();

            // Spheres
            var sphereMesh = SampleHelper.CreateMesh(content, graphicsService, new SphereShape(1));

            for (int i = 0; i < 100; i++)
            {
                Vector3 position = new Vector3(random.NextFloat(-100, 100), random.NextFloat(0, 3), random.NextFloat(-100, 100));
                float   scale    = random.NextFloat(0.5f, 3f);
                var     meshNode = new MeshNode(sphereMesh)
                {
                    PoseLocal  = new Pose(position),
                    ScaleLocal = new Vector3(scale),
                    IsStatic   = true,
                };
                graphicsScreen.Scene.Children.Add(meshNode);
            }

            // Boxes
            var boxMesh = SampleHelper.CreateMesh(content, graphicsService, new BoxShape(1, 1, 1));

            for (int i = 0; i < 100; i++)
            {
                Vector3    position    = new Vector3(random.NextFloat(-100, 100), random.NextFloat(0, 3), random.NextFloat(-100, 100));
                Quaternion orientation = random.NextQuaternion();
                Vector3    scale       = random.NextVector3(0.1f, 4f);
                var        meshNode    = new MeshNode(boxMesh)
                {
                    PoseLocal  = new Pose(position, orientation),
                    ScaleLocal = scale,
                    IsStatic   = true,
                };
                graphicsScreen.Scene.Children.Add(meshNode);
            }

            // Height field with smooth hills.
            var numberOfSamplesX = 20;
            var numberOfSamplesZ = 20;
            var samples          = new float[numberOfSamplesX * numberOfSamplesZ];

            for (int z = 0; z < numberOfSamplesZ; z++)
            {
                for (int x = 0; x < numberOfSamplesX; x++)
                {
                    if (x == 0 || z == 0 || x == 19 || z == 19)
                    {
                        // Set this boundary elements to a low height, so that the height field is connected
                        // to the ground.
                        samples[z * numberOfSamplesX + x] = -1;
                    }
                    else
                    {
                        // A sine/cosine function that creates some interesting waves.
                        samples[z * numberOfSamplesX + x] = 1 + (float)(Math.Cos(z / 2f) * Math.Sin(x / 2f) * 1);
                    }
                }
            }
            var heightField         = new HeightField(0, 0, 20, 20, samples, numberOfSamplesX, numberOfSamplesZ);
            var heightFieldMesh     = SampleHelper.CreateMesh(content, graphicsService, heightField);
            var heightFieldMeshNode = new MeshNode(heightFieldMesh)
            {
                PoseLocal  = new Pose(new Vector3(20, 0, -20)),
                ScaleLocal = new Vector3(1, 2, 1),
                IsStatic   = true,
            };

            graphicsScreen.Scene.Children.Add(heightFieldMeshNode);

            // Dudes.
            for (int i = 0; i < 10; i++)
            {
                Vector3 position    = new Vector3(random.NextFloat(-20, 20), 0, random.NextFloat(-20, 20));
                Matrix  orientation = Matrix.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                gameObjectService.Objects.Add(new DudeObject(services)
                {
                    Pose = new Pose(position, orientation)
                });
            }

            // Palm trees.
            for (int i = 0; i < 100; i++)
            {
                Vector3 position    = new Vector3(random.NextFloat(-80, 80), 0, random.NextFloat(-100, 100));
                Matrix  orientation = Matrix.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                float   scale       = random.NextFloat(0.5f, 1.2f);
                gameObjectService.Objects.Add(new StaticObject(services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
            }

            // Rocks
            for (int i = 0; i < 100; i++)
            {
                Vector3    position    = new Vector3(random.NextFloat(-80, 80), 1, random.NextFloat(-100, 100));
                Quaternion orientation = RandomHelper.Random.NextQuaternion();
                float      scale       = random.NextFloat(0.5f, 1.2f);
                gameObjectService.Objects.Add(new StaticObject(services, "Rock/rock_05", scale, new Pose(position, orientation)));
            }

            // Grass
            for (int i = 0; i < 100; i++)
            {
                Vector3 position    = new Vector3(random.NextFloat(-20, 20), 0, random.NextFloat(-20, 20));
                Matrix  orientation = Matrix.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                float   scale       = random.NextFloat(0.5f, 1.2f);
                gameObjectService.Objects.Add(new StaticObject(services, "Grass/Grass", scale, new Pose(position, orientation)));
            }

            // More plants
            for (int i = 0; i < 100; i++)
            {
                Vector3 position    = new Vector3(random.NextFloat(-20, 20), 0, random.NextFloat(-20, 20));
                Matrix  orientation = Matrix.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                float   scale       = random.NextFloat(0.5f, 1.2f);
                gameObjectService.Objects.Add(new StaticObject(services, "Parviflora/Parviflora", scale, new Pose(position, orientation)));
            }

            // "Skyscrapers"
            for (int i = 0; i < 20; i++)
            {
                Vector3 position    = new Vector3(random.NextFloat(90, 100), 0, random.NextFloat(-100, 100));
                Matrix  orientation = Matrix.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                Vector3 scale       = new Vector3(random.NextFloat(6, 20), random.NextFloat(10, 100), random.NextFloat(6, 20));
                var     meshNode    = new MeshNode(boxMesh)
                {
                    PoseLocal  = new Pose(position, orientation),
                    ScaleLocal = scale,
                    IsStatic   = true,
                    UserFlags  = 1, // Mark the distant huge objects. Used in render callbacks in the CompositeShadowSample.
                };
                graphicsScreen.Scene.Children.Add(meshNode);
            }

            // "Hills"
            for (int i = 0; i < 20; i++)
            {
                Vector3 position = new Vector3(random.NextFloat(-90, -100), 0, random.NextFloat(-100, 100));
                Vector3 scale    = new Vector3(random.NextFloat(10, 20), random.NextFloat(10, 30), random.NextFloat(10, 20));
                var     meshNode = new MeshNode(sphereMesh)
                {
                    PoseLocal  = new Pose(position),
                    ScaleLocal = scale,
                    IsStatic   = true,
                    UserFlags  = 1, // Mark the distant huge objects. Used in render callbacks in the CompositeShadowSample.
                };
                graphicsScreen.Scene.Children.Add(meshNode);
            }
        }
Esempio n. 42
0
    public CompositeShadowSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;
      _graphicsScreen = new DeferredGraphicsScreen(Services)
      {
        // For debugging: Disable materials and only show light buffer.
        DebugMode = DeferredGraphicsDebugMode.VisualizeDiffuseLightBuffer
      };
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);

      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      GameObjectService.Objects.Add(new GrabObject(Services));

      // Create test scene.
      ShadowSample.CreateScene(Services, ContentManager, _graphicsScreen);

      // Create 3 different shadows:
      // The VarianceShadow covers the whole level.
      _vsmShadow = new VarianceShadow
      {
        Prefer16Bit = false,
        PreferredSize = 512,
        MinLightDistance = 200,
        MaxDistance = 200,
        FadeOutRange = 0,
        ShadowFog = 0,
        TargetArea = new Aabb(new Vector3F(-100, 0, -100), new Vector3F(100, 50, 100))
      };
      _vsmShadow.Filter = new Blur(GraphicsService);
      _vsmShadow.Filter.NumberOfPasses = 1;
      _vsmShadow.Filter.InitializeGaussianBlur(11, 3, false);

      // The CascadedShadow for static objects.
      _staticCascadedShadow = new CascadedShadow
      {
        PreferredSize = 1024,
        Prefer16Bit = true,
        Distances = new Vector4F(4, 12, 20, 80),
        MinLightDistance = 200,
      };

      // The CascadedShadow for dynamic objects covering a smaller distance.
      _dynamicCascadedShadow = new CascadedShadow
      {
        PreferredSize = 1024,
        Prefer16Bit = true,
        NumberOfCascades = 2,
        Distances = new Vector4F(4, 12, 0, 0),
        MinLightDistance = 200,
      };

      // Get directional light created by the DynamicSkyObject and replace the default
      // shadow with our a CompositeShadow.
      _lightNode = _graphicsScreen.Scene.GetDescendants().OfType<LightNode>().First(n => n.Shadow is CascadedShadow);
      _lightNode.Shadow = new CompositeShadow
      {
        Shadows =
        {
          _vsmShadow,
          _staticCascadedShadow,
          _dynamicCascadedShadow,
        }
      };

      // We do not want to render the same objects into all 3 shadow maps. We use a custom
      // render callback to render each objects into only one of the shadow maps.
      _graphicsScreen.ShadowMapRenderer.RenderCallback = context =>
      {
        // Query all shadow casters.
        var query = context.Scene.Query<ShadowCasterQuery>(context.CameraNode, context);
        if (query.ShadowCasters.Count == 0)
          return false;

        // Get the shadow which is currently being rendered.
        var shadow = context.Object;

        // Create a list of scene nodes for the current shadow.
        var list = _tempList;
        if (shadow == _vsmShadow)
        {
          // Get the hills and skyscrapers which have been marked with a user flag 
          // in ShadowSample.CreateScene.
          foreach (var node in query.ShadowCasters)
            if (node.UserFlags == 1)
              _tempList.Add(node);
        }
        else if (shadow == _staticCascadedShadow)
        {
          // Get all static objects except the hills/skyscrapers.
          foreach (var node in query.ShadowCasters)
            if (node.UserFlags == 0 && node.IsStatic)
              _tempList.Add(node);
        }
        else if (shadow == _dynamicCascadedShadow)
        {
          // Get all dynamic objects.
          foreach (var node in query.ShadowCasters)
            if (!node.IsStatic)
              _tempList.Add(node);
        }
        else
        {
          // Other shadows of other lights.
          list = query.ShadowCasters;
        }

        // Render the selected objects into the shadow map.
        _graphicsScreen.MeshRenderer.Render(list, context);

        _tempList.Clear();
        return true;
      };

      // Register the custom renderers for the VarianceShadow.
      _graphicsScreen.ShadowMapRenderer.Renderers.Add(new VarianceShadowMapRenderer(_graphicsScreen.ShadowMapRenderer.RenderCallback));
      _graphicsScreen.ShadowMaskRenderer.Renderers.Add(new VarianceShadowMaskRenderer(GraphicsService));

      CreateGuiControls();
    }
Esempio n. 43
0
    public VegetationSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);

      var scene = _graphicsScreen.Scene;
      Services.Register(typeof(IScene), null, scene);

      // Add gravity and damping to the physics simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      // Add standard game objects.
      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true));
      GameObjectService.Objects.Add(new GroundObject(Services));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new LavaBallsObject(Services));

      // Add a new game object which controls the wind velocity and "Wind" parameters in effects.
      GameObjectService.Objects.Add(new WindObject(Services));


      // The vegetation effects use an effect parameter named "LodDistances". By default all
      // effect parameters are shared per "Material". However, we want to change the parameter
      // per instance. Therefore, the effect declares the parameter like this:
      // float3 LodDistances < string Hint = "PerInstance"; >;
      // However, MonoGame does not yet support effect annotations. Therefore, we tell the
      // graphics service that the "LodDistances" parameter should be stored per instance by
      // adding a new entry to the default effect interpreter.
      var defaultEffectInterpreter = GraphicsService.EffectInterpreters.OfType<DefaultEffectInterpreter>().First();
      if (!defaultEffectInterpreter.ParameterDescriptions.ContainsKey("LodDistances"))
        defaultEffectInterpreter.ParameterDescriptions.Add(
          "LodDistances",
          (parameter, i) => new EffectParameterDescription(parameter, "LodDistances", i, EffectParameterHint.PerInstance));


      // Load three different plant models.
      // The palm tree consists of a single mesh. It uses the *Vegetation.fx effects.
      ModelNode palmModelNode = ContentManager.Load<ModelNode>("Vegetation/PalmTree/palm_tree");
      Mesh palmMesh = ((MeshNode)palmModelNode.Children[0]).Mesh;

      // The bird's nest plant consists of 2 LODs. It uses the *Vegetation.fx effects.
      ModelNode plantModelNode = ContentManager.Load<ModelNode>("Vegetation/BirdnestPlant/BirdnestPlant");
      LodGroupNode plantLodGroupNode = plantModelNode.GetDescendants().OfType<LodGroupNode>().First().Clone();

      // The grass model consists of one mesh. It uses the *Grass.fx effects.
      ModelNode grassModelNode = ContentManager.Load<ModelNode>("Vegetation/Grass/grass");
      Mesh grassMesh = ((MeshNode)grassModelNode.Children[0]).Mesh;

      // Store all used meshes in a list for use in UpdateMaterialEffectParameters.
      _meshes.Add(palmMesh);
      foreach (var meshNode in plantLodGroupNode.Levels.Select(lodEntry => lodEntry.Node).OfType<MeshNode>())
        _meshes.Add(meshNode.Mesh);
      _meshes.Add(grassMesh);

      // We can add individual plant instances to the scene like this:
      // (However, this is inefficient for large amounts of plants.)
      _graphicsScreen.Scene.Children.Add(new MeshNode(palmMesh)
      {
        PoseLocal = new Pose(new Vector3(-2, 0, 0))
      });
      plantLodGroupNode.PoseLocal = Pose.Identity;
      _graphicsScreen.Scene.Children.Add(plantLodGroupNode);
      _graphicsScreen.Scene.Children.Add(new MeshNode(grassMesh)
      {
        PoseLocal = new Pose(new Vector3(2, 0, 0))
      });


      int numberOfInstancesPerCell = 100;
#else
      int numberOfInstancesPerCell = 10;


      // It is more efficient to group instances in batches and render them using mesh instancing.
      // This is handled by the VegetationObject class.
      GameObjectService.Objects.Add(new VegetationObject(Services, palmMesh, numberOfInstancesPerCell, 20, 10, 10, 1)
      {
        Name = "PalmTrees"
      });

      // The bird's nest plant has 2 LODs. We create two VegetationObjects. One displays the
      // detailed meshes near the camera. The second displays the low-poly meshes in the distance.
      var plantMeshLod0 = ((MeshNode)plantLodGroupNode.Levels[0].Node).Mesh;
      _meshes.Add(plantMeshLod0);
      GameObjectService.Objects.Add(new VegetationObject(Services, plantMeshLod0, numberOfInstancesPerCell, 20, 10, 10, 2)
      {
        Name = "PlantLOD0",
        MaxDistance = plantLodGroupNode.Levels[1].Distance,
      });

      var plantMeshLod1 = ((MeshNode)plantLodGroupNode.Levels[1].Node).Mesh;
      _meshes.Add(plantMeshLod1);
      GameObjectService.Objects.Add(new VegetationObject(Services, plantMeshLod1, numberOfInstancesPerCell, 20, 10, 10, 2)
      {
        Name = "PlantLOD1",
        MinDistance = plantLodGroupNode.Levels[1].Distance,
        MaxDistance = plantLodGroupNode.MaxDistance,
        CastsShadows = false,  // No shadows in the distance.
      });

      // Grass, lots of it...
      GameObjectService.Objects.Add(new VegetationObject(Services, grassMesh, numberOfInstancesPerCell * 10, 10, 20, 20, 3)
      {
        Name = "Grass",
        MaxDistance = 30,
        CastsShadows = false,
      });

      CreateGuiControls();
    }
Esempio n. 44
0
    public WaterSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;
      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics Simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      // More standard objects.
      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      //GameObjectService.Objects.Add(new StaticSkyObject(Services));
      var dynamicSkyObject = new DynamicSkyObject(Services, true, false, true);
      GameObjectService.Objects.Add(dynamicSkyObject);

      // Add a ground plane with some detail to see the water refractions.
      Simulation.RigidBodies.Add(new RigidBody(new PlaneShape(new Vector3F(0, 1, 0), 0)));
      GameObjectService.Objects.Add(new StaticObject(Services, "Gravel/Gravel", 1, new Pose(new Vector3F(0, 0.001f, 0))));

      GameObjectService.Objects.Add(new DudeObject(Services));
      GameObjectService.Objects.Add(new DynamicObject(Services, 1));
      GameObjectService.Objects.Add(new DynamicObject(Services, 2));
      GameObjectService.Objects.Add(new DynamicObject(Services, 5));
      GameObjectService.Objects.Add(new DynamicObject(Services, 6));
      GameObjectService.Objects.Add(new DynamicObject(Services, 7));
      GameObjectService.Objects.Add(new FogObject(Services) { AttachToCamera = true });

      // The LavaBalls class controls all lava ball instances.
      var lavaBalls = new LavaBallsObject(Services);
      GameObjectService.Objects.Add(lavaBalls);

      // Add a few palm trees.
      var random = new Random(12345);
      for (int i = 0; i < 10; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.5f, 1.2f);
        GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
      }

      // Define the appearance of the water.
      var water = new Water
      {
        SpecularColor = new Vector3F(10f),

        // Small water ripples/waves are created using scrolling normal maps.
        NormalMap0 = ContentManager.Load<Texture2D>("Water/Wave0"),
        NormalMap1 = ContentManager.Load<Texture2D>("Water/Wave1"),
        NormalMap0Scale = 1.8f,
        NormalMap1Scale = 2.2f,
        NormalMap0Velocity = new Vector3F(-0.02f, 0, 0.03f),
        NormalMap1Velocity = new Vector3F(0.02f, 0, -0.03f),
        NormalMap0Strength = 0.5f,
        NormalMap1Strength = 0.5f,

        ReflectionDistortion = 0.2f,
        ReflectionColor = new Vector3F(0.7f),
        RefractionDistortion = 0.05f,
      };

      // Create a box-shaped body of water.
      // We use a TransformedShape containing a BoxShape because the top of the 
      // water body must be at height 0.
      var shape = new TransformedShape(new GeometricObject(
        new BoxShape(10, 1, 20),
        new Pose(new Vector3F(0, -0.5f, 0))));
      _waterNode0 = new WaterNode(water, shape)
      {
        PoseWorld = new Pose(new Vector3F(-1, 0.5f, 0), Matrix33F.CreateRotationY(0.1f)),
        SkyboxReflection = _graphicsScreen.Scene.GetDescendants().OfType<SkyboxNode>().First(),
        DepthBufferWriteEnable = true,
      };
      _graphicsScreen.Scene.Children.Add(_waterNode0);

      // Optional: Create a WaterFlow to move the water using a flow texture.
      _waterFlow0 = new WaterFlow
      {
        FlowMapSpeed = 0.5f,
        FlowMap = GenerateFlowMap(),
        CycleDuration = 3f,
        NoiseMapStrength = 0.1f,
        NoiseMapScale = 0.5f,
      };
      _waterNode0.Flow = _waterFlow0;

      // Optional: Use a planar reflection instead of the skybox reflection.
      // We add a PlanarReflectionNode as a child of the WaterNode.
      var renderToTexture = new RenderToTexture
      {
        Texture = new RenderTarget2D(GraphicsService.GraphicsDevice, 512, 512, false, SurfaceFormat.HdrBlendable, DepthFormat.None),
      };
      var planarReflectionNode = new PlanarReflectionNode(renderToTexture)
      {
        // Same shape as WaterNode.
        Shape = _waterNode0.Shape,

        // Reflection plane is horizontal.
        NormalLocal = new Vector3F(0, 1, 0),
      };
      _waterNode0.PlanarReflection = planarReflectionNode;
      _waterNode0.Children = new SceneNodeCollection(1) { planarReflectionNode };

      // Create a short river with an inclined water surface.
      // Using a WaterFlow with a SurfaceSlopeSpeed, the water automatically flows
      // down the inclined surface.
      _waterNode1 = new WaterNode(water, GetSpiralShape())
      {
        PoseWorld = new Pose(new Vector3F(10, 1.5f, 0), Matrix33F.CreateRotationY(0.1f)),
        EnableUnderwaterEffect = false,
        SkyboxReflection = _graphicsScreen.Scene.GetDescendants().OfType<SkyboxNode>().First(),
        Flow = new WaterFlow
        {
          SurfaceSlopeSpeed = 0.5f,
          CycleDuration = 2f,
          NoiseMapStrength = 0.1f,
          NoiseMapScale = 1,
        }
      };
      _graphicsScreen.Scene.Children.Add(_waterNode1);
    }
Esempio n. 45
0
        public OceanSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;
            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics Simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            // More standard objects.
            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            //GameObjectService.Objects.Add(new StaticSkyObject(Services));
            var dynamicSkyObject = new DynamicSkyObject(Services, true, false, true);

            GameObjectService.Objects.Add(dynamicSkyObject);

            // Add an island model.
            GameObjectService.Objects.Add(new StaticObject(Services, "Island/Island", new Vector3F(30), new Pose(new Vector3F(0, 0.75f, 0)), true, true));

            GameObjectService.Objects.Add(new DynamicObject(Services, 1));
            GameObjectService.Objects.Add(new DynamicObject(Services, 2));
            GameObjectService.Objects.Add(new DynamicObject(Services, 5));
            GameObjectService.Objects.Add(new DynamicObject(Services, 6));
            GameObjectService.Objects.Add(new DynamicObject(Services, 7));
            GameObjectService.Objects.Add(new FogObject(Services)
            {
                AttachToCamera = true
            });

            // The LavaBalls class controls all lava ball instances.
            var lavaBalls = new LavaBallsObject(Services);

            GameObjectService.Objects.Add(lavaBalls);

            // Add a few palm trees.
            Random random = new Random(12345);

            for (int i = 0; i < 20; i++)
            {
                Vector3F  position    = new Vector3F(random.NextFloat(-7, 4), 0, random.NextFloat(13, 18));
                Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                float     scale       = random.NextFloat(0.8f, 1.2f);
                GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
            }

            // Define the appearance of the water.
            var waterOcean = new Water
            {
                SpecularColor = new Vector3F(20f),
                SpecularPower = 500,

                NormalMap0 = null,
                NormalMap1 = null,

                RefractionDistortion = 0.1f,
                ReflectionColor      = new Vector3F(0.2f),
                RefractionColor      = new Vector3F(0.6f),

                // Water is scattered in high waves and this makes the wave crests brighter.
                // ScatterColor defines the intensity of this effect.
                ScatterColor = new Vector3F(0.05f, 0.1f, 0.1f),

                // Foam is automatically rendered where the water intersects geometry and
                // where wave are high.
                FoamMap      = ContentManager.Load <Texture2D>("Water/Foam"),
                FoamMapScale = 5,
                FoamColor    = new Vector3F(1),
                FoamCrestMin = 0.3f,
                FoamCrestMax = 0.8f,

                // Approximate underwater caustics are computed in real-time from the waves.
                CausticsSampleCount = 3,
                CausticsIntensity   = 3,
                CausticsPower       = 100,
            };

            // If we do not specify a shape in the WaterNode constructor, we get an infinite
            // water plane.
            _waterNode = new WaterNode(waterOcean, null)
            {
                PoseWorld        = new Pose(new Vector3F(0, 0.5f, 0)),
                SkyboxReflection = _graphicsScreen.Scene.GetDescendants().OfType <SkyboxNode>().First(),

                // ExtraHeight must be set to a value greater than the max. wave height.
                ExtraHeight = 2,
            };
            _graphicsScreen.Scene.Children.Add(_waterNode);

            // OceanWaves can be set to displace water surface using a displacement map.
            // The displacement map is computed by the WaterWaveRenderer (see DeferredGraphicsScreen)
            // using FFT and a statistical ocean model.
            _waterNode.Waves = new OceanWaves
            {
                TextureSize    = 256,
                HeightScale    = 0.004f,
                Wind           = new Vector3F(10, 0, 10),
                Directionality = 1,
                Choppiness     = 1,
                TileSize       = 20,

                // If we enable CPU queries, we can call OceanWaves.GetDisplacement()
                // (see Update() method below).
                EnableCpuQueries = true,
            };

            // Optional: Use a planar reflection instead of the skybox reflection.
            // We add a PlanarReflectionNode as a child of the WaterNode.
            var renderToTexture = new RenderToTexture
            {
                Texture = new RenderTarget2D(GraphicsService.GraphicsDevice, 512, 512, false, SurfaceFormat.HdrBlendable, DepthFormat.None),
            };
            var planarReflectionNode = new PlanarReflectionNode(renderToTexture)
            {
                Shape       = _waterNode.Shape,
                NormalLocal = new Vector3F(0, 1, 0),
                IsEnabled   = false,
            };

            _waterNode.PlanarReflection = planarReflectionNode;
            _waterNode.Children         = new SceneNodeCollection(1)
            {
                planarReflectionNode
            };

            // To let rigid bodies swim, we add a Buoyancy force effect. This force effect
            // computes buoyancy of a flat water surface.
            Simulation.ForceEffects.Add(new Buoyancy
            {
                Surface     = new Plane(new Vector3F(0, 1, 0), _waterNode.PoseWorld.Position.Y),
                Density     = 1500,
                AngularDrag = 0.3f,
                LinearDrag  = 3,
            });
        }
        public CompositeShadowSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;
            _graphicsScreen = new DeferredGraphicsScreen(Services)
            {
                // For debugging: Disable materials and only show light buffer.
                DebugMode = DeferredGraphicsDebugMode.VisualizeDiffuseLightBuffer
            };
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);

            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            GameObjectService.Objects.Add(new GrabObject(Services));

            // Create test scene.
            ShadowSample.CreateScene(Services, ContentManager, _graphicsScreen);

            // Create 3 different shadows:
            // The VarianceShadow covers the whole level.
            _vsmShadow = new VarianceShadow
            {
                Prefer16Bit      = false,
                PreferredSize    = 512,
                MinLightDistance = 200,
                MaxDistance      = 200,
                FadeOutRange     = 0,
                ShadowFog        = 0,
                TargetArea       = new Aabb(new Vector3(-100, 0, -100), new Vector3(100, 50, 100))
            };
            _vsmShadow.Filter = new Blur(GraphicsService);
            _vsmShadow.Filter.NumberOfPasses = 1;
            _vsmShadow.Filter.InitializeGaussianBlur(11, 3, false);

            // The CascadedShadow for static objects.
            _staticCascadedShadow = new CascadedShadow
            {
                PreferredSize    = 1024,
                Prefer16Bit      = true,
                Distances        = new Vector4(4, 12, 20, 80),
                MinLightDistance = 200,
            };

            // The CascadedShadow for dynamic objects covering a smaller distance.
            _dynamicCascadedShadow = new CascadedShadow
            {
                PreferredSize    = 1024,
                Prefer16Bit      = true,
                NumberOfCascades = 2,
                Distances        = new Vector4(4, 12, 0, 0),
                MinLightDistance = 200,
            };

            // Get directional light created by the DynamicSkyObject and replace the default
            // shadow with our a CompositeShadow.
            _lightNode        = _graphicsScreen.Scene.GetDescendants().OfType <LightNode>().First(n => n.Shadow is CascadedShadow);
            _lightNode.Shadow = new CompositeShadow
            {
                Shadows =
                {
                    _vsmShadow,
                    _staticCascadedShadow,
                    _dynamicCascadedShadow,
                }
            };

            // We do not want to render the same objects into all 3 shadow maps. We use a custom
            // render callback to render each objects into only one of the shadow maps.
            _graphicsScreen.ShadowMapRenderer.RenderCallback = context =>
            {
                // Query all shadow casters.
                var query = context.Scene.Query <ShadowCasterQuery>(context.CameraNode, context);
                if (query.ShadowCasters.Count == 0)
                {
                    return(false);
                }

                // Get the shadow which is currently being rendered.
                var shadow = context.Object;

                // Create a list of scene nodes for the current shadow.
                var list = _tempList;
                if (shadow == _vsmShadow)
                {
                    // Get the hills and skyscrapers which have been marked with a user flag
                    // in ShadowSample.CreateScene.
                    foreach (var node in query.ShadowCasters)
                    {
                        if (node.UserFlags == 1)
                        {
                            _tempList.Add(node);
                        }
                    }
                }
                else if (shadow == _staticCascadedShadow)
                {
                    // Get all static objects except the hills/skyscrapers.
                    foreach (var node in query.ShadowCasters)
                    {
                        if (node.UserFlags == 0 && node.IsStatic)
                        {
                            _tempList.Add(node);
                        }
                    }
                }
                else if (shadow == _dynamicCascadedShadow)
                {
                    // Get all dynamic objects.
                    foreach (var node in query.ShadowCasters)
                    {
                        if (!node.IsStatic)
                        {
                            _tempList.Add(node);
                        }
                    }
                }
                else
                {
                    // Other shadows of other lights.
                    list = query.ShadowCasters;
                }

                // Render the selected objects into the shadow map.
                _graphicsScreen.MeshRenderer.Render(list, context);

                _tempList.Clear();
                return(true);
            };

            // Register the custom renderers for the VarianceShadow.
            _graphicsScreen.ShadowMapRenderer.Renderers.Add(new VarianceShadowMapRenderer(_graphicsScreen.ShadowMapRenderer.RenderCallback));
            _graphicsScreen.ShadowMaskRenderer.Renderers.Add(new VarianceShadowMaskRenderer(GraphicsService));

            CreateGuiControls();
        }
        public DeferredLightingSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);

            // Add a game object which adds some GUI controls for the deferred graphics
            // screen to the Options window.
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new StaticSkyObject(Services)); // Skybox + some lights.
            GameObjectService.Objects.Add(new GroundObject(Services));

            // Add a god ray post-process filter and a game object which updates the god ray directions.
            var godRayFilter = new GodRayFilter(GraphicsService)
            {
                Intensity       = new Vector3F(1.0f),
                NumberOfSamples = 12,
                NumberOfPasses  = 2,
                Softness        = 1,
            };

            _graphicsScreen.PostProcessors.Add(godRayFilter);
            GameObjectService.Objects.Add(new GodRayObject(Services, godRayFilter));

            GameObjectService.Objects.Add(new DudeObject(Services));
            GameObjectService.Objects.Add(new DynamicObject(Services, 1));
            GameObjectService.Objects.Add(new DynamicObject(Services, 2));
            GameObjectService.Objects.Add(new DynamicObject(Services, 3));
            GameObjectService.Objects.Add(new DynamicObject(Services, 4));
            GameObjectService.Objects.Add(new DynamicObject(Services, 5));
            GameObjectService.Objects.Add(new DynamicObject(Services, 6));
            GameObjectService.Objects.Add(new DynamicObject(Services, 7));
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            GameObjectService.Objects.Add(new FogObject(Services));
            GameObjectService.Objects.Add(new CampfireObject(Services));

            // The LavaBalls class controls all lava ball instances.
            var lavaBalls = new LavaBallsObject(Services);

            GameObjectService.Objects.Add(lavaBalls);

            // Create a lava ball instance.
            lavaBalls.Spawn();

            // Add a few palm trees.
            Random random = new Random(12345);

            for (int i = 0; i < 10; i++)
            {
                Vector3F  position    = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
                Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                float     scale       = random.NextFloat(0.5f, 1.2f);
                GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
            }
        }
Esempio n. 48
0
    public EnvironmentLightSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics Simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new GroundObject(Services));
      GameObjectService.Objects.Add(new DudeObject(Services));
      var lavaBallsObject = new LavaBallsObject(Services);
      GameObjectService.Objects.Add(lavaBallsObject);
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new FogObject(Services));
      GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Barrier", 0.9f, new Pose(new Vector3F(0, 0, -2))));
      GameObjectService.Objects.Add(new StaticObject(Services, "Barrier/Cylinder", 0.9f, new Pose(new Vector3F(3, 0, 0), QuaternionF.CreateRotationY(MathHelper.ToRadians(-20)))));
      GameObjectService.Objects.Add(new StaticSkyObject(Services));

      // Add a few palm trees.
      Random random = new Random(12345);
      for (int i = 0; i < 10; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.5f, 1.2f);
        GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
      }

      // Add some more dynamic objects.
      for (int i = 0; i < 5; i++)
      {
        lavaBallsObject.Spawn();
        GameObjectService.Objects.Add(new ProceduralObject(Services));
        GameObjectService.Objects.Add(new DynamicObject(Services, 7));
      }

      // To show the effect of the EnvironmentLight in isolation, disable all other light sources.
      //foreach (var light in _graphicsScreen.Scene.GetDescendants().OfType<LightNode>())
      //  light.IsEnabled = false;

      // Add the environment light.
      var environmentLight = new EnvironmentLight
      {
        Color = new Vector3F(0.1f),
        DiffuseIntensity = 0,
        SpecularIntensity = 1,
        EnvironmentMap = ContentManager.Load<TextureCube>("Sky2"),
      };
      var environmentLightNode = new LightNode(environmentLight)
      {
        Name = "Environment",
      };
      _graphicsScreen.Scene.Children.Add(environmentLightNode);

      // The EnvironmentLight is a new light type. We have to register a light renderer
      // for this light in the LightRenderer of the DeferredGraphicsScreen.
      _graphicsScreen.LightBufferRenderer.LightRenderer.Renderers.Add(new EnvironmentLightRenderer(GraphicsService));

      // EnvironmentLight.fx uses the specular power of the materials to determine
      // which mip map level of the cube is reflected. 
      // In reality, a high specular power is necessary to reflect the cube map
      // with all its detail. To reflect a cube map level with 512 texels size, we 
      // need a specular power of ~200000.
      // To make the reflection effects more obvious, let's change some material properties
      // and make the more reflective.

      // ProceduralObject:
      var proceduralObjects = _graphicsScreen.Scene
                                             .GetDescendants()
                                             .OfType<MeshNode>()
                                             .Where(mn => mn.Mesh.Name == "ProceduralObject")
                                             .Select(mn => mn.Mesh);
      foreach (var mesh in proceduralObjects)
      {
        foreach (var material in mesh.Materials)
        {
          material["GBuffer"].Set("SpecularPower", 10000f);
          material["Material"].Set("DiffuseColor", new Vector3(0.01f));
          material["Material"].Set("SpecularColor", new Vector3(1));
        }
      }

      // Frame of GlassBox:
      var glassBoxes = _graphicsScreen.Scene
                                      .GetDescendants()
                                      .OfType<ModelNode>()
                                      .Where(mn => mn.Name == "GlassBox")
                                      .Select(mn => ((MeshNode)mn.Children[0]).Mesh);
      foreach (var mesh in glassBoxes)
      {
        foreach (var material in mesh.Materials.Where(m => m.Contains("GBuffer")))
        {
          material["GBuffer"].Set("SpecularPower", 100000f);
          material["Material"].Set("DiffuseColor", new Vector3(0.0f));
          material["Material"].Set("SpecularColor", new Vector3(1));
        }
      }

      // LavaBall:
      var lavaBalls = _graphicsScreen.Scene
                                     .GetDescendants()
                                     .OfType<ModelNode>()
                                     .Where(mn => mn.Name == "LavaBall")
                                     .Select(mn => ((MeshNode)mn.Children[0]).Mesh);
      foreach (var mesh in lavaBalls)
      {
        foreach (var material in mesh.Materials.Where(m => m.Contains("GBuffer")))
        {
          material["GBuffer"].Set("SpecularPower", 10000f);
          material["Material"].Set("DiffuseColor", new Vector3(0.0f));
          material["Material"].Set("SpecularColor", new Vector3(10));
          material["Material"].Set("EmissiveColor", new Vector3(0.0f));
        }
      }

      // Ground plane:
      var groundPlanes = _graphicsScreen.Scene
                                        .GetDescendants()
                                        .OfType<ModelNode>()
                                        .Where(mn => mn.Name == "Ground")
                                        .Select(mn => ((MeshNode)mn.Children[0]).Mesh);
      foreach (var mesh in groundPlanes)
      {
        foreach (var material in mesh.Materials.Where(m => m.Contains("GBuffer")))
        {
          material["GBuffer"].Set("SpecularPower", 200000.0f);
          material["Material"].Set("DiffuseColor", new Vector3(0.5f));
          material["Material"].Set("SpecularColor", new Vector3(0.4f));
        }
      }

      // Please note, XNA does not filter cube maps over cube map borders. Therefore, reflections
      // of low resolution mip map levels might show obvious borders between the cube map
      // sides. In this case you can change the EnvironmentLight.fx effect to always reflect
      // the mip map level 0.
      // This is not a problem with MonoGame because DirectX automatically filters cube map borders.
    }
Esempio n. 49
0
        public LightClipSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;
            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true));
            GameObjectService.Objects.Add(new GroundObject(Services));

            GameObjectService.Objects.Add(new DudeObject(Services));
            GameObjectService.Objects.Add(new DynamicObject(Services, 1));
            GameObjectService.Objects.Add(new DynamicObject(Services, 2));
            GameObjectService.Objects.Add(new DynamicObject(Services, 3));
            GameObjectService.Objects.Add(new DynamicObject(Services, 4));
            GameObjectService.Objects.Add(new DynamicObject(Services, 6));
            GameObjectService.Objects.Add(new DynamicObject(Services, 7));
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            GameObjectService.Objects.Add(new FogObject(Services));

            // The LavaBalls class controls all lava ball instances.
            var lavaBalls = new LavaBallsObject(Services);

            GameObjectService.Objects.Add(lavaBalls);

            // Create a lava ball instance.
            lavaBalls.Spawn();

            // Add a few palm trees.
            Random random = new Random(12345);

            for (int i = 0; i < 10; i++)
            {
                Vector3 position    = new Vector3(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
                Matrix  orientation = Matrix.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                float   scale       = random.NextFloat(0.5f, 1.2f);
                GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
            }

            var boxShape       = new BoxShape(3, 3, 3);
            var compositeShape = new CompositeShape
            {
                Children =
                {
                    new GeometricObject(boxShape, new Pose(new Vector3(-2, 1.4f, 0))),
                    new GeometricObject(boxShape, new Pose(new Vector3(2,  1.4f, 0))),
                }
            };

            _clip = new GeometricObject(compositeShape, Pose.Identity);

            foreach (var lightNode in _graphicsScreen.Scene.GetDescendants().OfType <LightNode>())
            {
                lightNode.Clip = _clip;
                //lightNode.InvertClip = true;
            }
        }
Esempio n. 50
0
    public DistortionSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;
      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new StaticSkyObject(Services)); // Skybox + some lights.

      //GameObjectService.Objects.Add(new GroundObject(Services));
      // Add a ground plane with some detail to see the water refractions.
      Simulation.RigidBodies.Add(new RigidBody(new PlaneShape(new Vector3F(0, 1, 0), 0)));
      GameObjectService.Objects.Add(new StaticObject(Services, "Gravel/Gravel", 1, new Pose(new Vector3F(0, 0.001f, 0))));

      GameObjectService.Objects.Add(new DudeObject(Services));
      GameObjectService.Objects.Add(new DynamicObject(Services, 1));
      GameObjectService.Objects.Add(new DynamicObject(Services, 2));
      GameObjectService.Objects.Add(new DynamicObject(Services, 3));
      GameObjectService.Objects.Add(new DynamicObject(Services, 5));
      GameObjectService.Objects.Add(new DynamicObject(Services, 6));
      GameObjectService.Objects.Add(new DynamicObject(Services, 7));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new FogObject(Services));
      GameObjectService.Objects.Add(new CampfireObject(Services));
      GameObjectService.Objects.Add(new LavaBallsObject(Services));

      // Add a few palm trees.
      Random random = new Random(12345);
      for (int i = 0; i < 10; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.5f, 1.2f);
        GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
      }

      // Add DistortionFilter to post-processors.
      _distortionFilter = new DistortionFilter(GraphicsService, ContentManager);
      _graphicsScreen.PostProcessors.Add(_distortionFilter);

      // Add 3 particle systems. 
      // The ParticleSystems are added to the IParticleSystemService.
      // The ParticleSystemNodes are added to the Scene of the DistortionFilter - not the usual Scene!
      _fireDistortionParticleSystemNode = new ParticleSystemNode(CreateFireDistortionParticleSystem())
      {
        PoseLocal = new Pose(new Vector3F(0, 0f, -1), Matrix33F.CreateRotationX(ConstantsF.PiOver2)),
      };
      ParticleSystemService.ParticleSystems.Add(_fireDistortionParticleSystemNode.ParticleSystem);
      _distortionFilter.Scene.Children.Add(_fireDistortionParticleSystemNode);

      _explosionDistortionParticleSystemNode = new ParticleSystemNode(CreateExplosionDistortionParticleSystem())
      {
        PoseLocal = new Pose(new Vector3F(0, 0, -1)),
      };
      ParticleSystemService.ParticleSystems.Add(_explosionDistortionParticleSystemNode.ParticleSystem);
      _distortionFilter.Scene.Children.Add(_explosionDistortionParticleSystemNode);

      _novaDistortionParticleSystemNode = new ParticleSystemNode(CreateNovaDistortionParticleSystem())
      {
        PoseLocal = new Pose(new Vector3F(0, 0.5f, -1), Matrix33F.CreateRotationX(ConstantsF.PiOver2)),
      };
      ParticleSystemService.ParticleSystems.Add(_novaDistortionParticleSystemNode.ParticleSystem);
      _distortionFilter.Scene.Children.Add(_novaDistortionParticleSystemNode);
    }
Esempio n. 51
0
        public ParallaxTerrainSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);

            var scene = _graphicsScreen.Scene;

            Services.Register(typeof(IScene), null, scene);

            // Add standard game objects.
            var cameraGameObject = new CameraObject(Services, 5000);

            cameraGameObject.ResetPose(new Vector3(0, 2, 0), 0, 0);
            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());
            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true)
            {
                EnableCloudShadows = false,
            });
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));

            // Create terrain.
            _terrainObject = new TerrainObject(Services);
            GameObjectService.Objects.Add(_terrainObject);

            // To see parallax occlusion mapping, we need a detail texture with a height map.
            // In this sample we reuse the pavement texture of the ParallaxMappingSample and
            // add it to the terrain.
            for (int row = 0; row < 2; row++)
            {
                for (int column = 0; column < 2; column++)
                {
                    var    terrainTile = _terrainObject.TerrainNode.Terrain.Tiles[row * 2 + column];
                    string tilePostfix = "-" + row + "-" + column; // e.g. "-0-1"

                    var materialPavement = new TerrainMaterialLayer(GraphicsService)
                    {
                        DiffuseColor         = new Vector3(1),
                        SpecularColor        = new Vector3(5),
                        SpecularPower        = 20,
                        DiffuseTexture       = ContentManager.Load <Texture2D>("Parallax/AgedPavement_diffuse"),
                        NormalTexture        = ContentManager.Load <Texture2D>("Parallax/AgedPavement_normal"),
                        SpecularTexture      = ContentManager.Load <Texture2D>("Parallax/AgedPavement_specular"),
                        HeightTexture        = ContentManager.Load <Texture2D>("Parallax/AgedPavement_height"),
                        TileSize             = 0.005f * 512,
                        BlendTexture         = ContentManager.Load <Texture2D>("Terrain/Terrain001-Blend-Grass" + tilePostfix),
                        BlendTextureChannel  = 0,
                        BlendHeightInfluence = 0.5f,
                        BlendThreshold       = 0.5f,
                        BlendRange           = 0.5f,
                    };

                    terrainTile.Layers.Add(materialPavement);
                }
            }

            // Replace the terrain effects with effects which support parallax occlusion mapping.
            UpdateTerrainMaterial(true);

            CreateGuiControls();
        }
Esempio n. 52
0
        public FogSphereSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            // Create a graphics screen. This screen has to call the FogSphereRenderer
            // to handle the FogSphereNode!
            _graphicsScreen = new DeferredGraphicsScreen(Services)
            {
                DrawReticle = true
            };
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics Simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            // More standard objects.
            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true));
            GameObjectService.Objects.Add(new GroundObject(Services));
            GameObjectService.Objects.Add(new DudeObject(Services));
            GameObjectService.Objects.Add(new DynamicObject(Services, 1));
            GameObjectService.Objects.Add(new DynamicObject(Services, 2));
            GameObjectService.Objects.Add(new DynamicObject(Services, 5));
            GameObjectService.Objects.Add(new DynamicObject(Services, 6));
            GameObjectService.Objects.Add(new DynamicObject(Services, 7));
            GameObjectService.Objects.Add(new FogObject(Services));
            GameObjectService.Objects.Add(new LavaBallsObject(Services));

            // Add a few palm trees.
            Random random = new Random(12345);

            for (int i = 0; i < 10; i++)
            {
                Vector3 position    = new Vector3(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
                Matrix  orientation = Matrix.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                float   scale       = random.NextFloat(0.5f, 1.2f);
                GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
            }

            // ----- Add a FogSphereNode to scene.
            var fogSphereNode = new FogSphereNode
            {
                Name       = "FogSphere",
                ScaleLocal = new Vector3(5, 3, 5),
                PoseWorld  = new Pose(new Vector3(0, 0, -3)),
            };

            _graphicsScreen.Scene.Children.Add(fogSphereNode);
        }
Esempio n. 53
0
        public RefractionSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics Simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            GameObjectService.Objects.Add(new GrabObject(Services));
            GameObjectService.Objects.Add(new GroundObject(Services));
            var lavaBallsObject = new LavaBallsObject(Services);

            GameObjectService.Objects.Add(lavaBallsObject);
            GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
            GameObjectService.Objects.Add(new FogObject(Services));
            GameObjectService.Objects.Add(new StaticSkyObject(Services));
            GameObjectService.Objects.Add(new CampfireObject(Services));
            for (int i = 0; i < 10; i++)
            {
                GameObjectService.Objects.Add(new DynamicObject(Services, 1));
                GameObjectService.Objects.Add(new DynamicObject(Services, 2));
                GameObjectService.Objects.Add(new DynamicObject(Services, 3));
            }

            // Add a few palm trees.
            Random random = new Random(12345);

            for (int i = 0; i < 10; i++)
            {
                Vector3F  position    = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
                Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                float     scale       = random.NextFloat(0.5f, 1.2f);
                GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
            }

            // Add a few dudes which use the refraction effect.
            for (int i = 0; i < 5; i++)
            {
                Vector3F  position    = new Vector3F(random.NextFloat(-4, 4), 0, random.NextFloat(2, -5));
                Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
                var       dudeObject  = new DudeObject(Services, "DudeRefracted/Dude")
                {
                    Pose = new Pose(position, orientation)
                };
                GameObjectService.Objects.Add(dudeObject);
                //dudeObject.AnimationController.Pause();
            }

            // The DeferredGraphicsScreen has a SceneRenderer, which contains all
            // renderers necessary to render transparent objects (e.g. BillboardRenderer
            // for particles, MeshRenderer for meshes, etc.).
            // We remove the MeshRenderer and add our own RefractionMeshRenderer instead.
            var meshRenderer = _graphicsScreen.AlphaBlendSceneRenderer.Renderers.OfType <MeshRenderer>().First();

            _graphicsScreen.AlphaBlendSceneRenderer.Renderers.Remove(meshRenderer);
            _graphicsScreen.AlphaBlendSceneRenderer.Renderers.Add(new RefractionMeshRenderer(GraphicsService));
        }
        public TerrainTextureSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            _graphicsScreen             = new DeferredGraphicsScreen(Services);
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);

            var scene = _graphicsScreen.Scene;

            Services.Register(typeof(IScene), null, scene);

            // Add gravity and damping to the physics simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services, 60);

            cameraGameObject.ResetPose(new Vector3F(0, 1.8f, 0), 0, 0);
            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            for (int i = 0; i < 10; i++)
            {
                GameObjectService.Objects.Add(new DynamicObject(Services, 1));
            }

            GameObjectService.Objects.Add(new DynamicSkyObject(Services, true, false, true));

            // Create a simple flat terrain.
            var terrain = new Terrain();

            _terrainTile = new TerrainTile(GraphicsService)
            {
                OriginX  = -100,
                OriginZ  = -100,
                CellSize = 1,
            };
            terrain.Tiles.Add(_terrainTile);

            // Create a flat dummy height texture.
            float[]   heights       = new float[200 * 200];
            Texture2D heightTexture = null;

            TerrainHelper.CreateHeightTexture(
                GraphicsService.GraphicsDevice,
                heights,
                200,
                200,
                false,
                ref heightTexture);
            _terrainTile.HeightTexture = heightTexture;

            var shadowMapEffect = ContentManager.Load <Effect>("DigitalRune/Terrain/TerrainShadowMap");
            var gBufferEffect   = ContentManager.Load <Effect>("DigitalRune/Terrain/TerrainGBuffer");
            var materialEffect  = ContentManager.Load <Effect>("DigitalRune/Terrain/TerrainMaterial");
            var material        = new Material
            {
                { "ShadowMap", new EffectBinding(GraphicsService, shadowMapEffect, null, EffectParameterHint.Material) },
                { "GBuffer", new EffectBinding(GraphicsService, gBufferEffect, null, EffectParameterHint.Material) },
                { "Material", new EffectBinding(GraphicsService, materialEffect, null, EffectParameterHint.Material) }
            };
            var terrainNode = new TerrainNode(terrain, material)
            {
                DetailClipmap =
                {
                    CellsPerLevel  = 1364,
                    NumberOfLevels =    9,
                    EnableMipMap   = true,
                },
            };

            scene.Children.Add(terrainNode);

            // Add 3 detail textures layers: gravel, rock, snow.
            float detailCellSize = terrainNode.DetailClipmap.CellSizes[0];
            var   materialGravel = new TerrainMaterialLayer(GraphicsService)
            {
                DiffuseTexture  = ContentManager.Load <Texture2D>("Terrain/Gravel-Diffuse"),
                NormalTexture   = ContentManager.Load <Texture2D>("Terrain/Gravel-Normal"),
                SpecularTexture = ContentManager.Load <Texture2D>("Terrain/Gravel-Specular"),
                TileSize        = detailCellSize * 512,
                BlendRange      = 0.1f,
            };

            _terrainTile.Layers.Add(materialGravel);

            var noiseTexture = NoiseHelper.GetNoiseTexture(GraphicsService, 128, 60);

            var materialRock = new TerrainMaterialLayer(GraphicsService)
            {
                DiffuseTexture          = ContentManager.Load <Texture2D>("Terrain/Rock-02-Diffuse"),
                NormalTexture           = ContentManager.Load <Texture2D>("Terrain/Rock-02-Normal"),
                SpecularTexture         = ContentManager.Load <Texture2D>("Terrain/Rock-02-Specular"),
                HeightTexture           = ContentManager.Load <Texture2D>("Terrain/Rock-02-Height"),
                TileSize                = detailCellSize * 1024,
                DiffuseColor            = new Vector3F(1 / 0.702f),
                BlendTexture            = noiseTexture,
                BlendTextureChannel     = 0,
                BlendRange              = 0.1f,
                TerrainHeightBlendRange = 0.1f,
            };

            _terrainTile.Layers.Add(materialRock);

            var materialSnow = new TerrainMaterialLayer(GraphicsService)
            {
                DiffuseTexture      = ContentManager.Load <Texture2D>("Terrain/Snow-Diffuse"),
                NormalTexture       = ContentManager.Load <Texture2D>("Terrain/Snow-Normal"),
                SpecularTexture     = ContentManager.Load <Texture2D>("Terrain/Snow-Specular"),
                TileSize            = detailCellSize * 512,
                BlendTexture        = noiseTexture,
                BlendTextureChannel = 1,
                BlendRange          = 0.1f,
            };

            _terrainTile.Layers.Add(materialSnow);

            // Create a flat plane for collision detection.
            var rigidBody = new RigidBody(new PlaneShape(), new MassFrame(), null)
            {
                MotionType = MotionType.Static,
            };

            Simulation.RigidBodies.Add(rigidBody);

            CreateGuiControls();
        }
Esempio n. 55
0
    // Creates a test scene with a lot of randomly placed objects.
    internal static void CreateScene(ServiceContainer services, ContentManager content, DeferredGraphicsScreen graphicsScreen)
    {
      var gameObjectService = services.GetInstance<IGameObjectService>();
      var graphicsService = services.GetInstance<IGraphicsService>();

      gameObjectService.Objects.Add(new DynamicSkyObject(services, true, false, true)
      {
        EnableAmbientLight = false, // Disable ambient light of sky to make shadows more visible.
        EnableCloudShadows = false
      });

      gameObjectService.Objects.Add(new GroundObject(services));
      gameObjectService.Objects.Add(new DynamicObject(services, 1));
      gameObjectService.Objects.Add(new DynamicObject(services, 2));
      gameObjectService.Objects.Add(new DynamicObject(services, 3));
      gameObjectService.Objects.Add(new DynamicObject(services, 5));
      gameObjectService.Objects.Add(new DynamicObject(services, 6));
      gameObjectService.Objects.Add(new DynamicObject(services, 7));
      gameObjectService.Objects.Add(new ObjectCreatorObject(services));
      gameObjectService.Objects.Add(new LavaBallsObject(services));

      var random = new Random();

      // Spheres
      var sphereMesh = SampleHelper.CreateMesh(content, graphicsService, new SphereShape(1));
      for (int i = 0; i < 100; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-100, 100), random.NextFloat(0, 3), random.NextFloat(-100, 100));
        float scale = random.NextFloat(0.5f, 3f);
        var meshNode = new MeshNode(sphereMesh)
        {
          PoseLocal = new Pose(position),
          ScaleLocal = new Vector3F(scale),
          IsStatic = true,
        };
        graphicsScreen.Scene.Children.Add(meshNode);
      }

      // Boxes
      var boxMesh = SampleHelper.CreateMesh(content, graphicsService, new BoxShape(1, 1, 1));
      for (int i = 0; i < 100; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-100, 100), random.NextFloat(0, 3), random.NextFloat(-100, 100));
        QuaternionF orientation = random.NextQuaternionF();
        Vector3F scale = random.NextVector3F(0.1f, 4f);
        var meshNode = new MeshNode(boxMesh)
        {
          PoseLocal = new Pose(position, orientation),
          ScaleLocal = scale,
          IsStatic = true,
        };
        graphicsScreen.Scene.Children.Add(meshNode);
      }

      // Height field with smooth hills.
      var numberOfSamplesX = 20;
      var numberOfSamplesZ = 20;
      var samples = new float[numberOfSamplesX * numberOfSamplesZ];
      for (int z = 0; z < numberOfSamplesZ; z++)
      {
        for (int x = 0; x < numberOfSamplesX; x++)
        {
          if (x == 0 || z == 0 || x == 19 || z == 19)
          {
            // Set this boundary elements to a low height, so that the height field is connected
            // to the ground.
            samples[z * numberOfSamplesX + x] = -1;
          }
          else
          {
            // A sine/cosine function that creates some interesting waves.
            samples[z * numberOfSamplesX + x] = 1 + (float)(Math.Cos(z / 2f) * Math.Sin(x / 2f) * 1);
          }
        }
      }
      var heightField = new HeightField(0, 0, 20, 20, samples, numberOfSamplesX, numberOfSamplesZ);
      var heightFieldMesh = SampleHelper.CreateMesh(content, graphicsService, heightField);
      var heightFieldMeshNode = new MeshNode(heightFieldMesh)
      {
        PoseLocal = new Pose(new Vector3F(20, 0, -20)),
        ScaleLocal = new Vector3F(1, 2, 1),
        IsStatic = true,
      };
      graphicsScreen.Scene.Children.Add(heightFieldMeshNode);

      // Dudes.
      for (int i = 0; i < 10; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-20, 20), 0, random.NextFloat(-20, 20));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        gameObjectService.Objects.Add(new DudeObject(services) { Pose = new Pose(position, orientation) });
      }

      // Palm trees.
      for (int i = 0; i < 100; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-80, 80), 0, random.NextFloat(-100, 100));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.5f, 1.2f);
        gameObjectService.Objects.Add(new StaticObject(services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
      }

      // Rocks
      for (int i = 0; i < 100; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-80, 80), 1, random.NextFloat(-100, 100));
        QuaternionF orientation = RandomHelper.Random.NextQuaternionF();
        float scale = random.NextFloat(0.5f, 1.2f);
        gameObjectService.Objects.Add(new StaticObject(services, "Rock/rock_05", scale, new Pose(position, orientation)));
      }

      // Grass
      for (int i = 0; i < 100; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-20, 20), 0, random.NextFloat(-20, 20));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.5f, 1.2f);
        gameObjectService.Objects.Add(new StaticObject(services, "Grass/Grass", scale, new Pose(position, orientation)));
      }

      // More plants
      for (int i = 0; i < 100; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-20, 20), 0, random.NextFloat(-20, 20));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.5f, 1.2f);
        gameObjectService.Objects.Add(new StaticObject(services, "Parviflora/Parviflora", scale, new Pose(position, orientation)));
      }

      // "Skyscrapers"
      for (int i = 0; i < 20; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(90, 100), 0, random.NextFloat(-100, 100));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        Vector3F scale = new Vector3F(random.NextFloat(6, 20), random.NextFloat(10, 100), random.NextFloat(6, 20));
        var meshNode = new MeshNode(boxMesh)
        {
          PoseLocal = new Pose(position, orientation),
          ScaleLocal = scale,
          IsStatic = true,
          UserFlags = 1, // Mark the distant huge objects. Used in render callbacks in the CompositeShadowSample.
        };
        graphicsScreen.Scene.Children.Add(meshNode);
      }

      // "Hills"
      for (int i = 0; i < 20; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-90, -100), 0, random.NextFloat(-100, 100));
        Vector3F scale = new Vector3F(random.NextFloat(10, 20), random.NextFloat(10, 30), random.NextFloat(10, 20));
        var meshNode = new MeshNode(sphereMesh)
        {
          PoseLocal = new Pose(position),
          ScaleLocal = scale,
          IsStatic = true,
          UserFlags = 1, // Mark the distant huge objects. Used in render callbacks in the CompositeShadowSample.
        };
        graphicsScreen.Scene.Children.Add(meshNode);
      }
    }
Esempio n. 56
0
    public ShadowSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;
      _graphicsScreen = new DeferredGraphicsScreen(Services)
      {
        // For debugging: Disable materials and only show light buffer.
        DebugMode = DeferredGraphicsDebugMode.VisualizeDiffuseLightBuffer
      };
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);

      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      GameObjectService.Objects.Add(new GrabObject(Services));

      CreateScene(Services, ContentManager, _graphicsScreen);

      // Disable existing lights.
      foreach (var lightNode in _graphicsScreen.Scene.GetDescendants().OfType<LightNode>())
        lightNode.IsEnabled = false;

      // Add a dim ambient light.
      _graphicsScreen.Scene.Children.Add(
        new LightNode(
          new AmbientLight
          {
            HemisphericAttenuation = 1,
            Intensity = 0.001f,
          }));

      // Add some test lights with shadows.
      _spotlight = new Spotlight { Range = 10, FalloffAngle = 0.8f, CutoffAngle = 1f };
      _standardShadow = new StandardShadow();
      _spotlightNode = new LightNode(_spotlight)
      {
        PoseWorld = new Pose(new Vector3F(0, 1f, -2)),
        Shadow = _standardShadow,
        IsEnabled = true,
      };
      _graphicsScreen.Scene.Children.Add(_spotlightNode);

      _cubeMapShadow = new CubeMapShadow();
      _pointLight = new PointLight { Range = 10, };
      _pointLightNode = new LightNode(_pointLight)
      {
        PoseWorld = new Pose(new Vector3F(0, 1f, -2)),
        Shadow = _cubeMapShadow,
        IsEnabled = false,
      };
      _graphicsScreen.Scene.Children.Add(_pointLightNode);

      CreateGuiControls();
    }
Esempio n. 57
0
    public DeferredLightingSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);

      // Add a game object which adds some GUI controls for the deferred graphics 
      // screen to the Options window.
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new StaticSkyObject(Services)); // Skybox + some lights.
      GameObjectService.Objects.Add(new GroundObject(Services));

      // Add a god ray post-process filter and a game object which updates the god ray directions.
      var godRayFilter = new GodRayFilter(GraphicsService)
      {
        Intensity = new Vector3F(1.0f),
        NumberOfSamples = 12,
        NumberOfPasses = 2,
        Softness = 1,
      };
      _graphicsScreen.PostProcessors.Add(godRayFilter);
      GameObjectService.Objects.Add(new GodRayObject(Services, godRayFilter));

      GameObjectService.Objects.Add(new DudeObject(Services));
      GameObjectService.Objects.Add(new DynamicObject(Services, 1));
      GameObjectService.Objects.Add(new DynamicObject(Services, 2));
      GameObjectService.Objects.Add(new DynamicObject(Services, 3));
      GameObjectService.Objects.Add(new DynamicObject(Services, 4));
      GameObjectService.Objects.Add(new DynamicObject(Services, 5));
      GameObjectService.Objects.Add(new DynamicObject(Services, 6));
      GameObjectService.Objects.Add(new DynamicObject(Services, 7));
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new FogObject(Services));
      GameObjectService.Objects.Add(new CampfireObject(Services));

      // The LavaBalls class controls all lava ball instances.
      var lavaBalls = new LavaBallsObject(Services);
      GameObjectService.Objects.Add(lavaBalls);

      // Create a lava ball instance.
      lavaBalls.Spawn();

      // Add a few palm trees.
      Random random = new Random(12345);
      for (int i = 0; i < 10; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.5f, 1.2f);
        GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
      }
    }
Esempio n. 58
0
    //--------------------------------------------------------------
    #region Methods
    //--------------------------------------------------------------

    protected override void OnLoad()
    {
      // Get common services and game objects.
      _graphicsService = _services.GetInstance<IGraphicsService>();
      _graphicsScreen = _graphicsService.Screens.OfType<DeferredGraphicsScreen>().First();
      var content = _services.GetInstance<ContentManager>();
      var scene = _services.GetInstance<IScene>();
      _simulation = _services.GetInstance<Simulation>();
      var gameObjectService = _services.GetInstance<IGameObjectService>();
      _cameraObject = gameObjectService.Objects.OfType<CameraObject>().First();
      _previousCameraFar = _cameraObject.CameraNode.Camera.Projection.Far;

      // Create a new terrain.
      var terrain = new Terrain();

      // The terrain is made up of terrain tiles which can be loaded independently. 
      // Each terrain tile consists of height and normal textures which define the terrain
      // geometry and terrain layers which define the material (detail textures).
      // In this sample we create 2x2 tiles.
      _tiles = new Tile[2, 2];
      for (int row = 0; row < 2; row++)
      {
        for (int column = 0; column < 2; column++)
        {
          // Create a tile and add it to the terrain.
          // (The tile content is loaded later.)
          var terrainTile = new TerrainTile(_graphicsService)
          {
            CellSize = 1,   // The terrain has a resolution of 1 height sample per world space unit.
          };
          terrain.Tiles.Add(terrainTile);

          // Create a rigid body with a height field for collision detection and add
          // it to the simulation. (The height data is loaded later.)
          var heightField = new HeightField
          {
            Depth = 1,
            UseFastCollisionApproximation = false,
          };
          var rigidBody = new RigidBody(heightField, new MassFrame(), null)
          {
            MotionType = MotionType.Static,
            UserData = terrainTile,
          };
          _simulation.RigidBodies.Add(rigidBody);

          // Store the tile for use later in this sample.
          _tiles[row, column] = new Tile
          {
            TerrainTile = terrainTile,
            RigidBody = rigidBody,
          };
        }
      }

      // Create a terrain node which represents the terrain in the scene graph.
      // The terrain node is rendered by the TerrainRenderer (see DeferredGraphicsScreen).
      // The material used to render the terrain is customizable.  The material must specify 
      // the effects for the different render passes which we use in the DeferredGraphicsScreen 
      // ("ShadowMap", "GBuffer", "Material").
      // The prebuilt DigitalRune content contains standard terrain effects. However, you could
      // change the effects to change how the material is rendered.
      // We can create the material by loading a .drmat file. Or we can create the material in
      // code like this:
      var shadowMapEffect = content.Load<Effect>("DigitalRune/Terrain/TerrainShadowMap");
      var gBufferEffect = content.Load<Effect>("DigitalRune/Terrain/TerrainGBuffer");
      var materialEffect = content.Load<Effect>("DigitalRune/Terrain/TerrainMaterial");
      var material = new Material
      {
        { "ShadowMap", new EffectBinding(_graphicsService, shadowMapEffect, null, EffectParameterHint.Material) },
        { "GBuffer", new EffectBinding(_graphicsService, gBufferEffect, null, EffectParameterHint.Material) },
        { "Material", new EffectBinding(_graphicsService, materialEffect, null, EffectParameterHint.Material) }
      };
      TerrainNode = new TerrainNode(terrain, material)
      {
        // The terrain rendering uses clipmaps.
        // The clipmaps are updated by the TerrainClipmapRenderer (see DeferredGraphicsScreen)
        // when the camera moves.
        // The base clipmap contains the basic geometry info (height, normals, hole info).
        // It also determines the terrain mesh resolution.
        BaseClipmap =
        {
          CellsPerLevel = 128,
          NumberOfLevels = 6
        },
        // The detail clipmap contains the splatted detail textures (e.g. grass, rock, ...).
        // (The max texture size in XNA is 4096x4096. That means we can fit 9 clipmap levels
        // into a single texture.)
        DetailClipmap =
        {
          CellsPerLevel = 1365,
          NumberOfLevels = 9,
        },
      };
      scene.Children.Add(TerrainNode);

      // Load the height and normal maps which define the terrain geometry.
      InitializeHeightsAndNormals();

      // Set the clipmap cell sizes.
      InitializeClipmapCellSizes();

      // Create the terrain layers which define the detail textures (e.g. grass, rock, ...)
      InitializeTerrainLayers(content);

      // Special note for AMD GPUs:
      // If we want anisotropic filtering for the terrain, then we need to enable mipmaps for
      // AMD GPUs. NVIDIA and Intel can do anisotropic filtering without mipmaps.
      //TerrainNode.DetailClipmap.EnableMipMap = true;

      CreateGuiControls();
    }
Esempio n. 59
0
        public ShadowSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;
            _graphicsScreen = new DeferredGraphicsScreen(Services)
            {
                // For debugging: Disable materials and only show light buffer.
                DebugMode = DeferredGraphicsDebugMode.VisualizeDiffuseLightBuffer
            };
            _graphicsScreen.DrawReticle = true;
            GraphicsService.Screens.Insert(0, _graphicsScreen);

            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add gravity and damping to the physics simulation.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Add a custom game object which controls the camera.
            var cameraGameObject = new CameraObject(Services);

            GameObjectService.Objects.Add(cameraGameObject);
            _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

            GameObjectService.Objects.Add(new GrabObject(Services));

            CreateScene(Services, ContentManager, _graphicsScreen);

            // Disable existing lights.
            foreach (var lightNode in _graphicsScreen.Scene.GetDescendants().OfType <LightNode>())
            {
                lightNode.IsEnabled = false;
            }

            // Add a dim ambient light.
            _graphicsScreen.Scene.Children.Add(
                new LightNode(
                    new AmbientLight
            {
                HemisphericAttenuation = 1,
                Intensity = 0.001f,
            }));

            // Add some test lights with shadows.
            _spotlight = new Spotlight {
                Range = 10, FalloffAngle = 0.8f, CutoffAngle = 1f
            };
            _standardShadow = new StandardShadow();
            _spotlightNode  = new LightNode(_spotlight)
            {
                PoseWorld = new Pose(new Vector3(0, 1f, -2)),
                Shadow    = _standardShadow,
                IsEnabled = true,
            };
            _graphicsScreen.Scene.Children.Add(_spotlightNode);

            _cubeMapShadow = new CubeMapShadow();
            _pointLight    = new PointLight {
                Range = 10,
            };
            _pointLightNode = new LightNode(_pointLight)
            {
                PoseWorld = new Pose(new Vector3(0, 1f, -2)),
                Shadow    = _cubeMapShadow,
                IsEnabled = false,
            };
            _graphicsScreen.Scene.Children.Add(_pointLightNode);

            CreateGuiControls();
        }
Esempio n. 60
0
    public RefractionSample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;

      _graphicsScreen = new DeferredGraphicsScreen(Services);
      _graphicsScreen.DrawReticle = true;
      GraphicsService.Screens.Insert(0, _graphicsScreen);
      GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

      Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
      Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

      // Add gravity and damping to the physics Simulation.
      Simulation.ForceEffects.Add(new Gravity());
      Simulation.ForceEffects.Add(new Damping());

      // Add a custom game object which controls the camera.
      var cameraGameObject = new CameraObject(Services);
      GameObjectService.Objects.Add(cameraGameObject);
      _graphicsScreen.ActiveCameraNode = cameraGameObject.CameraNode;

      GameObjectService.Objects.Add(new GrabObject(Services));
      GameObjectService.Objects.Add(new GroundObject(Services));
      var lavaBallsObject = new LavaBallsObject(Services);
      GameObjectService.Objects.Add(lavaBallsObject);
      GameObjectService.Objects.Add(new ObjectCreatorObject(Services));
      GameObjectService.Objects.Add(new FogObject(Services));
      GameObjectService.Objects.Add(new StaticSkyObject(Services));
      GameObjectService.Objects.Add(new CampfireObject(Services));
      for (int i = 0; i < 10; i++)
      {
        GameObjectService.Objects.Add(new DynamicObject(Services, 1));
        GameObjectService.Objects.Add(new DynamicObject(Services, 2));
        GameObjectService.Objects.Add(new DynamicObject(Services, 3));
      }

      // Add a few palm trees.
      Random random = new Random(12345);
      for (int i = 0; i < 10; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-3, -8), 0, random.NextFloat(0, -5));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.5f, 1.2f);
        GameObjectService.Objects.Add(new StaticObject(Services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
      }

      // Add a few dudes which use the refraction effect.
      for (int i = 0; i < 5; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-4, 4), 0, random.NextFloat(2, -5));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        var dudeObject = new DudeObject(Services, "DudeRefracted/Dude")
        {
          Pose = new Pose(position, orientation)
        };
        GameObjectService.Objects.Add(dudeObject);
        //dudeObject.AnimationController.Pause();
      }

      // The DeferredGraphicsScreen has a SceneRenderer, which contains all 
      // renderers necessary to render transparent objects (e.g. BillboardRenderer 
      // for particles, MeshRenderer for meshes, etc.).
      // We remove the MeshRenderer and add our own RefractionMeshRenderer instead.
      var meshRenderer = _graphicsScreen.AlphaBlendSceneRenderer.Renderers.OfType<MeshRenderer>().First();
      _graphicsScreen.AlphaBlendSceneRenderer.Renderers.Remove(meshRenderer);
      _graphicsScreen.AlphaBlendSceneRenderer.Renderers.Add(new RefractionMeshRenderer(GraphicsService));
    }