示例#1
0
文件: MyScene.cs 项目: noatom/Samples
        protected override void CreateScene()
        {
            //Dark background
            RenderManager.BackgroundColor = Color.Black;

            //Create the player character
            this.CreatePlayer();

            //Add the UI
            this.CreateUI();

            //Create the level
            this.CreateLevel();

            //Create the camera
            FreeCamera camera = new FreeCamera("freeCamera", new Vector3(0, 2f, -2.5f), Vector3.UnitY * 0.9f)
            {
                Speed = 5
            };
            camera.Entity.AddComponent(new CameraBehavior(EntityManager.Find("isis")));

            //Add some light!
            PointLight light = new PointLight("light", Vector3.Zero)
            {
                Attenuation = 75,
                Color = new Color(1, 0.6f, 0.4f),
                IsVisible = true
            };
            light.Entity.AddComponent(new FollowCameraBehavior(camera.Entity));
            light.Entity.AddComponent(new TorchLightBehaviour());

            EntityManager.Add(light);
            EntityManager.Add(camera);
            RenderManager.SetActiveCamera(camera.Entity);
        }
示例#2
0
文件: MyScene.cs 项目: noatom/Samples
        /// <summary>
        /// Creates the flare.
        /// </summary>
        /// <returns></returns>
        private void CreateSunFlare()
        {
            PointLight skylight = new PointLight("SkyLight", new Vector3(100, 0, 0))
            {
                Attenuation = 1000,
                Color = Color.White,
                IsVisible = true,
            };

            LensFlare flare = new LensFlare();

            flare.Flares = new FlareElement[]
            {
                new FlareElement(0, new Vector2(3), new Color(1f,  1f,  1f), "Content/flareTexture.wpk"),
                new FlareElement(0.2f, new Vector2(1), new Color(0.2f,  0.2f,  0.2f), "Content/flare5.wpk"),
                new FlareElement(0.5f, new Vector2(1), new Color(0.2f,  0.2f,  0.2f), "Content/flare3.wpk"),
                new FlareElement(0.8f, new Vector2(1), new Color(0.2f,  0.2f,  0.2f), "Content/flare4.wpk"),
                new FlareElement(1.2f, new Vector2(1), new Color(0.2f,  0.2f,  0.2f), "Content/flare2.wpk"),
                new FlareElement(1.5f, new Vector2(1), new Color(0.2f,  0.2f,  0.2f), "Content/flare1.wpk"),
            };

            skylight.LensFlare = flare;

            EntityManager.Add(skylight);
        }
        public ThumbnailLighting()
        {
            Model = new LocalDataSource();
            this.InitializeComponent();

            // Get the current compositor
            _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;


            //
            // Create the lights
            //

            _ambientLight = _compositor.CreateAmbientLight();
            _pointLight = _compositor.CreatePointLight();
            _distantLight = _compositor.CreateDistantLight();
            _spotLight = _compositor.CreateSpotLight();
        }
示例#4
0
        /// <summary>
        /// Creates the scene.
        /// </summary>
        /// <remarks>
        /// This method is called before all <see cref="T:WaveEngine.Framework.Entity" /> instances in this instance are initialized.
        /// </remarks>
        protected override void CreateScene()
        {
            RenderManager.BackgroundColor = Color.Black;
            RenderManager.DebugLines = false;
            RenderManager.RegisterLayerBefore(new SkyLayer(this.RenderManager), DefaultLayers.Alpha);

            FreeCamera camera = new FreeCamera("camera", new Vector3(-2.4f, 0, -3), new Vector3(-1.6f, 0, -2.5f))
            {
                Speed = 2,
                NearPlane = 0.1f
            };

            EntityManager.Add(camera.Entity);
            RenderManager.SetActiveCamera(camera.Entity);

            this.Sun = this.CreateSunFlare();

            this.Earth = this.CreatePlanet("Earth", Vector3.Zero, 1, 10, Vector3.Zero, 0);
            this.Moon = this.CreatePlanet("Moon", new Vector3(0, 0, 20), 1, 28, Vector3.Zero, 28);
        }
示例#5
0
        protected override void CreateScene()
        {
            //Create the player character
            this.CreatePlayer();

            //Add the UI
            this.CreateUI();

            //Create the level
            this.CreateLevel();

            //Create the camera
            FreeCamera camera = new FreeCamera("freeCamera", new Vector3(0, 2f, -2.5f), Vector3.UnitY * 0.9f)
            {
                Speed = 5,
                BackgroundColor = Color.Black,
            };
            camera.Entity.AddComponent(new CameraBehavior(EntityManager.Find("isis")));

            FixedCamera2D camera2D = new FixedCamera2D("camera2D")
            {
                ClearFlags = ClearFlags.DepthAndStencil
            };

            //Add some light!
            PointLight light = new PointLight("light", Vector3.Zero)
            {
                Attenuation = 75,
                Color = new Color(1, 0.6f, 0.4f),
                IsVisible = true
            };
            light.Entity.AddComponent(new FollowCameraBehavior(camera.Entity));
            light.Entity.AddComponent(new TorchLightBehaviour());

            EntityManager.Add(light);
            EntityManager.Add(camera);
            EntityManager.Add(camera2D);
        }
示例#6
0
        /// <summary>
        /// Actor class constructor.
        /// </summary>
        /// <param name="layer">Actor's layer</param>
        public Actor(Layer layer)
            : base(layer)
        {
            //Empties variables
            m_LastShip          = null;
            m_RotationX         = 0.0f;
            m_RotationY         = 0.0f;
            m_Movement	        = Vector3.Zero;
            m_SavedVelocity     = Vector3.Zero;
            m_SavedAcceleration = Vector3.Zero;

            //Initialize values
            m_Life      = 0;
            m_Jumping	= false;
            m_Forward	= new Vector3(0.0f, 0.0f, 1.0f);
            m_Sideway	= new Vector3(-1.0f, 0.0f, 0.0f);

            //Create light
            m_Light					= new PointLight();
            m_Light.Range			= 40.0f;
            m_Light.DiffuseColor	= new Vector3(1.0f, 1.0f, 1.0f);
            m_Light.SpecularColor	= new Vector3(0.3f, 0.3f, 0.3f);
        }
示例#7
0
 public void RemovePointLight(PointLight light)
 {
     PointLights[Buffer].Remove(light);
 }
 /// <summary>
 /// Create an ExpressionNode reference to this CompositionObject.
 /// </summary>
 /// <param name="compObj">The comp object.</param>
 /// <returns>PointLightReferenceNode.</returns>
 public static PointLightReferenceNode GetReference(this PointLight compObj)
 {
     return(new PointLightReferenceNode(null, compObj));
 }
示例#9
0
文件: frmMain.cs 项目: zulis/Sandbox
        private ObjectBase CreateObjectCopy(ObjectBase selectedObject)
        {
            Cursor tmpCursor = Cursor.Current;
            Cursor = Cursors.WaitCursor;

            if (selectedObject.GetType().Equals(typeof(Engine.Mesh)))
            {
                var mesh = new Engine.Mesh(core, Settings, selectedObject.FileName);
                mesh.IsAnimated = (selectedObject as Engine.Mesh).IsAnimated;
                mesh.CustomTexture = (selectedObject as Engine.Mesh).CustomTexture;
                mesh.Visible = selectedObject.Visible;
                mesh.Position = selectedObject.Position;
                mesh.Rotation = selectedObject.Rotation;
                mesh.Scale = selectedObject.Scale;
                mesh.Mass = (selectedObject as Engine.Mesh).Mass;
                mesh.Bounding = (selectedObject as Engine.Mesh).Bounding;
                mesh.KineticFriction = (selectedObject as Engine.Mesh).KineticFriction;
                mesh.StaticFriction = (selectedObject as Engine.Mesh).StaticFriction;
                mesh.Bounciness = (selectedObject as Engine.Mesh).Bounciness;
                mesh.Softness = (selectedObject as Engine.Mesh).Softness;
                mesh.Material = (selectedObject as Engine.Mesh).Material;
                mesh.EnableLightning = (selectedObject as Engine.Mesh).EnableLightning;
                mesh.SetCustomCollection((selectedObject as Engine.Mesh).CustomParams);
                mesh.TextureScale = (selectedObject as Engine.Mesh).TextureScale;
                mesh.ScriptEnabled = (selectedObject as Engine.Mesh).ScriptEnabled;
                mesh.Script = (selectedObject as Engine.Mesh).Script.Replace((selectedObject as Engine.Mesh).Name, mesh.Name);
                mesh.Update();
                AddToSceneTreeView(sceneObjectsNode, mesh);
                Cursor = tmpCursor;
                return mesh;
            }

            if (selectedObject.GetType().Equals(typeof(PointLight)))
            {
                VECTOR3D pos = selectedObject.Position;
                var pointLight = (PointLight)selectedObject;
                var light = new PointLight(core, new TV_3DVECTOR(pos.X, pos.Y, pos.Z));
                light.Color = pointLight.Color;
                light.Radius = pointLight.Radius;
                light.Visible = pointLight.Visible;
                light.SetCustomCollection(pointLight.CustomParams);
                light.Update();
                AddToSceneTreeView(sceneLightsNode, light);
                Cursor = tmpCursor;
                return light;
            }

            if (selectedObject.GetType().Equals(typeof(Sound)))
            {
                var sound = new Sound(core, selectedObject.FileName);
                sound.Position = selectedObject.Position;
                sound.Stopped = (selectedObject as Sound).Stopped;
                sound.Volume = (selectedObject as Sound).Volume;
                sound.Loop = (selectedObject as Sound).Loop;
                sound.Is3D = (selectedObject as Sound).Is3D;
                sound.SetCustomCollection((selectedObject as Sound).CustomParams);
                sound.Update();
                AddToSceneTreeView(sceneSoundsNode, sound);
                Cursor = tmpCursor;
                return sound;
            }

            if (selectedObject.GetType().Equals(typeof(Engine.Trigger)))
            {
                var trigger = new Engine.Trigger(core);
                trigger.Position = selectedObject.Position;
                trigger.Rotation = selectedObject.Rotation;
                trigger.Scale = selectedObject.Scale;
                trigger.Color = (selectedObject as Trigger).Color;
                trigger.SetCustomCollection((selectedObject as Engine.Trigger).CustomParams);
                trigger.Update();
                AddToSceneTreeView(sceneTriggersNode, trigger);
                Cursor = tmpCursor;
                return trigger;
            }

            if (selectedObject.GetType().Equals(typeof(Engine.Particle)))
            {
                var particle = new Engine.Particle(core, selectedObject.FileName);
                particle.Position = selectedObject.Position;
                particle.Rotation = selectedObject.Rotation;
                particle.Scale = selectedObject.Scale;
                particle.Visible = selectedObject.Visible;
                particle.SetCustomCollection((selectedObject as Engine.Particle).CustomParams);
                particle.Update();
                AddToSceneTreeView(sceneParticlesNode, particle);
                Cursor = tmpCursor;
                return particle;
            }

            return null;
        }
示例#10
0
        public static void RowTestByDelegate(int spp, string fileSuffix, Func <float, int, IMaterial> materialFunc)
        {
            var dx    = 3.65f;
            var nX    = 11;
            var delta = 1f / (nX - 1);
            var prims = new List <IPrimitive>();

            for (var x = 0; x < nX; x++)
            {
                var s1t = Transform.Translate(x * dx, 0, 0);
                var s1  = new Sphere(s1t, Transform.Invert(s1t), false, 1.5f, -1.5f, 1.5f, 360);
                var s1g = new GeometricPrimitive(s1, materialFunc(delta * x, x + 1), null);
                prims.Add(s1g);
            }

            var slt = Transform.Translate(5, 2, -4);
            var slg = new Sphere(slt, Transform.Invert(slt), false, 0.5f, -0.5f, 0.5f, 360);
            var ls  = Spectrum.FromBlackbodyT(7500);
            var dl  = new DiffuseAreaLight(slt, null, ls * 100, 20, slg);
            var sg  = new GeometricPrimitive(slg, new MatteMaterial(new ConstantTexture <Spectrum>(ls), new ConstantTexture <float>(0f), null), dl);

            prims.Add(sg);

            var bvh = new BVH(prims.ToArray(), SplitMethod.HLBVH);

            var mid = bvh.WorldBounds.Centroid;

            var width  = 1200;
            var height = 140;
            var from   = new Point(mid.X, 6f, -12f);
            var to     = mid;

            var fov         = 5.6f;
            var aspectRatio = (float)width / height;

            var transform = Transform.Translate(mid.X, 0f, -50f);
            var dist      = Point.Distance(from, to);
            var filter    = new MitchellFilter(new Vector2(2.5f, 2.5f), 0.7f, 0.15f);
            var film      = new Film(new PixelVector(width, height), new Bounds2D(0, 0, 1, 1), filter, 20f, 1f);
            var camera    = PerspectiveCamera.Create(transform, aspectRatio, 0.0f, dist, fov, film);

            //var integrator = new WhittedIntegrator(4, camera, new HaltonSampler(spp, film.GetSampleBounds()),
            //                                       film.CroppedBounds);

            var integrator = new PathIntegrator(3, camera, new HaltonSampler(spp, film.GetSampleBounds()),
                                                film.CroppedBounds, 6f, LightSampleStrategy.Spatial);

            film.SetSink(new Sink(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "row_" + fileSuffix));

            var lt  = Transform.Translate(mid.X - 60, 200, -80);
            var s   = Spectrum.FromBlackbodyT(4500) * 100000f;
            var pl1 = new PointLight(lt, null, s);

            lt = Transform.Translate(mid.X + 100, 100, -200);
            s  = Spectrum.FromBlackbodyT(2200) * 50000f;
            var pl2 = new PointLight(lt, null, s);

            lt = Transform.Translate(mid.X, 1000f, 0);
            s  = Spectrum.FromBlackbodyT(7000) * 5f;
            var pl3 = new DistantLight(lt, s, new Vector(0, -0.5f, 1));

            lt = Transform.Translate(mid.X, 10, -300);
            s  = Spectrum.FromBlackbodyT(5500) * 100000f;
            var pl4 = new PointLight(lt, null, s);

            var splt = Transform.RotateX(MathF.Rad(18f)).RotateY(MathF.Rad(75)).Translate(0, 10, -8);

            s = Spectrum.FromBlackbodyT(5500) * 100000f;
            var sl = new SpotLight(splt, null, s, 5f, 2f);

            var scene = new Scene(bvh, new ILight[] { pl1, pl2, pl3, pl4, dl, sl });

            //var scene = new Scene(bvh, new ILight[] { dl });

            Console.WriteLine("Rendering at {0}x{1}...", width, height);
            var stopwatch = new Stopwatch();

            stopwatch.Start();
            integrator.Render(scene);
            stopwatch.Stop();
            Console.WriteLine("Done ({0})", stopwatch.Elapsed);
        }
示例#11
0
        public async ValueTask CreateScene()
        {
            var canvas = await Canvas.GetElementById(
                "game-window"
                );

            var engine = await Engine.NewEngine(
                canvas,
                true
                );

            var scene = await Scene.NewScene(
                engine
                );

            var light0 = await PointLight.NewPointLight(
                "Omni",
                await Vector3.NewVector3(
                    0,
                    100,
                    8
                    ),
                scene
                );

            var light1 = await HemisphericLight.NewHemisphericLight(
                "HemisphericLight",
                await Vector3.NewVector3(
                    0,
                    100,
                    8
                    ),
                scene
                );

            var house = await SceneLoader.ImportMesh(
                null,
                "assets/",
                "House.gltf",
                scene
                );

            var freeCamera = await FreeCamera.NewFreeCamera(
                "FreeCamera",
                await Vector3.NewVector3(
                    0,
                    0,
                    -100
                    ),
                scene
                );

            await freeCamera.set_rotation(await Vector3.NewVector3(
                                              0,
                                              0,
                                              0
                                              ));

            await scene.set_activeCamera(freeCamera);

            await freeCamera.attachControl(
                canvas,
                false
                );

            await engine.runRenderLoop(() => Task.Run(() => scene.render(true, false)));

            _engine = engine;
        }
示例#12
0
 public void store(ShadingState state, Vector3 dir, Color power, Color diffuse)
 {
     state.faceforward();
     PointLight vpl = new PointLight();
     vpl.p = state.getPoint();
     vpl.n = state.getNormal();
     vpl.power = power;
     lock (lockObj)
     {
         virtualLights.Add(vpl);
     }
 }
示例#13
0
        protected override Canvas Render(CameraRenderOptions options)
        {
            // Colors
            var tableLegColor = new Color(0.5529, 0.4235, 0.3255);

            // Shapes
            var floorCeiling = new Cube(
                "FloorCeiling",
                Matrix4x4.CreateTranslation(0, 1, 0).Scale(20, 7, 20),
                new Material(
                    pattern: new CheckerPattern(
                        Colors.Black,
                        Colors.DarkGray,
                        Matrix4x4.CreateScaling(0.07, 0.07, 0.07)),
                    ambient: 0.25,
                    diffuse: 0.7,
                    specular: 0.9,
                    shininess: 300,
                    reflective: 0.1));

            var walls = new Cube(
                "Walls",
                Matrix4x4.CreateScaling(10, 10, 10),
                new Material(
                    pattern: new CheckerPattern(
                        new Color(0.4863, 0.3765, 0.2941),
                        new Color(0.3725, 0.2902, 0.2275),
                        Matrix4x4.CreateScaling(0.05, 20, 0.05)),
                    ambient: 0.1,
                    diffuse: 0.7,
                    specular: 0.9,
                    shininess: 300,
                    reflective: 0.1));

            var tableTop = new Cube(
                "TableTop",
                Matrix4x4.CreateScaling(3, 0.1, 2).Translate(0, 3.1, 0),
                new Material(
                    pattern: new StripePattern(
                        tableLegColor,
                        new Color(0.6588, 0.5098, 0.4000),
                        Matrix4x4.CreateRotationY(0.1).Scale(0.05, 0.05, 0.05)),
                    ambient: 0.1,
                    diffuse: 0.7,
                    specular: 0.9,
                    shininess: 300,
                    reflective: 0.2));

            var leg1 = new Cube(
                "Leg1",
                Matrix4x4.CreateScaling(0.1, 1.5, 0.1).Translate(2.7, 1.5, -1.7),
                new Material(tableLegColor, ambient: 0.2, diffuse: 0.7));

            var leg2 = new Cube(
                "Leg2",
                Matrix4x4.CreateScaling(0.1, 1.5, 0.1).Translate(2.7, 1.5, 1.7),
                new Material(tableLegColor, ambient: 0.2, diffuse: 0.7));

            var leg3 = new Cube(
                "Leg3",
                Matrix4x4.CreateScaling(0.1, 1.5, 0.1).Translate(-2.7, 1.5, -1.7),
                new Material(tableLegColor, ambient: 0.2, diffuse: 0.7));

            var leg4 = new Cube(
                "Leg4",
                Matrix4x4.CreateScaling(0.1, 1.5, 0.1).Translate(-2.7, 1.5, 1.7),
                new Material(tableLegColor, ambient: 0.2, diffuse: 0.7));

            var glassCube = new Cube(
                "GlassCube",
                Matrix4x4.CreateScaling(0.25, 0.25, 0.25).RotateY(0.2).Translate(0, 3.45001, 0),
                new Material(
                    new Color(1, 1, 0.8),
                    ambient: 0,
                    diffuse: 0.3,
                    specular: 0.9,
                    shininess: 300,
                    reflective: 0.7,
                    transparency: 0.7,
                    refractiveIndex: 1.5))
            {
                IsShadowHidden = true
            };

            var littleCube1 = new Cube(
                "LittleCube1",
                Matrix4x4.CreateScaling(0.15, 0.15, 0.15).RotateY(-0.4).Translate(1, 3.35, -0.9),
                new Material(new Color(1, 0.5, 0.5), diffuse: 0.4, reflective: 0.6));

            var littleCube2 = new Cube(
                "LittleCube2",
                Matrix4x4.CreateScaling(0.15, 0.07, 0.15).RotateY(0.4).Translate(-1.5, 3.27, 0.3),
                new Material(new Color(1, 1, 0.5)));

            var littleCube3 = new Cube(
                "LittleCube3",
                Matrix4x4.CreateScaling(0.2, 0.05, 0.05).RotateY(0.4).Translate(0, 3.25, 1),
                new Material(new Color(0.5, 1, 0.5)));

            var littleCube4 = new Cube(
                "LittleCube4",
                Matrix4x4.CreateScaling(0.05, 0.2, 0.05).RotateY(0.8).Translate(-0.6, 3.4, -1),
                new Material(new Color(0.5, 0.5, 1)));

            var littleCube5 = new Cube(
                "LittleCube5",
                Matrix4x4.CreateScaling(0.05, 0.2, 0.05).RotateY(0.8).Translate(2, 3.4, 1),
                new Material(new Color(0.5, 1, 1)));

            var frame1 = new Cube(
                "Frame1",
                Matrix4x4.CreateScaling(0.05, 1, 1).Translate(-10, 4, 1),
                new Material(new Color(0.7098, 0.2471, 0.2196), diffuse: 0.6));

            var frame2 = new Cube(
                "Frame2",
                Matrix4x4.CreateScaling(0.05, 0.4, 0.4).Translate(-10, 3.4, 2.7),
                new Material(new Color(0.2667, 0.2706, 0.6902), diffuse: 0.6));

            var frame3 = new Cube(
                "Frame3",
                Matrix4x4.CreateScaling(0.05, 0.4, 0.4).Translate(-10, 4.6, 2.7),
                new Material(new Color(0.3098, 0.5961, 0.3098), diffuse: 0.6));

            var mirrorFrame = new Cube(
                "MirrorFrame",
                Matrix4x4.CreateScaling(5, 1.5, 0.05).Translate(-2, 3.5, 9.95),
                new Material(new Color(0.3882, 0.2627, 0.1882), diffuse: 0.7));

            var mirror = new Cube(
                "Mirror",
                Matrix4x4.CreateScaling(4.8, 1.4, 0.06).Translate(-2, 3.5, 9.95),
                new Material(Colors.Black, ambient: 0, diffuse: 0, specular: 1, shininess: 300, reflective: 1));

            // Lights, camera, action.
            var light = new PointLight(new Point(0, 6.9, -5), new Color(1, 1, 0.9));
            var world = new World(
                light,
                floorCeiling,
                walls,
                tableTop,
                leg1,
                leg2,
                leg3,
                leg4,
                glassCube,
                littleCube1,
                littleCube2,
                littleCube3,
                littleCube4,
                littleCube5,
                frame1,
                frame2,
                frame3,
                mirrorFrame,
                mirror);

            var cameraTransform = Matrix4x4.CreateLookAt(new Point(8, 6, -8), new Point(0, 3, 0), Vector.UnitY);
            var camera          = new Camera(CanvasWidth, CanvasHeight, fieldOfView: 0.785, cameraTransform);

            Canvas canvas = camera.Render(world, options);

            return(canvas);
        }
 public void SetLighting(bool Real)
 {
     lock (GlobalStats.ObjectManagerLocker)
         this.ScreenManager.inter.LightManager.Clear();
     if (!Real)
     {
         lock (GlobalStats.ObjectManagerLocker)
         {
             LightRig local_0 = this.ScreenManager.Content.Load<LightRig>("example/NewGamelight_rig");
             this.ScreenManager.inter.LightManager.Clear();
             this.ScreenManager.inter.LightManager.Submit((ILightRig)local_0);
         }
     }
     else
     {
         lock (GlobalStats.ObjectManagerLocker)
         {
             foreach (SolarSystem item_0 in UniverseScreen.SolarSystemList)
             {
                 PointLight local_2 = new PointLight();
                 local_2.DiffuseColor = new Vector3(1f, 1f, 0.85f);
                 local_2.Intensity = 2.5f;
                 local_2.ObjectType = ObjectType.Dynamic;
                 local_2.FillLight = true;
                 local_2.Radius = 150000f;
                 local_2.Position = new Vector3(item_0.Position, 2500f);
                 local_2.World = Matrix.Identity * Matrix.CreateTranslation(local_2.Position);
                 local_2.Enabled = true;
                 this.ScreenManager.inter.LightManager.Submit((ILight)local_2);
                 PointLight local_3 = new PointLight();
                 local_3.DiffuseColor = new Vector3(1f, 1f, 0.85f);
                 local_3.Intensity = 2.5f;
                 local_3.ObjectType = ObjectType.Dynamic;
                 local_3.FillLight = false;
                 local_3.Radius = 5000f;
                 local_3.Position = new Vector3(item_0.Position, -2500f);
                 local_3.World = Matrix.Identity * Matrix.CreateTranslation(local_3.Position);
                 local_3.Enabled = true;
                 this.ScreenManager.inter.LightManager.Submit((ILight)local_3);
                 PointLight local_4 = new PointLight();
                 local_4.DiffuseColor = new Vector3(1f, 1f, 0.85f);
                 local_4.Intensity = 1f;
                 local_4.ObjectType = ObjectType.Dynamic;
                 local_4.FillLight = false;
                 local_4.Radius = 100000f;
                 local_4.Position = new Vector3(item_0.Position, -6500f);
                 local_4.World = Matrix.Identity * Matrix.CreateTranslation(local_4.Position);
                 local_4.Enabled = true;
                 this.ScreenManager.inter.LightManager.Submit((ILight)local_4);
             }
         }
     }
 }
示例#15
0
 public bool init(Scene scene)
 {
     if (numSets < 1)
         numSets = 1;
     UI.printInfo(UI.Module.LIGHT, "Instant Global Illumination settings:");
     UI.printInfo(UI.Module.LIGHT, "  * Samples:     {0}", numPhotons);
     UI.printInfo(UI.Module.LIGHT, "  * Sets:        {0}", numSets);
     UI.printInfo(UI.Module.LIGHT, "  * Bias bound:  {0}", c);
     UI.printInfo(UI.Module.LIGHT, "  * Bias rays:   {0}", numBias);
     virtualLights = new PointLight[numSets][];
     if (numPhotons > 0)
     {
         for (int i = 0, seed = 0; i < virtualLights.Length; i++, seed += numPhotons)
         {
             PointLightStore map = new PointLightStore(this);
             if (!scene.calculatePhotons(map, "virtual", seed))
                 return false;
             virtualLights[i] = map.virtualLights.ToArray();
             UI.printInfo(UI.Module.LIGHT, "Stored {0} virtual point lights for set {0} of {0}", virtualLights[i].Length, i + 1, numSets);
         }
     }
     else
     {
         // create an empty array
         for (int i = 0; i < virtualLights.Length; i++)
             virtualLights[i] = new PointLight[0];
     }
     return true;
 }
示例#16
0
 internal void add(PointLight pointLight)
 {
     throw new NotImplementedException();
 }
示例#17
0
        protected override void CreateScene()
        {
            WaveServices.ScreenLayers.SetDiagnosticsActive(true);
            //RenderManager.DebugLines = true;

            RenderManager.BackgroundColor = Color.CornflowerBlue;

            //Create the camera
            FreeCamera camera = new FreeCamera("freeCamera", new Vector3(42.60071f, 10.3373f, -45.83459f), new Vector3(41.77419f, 10.37616f, -45.27303f))
            {
                Speed = 10
            };

            //Add some light!
            PointLight light = new PointLight("light", Vector3.Zero)
            {
                Position = new Vector3(0, 5, 0),
                Attenuation = 750,
                Color = new Color(1, 0.6f, 0.4f),
                IsVisible = true
            };

            EntityManager.Add(light);
            EntityManager.Add(camera);

            Material columnMaterialA = new NormalMappingMaterial("Content/column1.wpk", "Content/column1_normal_spec.wpk") { AmbientColor = Color.White * 0.3f };
            Material columnMaterialB = new NormalMappingMaterial("Content/column2.wpk", "Content/column2_normal_spec.wpk") { AmbientColor = Color.White * 0.3f };

            bool isStatic = true;
            float columnSpacing = 8;
            int nCols = 10;
            int nColumns = 0;

            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < nCols; j++)
                {
                    Entity column = new Entity("column_" + nColumns++) { IsStatic = isStatic }
                        .AddComponent(new Transform3D() 
                        { 
                            Position = new Vector3(-j * columnSpacing, 0, (i - 1) * columnSpacing),
                            Rotation = new Vector3(0, (WaveServices.Random.NextInt() % 4) * MathHelper.PiOver4, 0)
                        })
                        .AddComponent(new ModelRenderer())
                        .AddComponent(new Model("Content/mainColumn.wpk"))
                        .AddComponent(new MaterialsMap(columnMaterialB));

                    EntityManager.Add(column);
                }
            }

            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < nCols; j++)
                {
                    Entity column = new Entity("column_" + nColumns++) { IsStatic = isStatic }
                        .AddComponent(new Transform3D() 
                        { 
                            Position = new Vector3(-j * columnSpacing, 0, (i - 4) * columnSpacing),
                            Rotation = new Vector3(0, (WaveServices.Random.NextInt() % 4) * MathHelper.PiOver2, 0)
                        })
                        .AddComponent(new ModelRenderer())
                        .AddComponent(new Model("Content/column.wpk"))
                        .AddComponent(new MaterialsMap(columnMaterialA));

                    EntityManager.Add(column);
                }
            }

            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < nCols; j++)
                {
                    Entity column = new Entity("column_" + nColumns++) { IsStatic = isStatic }
                        .AddComponent(new Transform3D() { Position = new Vector3(-j * columnSpacing, 0, (i + 1) * columnSpacing) })
                        .AddComponent(new ModelRenderer())
                        .AddComponent(new Model("Content/column.wpk"))
                        .AddComponent(new MaterialsMap(columnMaterialA));

                    EntityManager.Add(column);
                }
            }
        }
示例#18
0
        public CompositionList()
        {
            this.InitializeComponent();

            this.Loaded += CompositionList_Loaded;
            this.Unloaded += CompositionList_Unloaded;

            // Get the current compositor
            _compositor = ElementCompositionPreview.GetElementVisual(this).Compositor;
            SurfaceLoader.Initialize(_compositor);
            
            //
            // Create the lights
            //
            _ambientLight = _compositor.CreateAmbientLight();
            _pointLight = _compositor.CreatePointLight();
            _distantLight = _compositor.CreateDistantLight();
            _spotLight = _compositor.CreateSpotLight();
        }
示例#19
0
        public (World, Camera) Setup(int width, int height, double fov)
        {
            // ======================================================
            // the camera
            // ======================================================

            var camera = new Camera(width, height, fov)
            {
                Transform = Transformation.ViewTransform(
                    new Point(-3, 1, 2.5),           // view from
                    new Point(0, 0.5, 0),            // view to
                    new Vector(0, 1, 0)),            // vector up

                ProgressMonitor = new ParallelConsoleProgressMonitor(height),
            };

            // ======================================================
            // light sources
            // ======================================================

            var light = new AreaLight(
                new Point(-1, 2, 4),
                new Vector(2, 0, 0),
                10,
                new Vector(0, 2, 0),
                10,
                new Color(1.5, 1.5, 1.5)
                );

            var light2 = new PointLight(new Point(-1, 2, 4), Color.White);

            var cube = new Cube()
            {
                Material = new Material()
                {
                    Color           = new Color(1.5, 1.5, 1.5),
                    Ambient         = 1.0,
                    Diffuse         = 0.0,
                    Specular        = 0.0,
                    Transparency    = 1.0,
                    RefractiveIndex = 1.0,
                },
                Transform =
                    Transformation.Translation(0, 3, 4) *
                    Transformation.Scaling(1, 1, 0.01),
                HitBy = RayType.Primary | RayType.Reflection | RayType.Refraction,
            };

            var plane = new Plane()
            {
                Material = new Material()
                {
                    Color    = Color.White,
                    Ambient  = 0.025,
                    Diffuse  = 0.67,
                    Specular = 0,
                },
            };

            var sphere = new Sphere()
            {
                Transform =
                    Transformation.Translation(0.5, 0.5, 0) *
                    Transformation.Scaling(0.5, 0.5, 0.5),
                Material = new Material()
                {
                    Color      = new Color(1, 0, 0),
                    Ambient    = 0.1,
                    Specular   = 0.0,
                    Diffuse    = 0.6,
                    Reflective = 0.3,
                },
            };

            var sphere2 = new Sphere()
            {
                Transform =
                    Transformation.Translation(-0.25, 0.33, 0) *
                    Transformation.Scaling(0.33, 0.33, 0.33),
                Material = new Material()
                {
                    Color      = new Color(0.5, 0.5, 1),
                    Ambient    = 0.1,
                    Specular   = 0.0,
                    Diffuse    = 0.6,
                    Reflective = 0.3,
                },
            };

            World world = new World();

            world.Shapes = new List <Shape> {
                cube, plane, sphere, sphere2
            };
            world.Lights = new List <ILight> {
                light
            };

            return(world, camera);
        }
示例#20
0
        public override void Generate(Chunk Chunk)
        {
            this.Chunk = Chunk;
               xmax = (int)Chunk.Size.X;
               ymax = (int)Chunk.Size.Y;

               LightList = new List<Vector2>();
               AlarmLights = new List<KeyValuePair<Vector2, Direction>>();

               CreateDungeon((int)Chunk.Size.X, (int)Chunk.Size.Y, 100);
               ConvertDungeon(Chunk);

               LightingEngine LE = (LightingEngine)Renderer.GetRenderEffect("LightingEngine");
               foreach (Vector2 V in LightList)
               {
               PointLight L = new PointLight()
               {
                   IsEnabled = true,
                   Color = new Vector4(0.9f, .2f, .2f, 1f),
                   Power = .85f,
                   LightDecay = 300,
                   Position = new Vector3(V.X * Chunk.tileSize, V.Y * Chunk.tileSize, 1),
               };

               LE.AddLight(L);
               }

               foreach (KeyValuePair<Vector2, Direction> Alarm in AlarmLights)
               {
               switch (Alarm.Value)
               {
                   case Direction.North:
                       for (int i = -2; i <= 2; i++)
                       {
                           if (!(GetCellType((int)Alarm.Key.X + i, (int)Alarm.Key.Y) == Tile.DirtFloor || GetCellType((int)Alarm.Key.X + i, (int)Alarm.Key.Y) == Tile.Corridor) ||
                               (GetCellType((int)Alarm.Key.X + i, (int)Alarm.Key.Y - 1) == Tile.DirtFloor || GetCellType((int)Alarm.Key.X + i, (int)Alarm.Key.Y - 1) == Tile.Corridor))
                           {
                               break;
                           }
                       }

                       new RedAlarmLamp(new Rectangle((int)Alarm.Key.X * 64 + 32, (int)Alarm.Key.Y * 64 + 4, 16,8), Chunk.map);

                       break;
                   case Direction.South:

                       for (int i = -2; i <= 2; i++)
                       {
                           if (!(GetCellType((int)Alarm.Key.X + i, (int)Alarm.Key.Y + 1) == Tile.DirtFloor || GetCellType((int)Alarm.Key.X + i, (int)Alarm.Key.Y + 1) == Tile.Corridor) ||
                               (GetCellType((int)Alarm.Key.X + i, (int)Alarm.Key.Y) == Tile.DirtFloor || GetCellType((int)Alarm.Key.X + i, (int)Alarm.Key.Y ) == Tile.Corridor))
                           {
                               break;
                           }
                       }

                       RedAlarmLamp tmp = new RedAlarmLamp(new Rectangle((int)Alarm.Key.X * 64 + 32, (int)Alarm.Key.Y * 64 + 60, 16,8), Chunk.map);
                       tmp.Fixture.Body.Rotation = (float)Math.PI;

                       break;
                   case Direction.East:

                       break;
                   case Direction.West:

                       break;
               }
               }
        }
示例#21
0
 public override void SpawnBody()
 {
     light = new PointLight(GetPosition(), 64, 15, new Location(GColor.R, GColor.G, GColor.B) * Brightness);
     TheClient.MainWorldView.Lights.Add(light);
     base.SpawnBody();
 }
示例#22
0
 public override void InitializeEnvironment()
 {
     base.InitializeEnvironment();
     //SpawnCar(1, 1);
     firstLight = new PointLight();
 }
示例#23
0
        protected override Canvas Render(CameraRenderOptions options)
        {
            var floor = new Sphere(
                "Floor",
                Matrix4x4.CreateScaling(10, 0.01, 10),
                new Material(new Color(1, 0.9, 0.9)).WithSpecular(0));

            var leftWall = new Sphere(
                "LeftWall",
                Matrix4x4.CreateScaling(10, 0.01, 10)
                .RotateX(Math.PI / 2)
                .RotateY(-Math.PI / 4)
                .Translate(0, 0, 5),
                floor.Material

                );

            var rightWall = new Sphere(
                "RightWall",
                Matrix4x4.CreateScaling(10, 0.01, 10)
                .RotateX(Math.PI / 2)
                .RotateY(Math.PI / 4)
                .Translate(0, 0, 5),
                floor.Material

                );

            var middle = new Sphere(
                "Middle",
                Matrix4x4.CreateTranslation(-0.5, 1, 0.5),
                new Material(new Color(0.1, 1, 0.5), diffuse: 0.7, specular: 0.3)

                );

            var right = new Sphere(
                "Right",
                Matrix4x4.CreateScaling(0.5, 0.5, 0.5).Translate(1.5, 0.5, -0.5),
                new Material(new Color(0.5, 1, 0.1), diffuse: 0.7, specular: 0.3)

                );

            var left = new Sphere(
                "Left",
                Matrix4x4.CreateScaling(0.33, 0.33, 0.33).Translate(-1.5, 0.33, -0.75),
                new Material(new Color(1, 0.8, 0.1), diffuse: 0.7, specular: 0.3)

                );

            var light1 = new PointLight(new Point(-10, 10, -10), Colors.White);
            var light2 = new PointLight(new Point(0, 10, -10), Colors.DarkGray);
            var light3 = new PointLight(new Point(10, 10, -10), Colors.DarkGray);

            var world = new World(
                new[] { light1, light2, light3 },
                new[] { floor, leftWall, rightWall, middle, right, left });

            var cameraTransform = Matrix4x4.CreateLookAt(new Point(0, 1.5, -5), new Point(0, 1, 0), Vector.UnitY);
            var camera          = new Camera(CanvasWidth, CanvasHeight, Math.PI / 3, cameraTransform);

            Canvas canvas = camera.Render(world, options);

            return(canvas);
        }
        public PlanarShadowsCustomization()
        {
            InitializeComponent();

            _disposables = new DisposeList();

            MainDXViewportView.DXSceneInitialized += delegate(object sender, EventArgs args)
            {
                if (MainDXViewportView.DXScene != null)
                {
                    // Load texture file into ShaderResourceView (in our case we load dds file; but we could also load png file)
                    string textureFileName          = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Resources/GrassTexture.jpg");
                    var    loadedShaderResourceView = Ab3d.DirectX.TextureLoader.LoadShaderResourceView(MainDXViewportView.DXScene.DXDevice.Device, textureFileName);

                    _disposables.Add(loadedShaderResourceView);

                    // Define DXEngine's materials for shadow plane
                    _shadowPlaneMaterial = new StandardMaterial()
                    {
                        DiffuseColor    = Color3.White, // When DiffuseTextures are set, then DiffuseColor is used as a color filter (White means no filter)
                        DiffuseTextures = new ShaderResourceView[] { loadedShaderResourceView }
                    };

                    _shadowPlaneBackMaterial = new StandardMaterial()
                    {
                        DiffuseColor = Colors.DimGray.ToColor3()
                    };

                    _disposables.Add(_shadowPlaneMaterial);
                    _disposables.Add(_shadowPlaneBackMaterial);


                    // Define the PlanarShadowRenderingProvider
                    _planarShadowRenderingProvider = new PlanarShadowRenderingProvider()
                    {
                        // We need to provide information about the position of the plane in 3D space
                        ShadowPlaneCenterPosition  = new Vector3(0, 0, 0),
                        ShadowPlaneSize            = new Vector2(400, 400),
                        ShadowPlaneNormalVector    = new Vector3(0, 1, 0),
                        ShadowPlaneHeightDirection = new Vector3(0, 0, -1),

                        // In case ShadowPlaneMaterial and/or ShadowPlaneBackMaterial are defined
                        // the PlanarShadowRenderingProvider will also render the 3D plane.
                        ShadowPlaneMaterial     = _shadowPlaneMaterial,
                        ShadowPlaneBackMaterial = _shadowPlaneBackMaterial,

                        // Set shadow properties
                        ShadowColor        = Color3.Black,
                        ShadowTransparency = (float)ShadowTransparencySlider.Value / 100.0f, // default value is 0.65f

                        // Because shadow is rendered as standard 3D object, we need to offset it from the shadow plane
                        // to prevent z-fighting problems that occur when two 3D objects are rendered to the same 3D position.
                        // This value need to be very small so that it is not seen that the shadow is above the plane.
                        // Default value is 0.01f.
                        ShadowOffsetFromPlane = 0.01f,

                        // When using PlanarShadowRenderingProvider we do not need PlanarShadowMeshCreator from Ab3d.PowerToys
                        // to prepare a special MeshGeometry3D for us. Also PlanarShadowMeshCreator does not need to manually (on the CPU)
                        // cut the shadow to the plane bounds but this can be done with using hardware accelerated algorithm (using stencil buffer).
                        // But if we still want to use PlanarShadowMeshCreator we can set the following two properties to false
                        // (for example if we wanted to use PlanarShadowRenderingProvider just to provide proper transparent shadows).
                        ApplyShadowMatrix      = true,
                        CutShadowToPlaneBounds = true,

                        IsCheckingIsCastingShadow = false, // Initially do not check for IsCastingShadow values (this is also a default value). See comments in LoadModel for more info.

                        //CustomShadowLight = new Ab3d.DirectX.Lights.DirectionalLight(new Vector3(0, -1, 1))
                        //CustomShadowLight = new Ab3d.DirectX.Lights.PointLight(new Vector3(0, 500, 0), 300)
                    };

                    _disposables.Add(_planarShadowRenderingProvider);


                    MainDXViewportView.DXScene.InitializeShadowRendering(_planarShadowRenderingProvider);
                }


                _lightHorizontalAngle = 30;
                _lightVerticalAngle   = 27;
                _lightDistance        = 500;

                _ambientLight = new AmbientLight(System.Windows.Media.Color.FromRgb(40, 40, 40));

                _shadowPointLight       = new PointLight();
                _shadowDirectionalLight = new DirectionalLight();

                Camera1.ShowCameraLight = ShowCameraLightType.Never; // prevent adding camera's light

                SetShadowLight(isDirectionalLight: true);

                UpdateLights();

                _loadedModel3D = LoadModel3D();
                MainViewport.Children.Add(_loadedModel3D.CreateModelVisual3D());
            };



            this.PreviewKeyDown += OnPreviewKeyDown;

            // This will allow receiving keyboard events
            this.Focusable = true;
            this.Focus();

            this.Unloaded += delegate(object sender, RoutedEventArgs args)
            {
                _disposables.Dispose();
                MainDXViewportView.Dispose();
            };
        }
示例#25
0
        public (World, Camera) Setup(int width, int height, double fov)
        {
            // ======================================================
            // the camera
            // ======================================================

            var camera = new Camera(width, height, fov)
            {
                Transform = Transformation.ViewTransform(
                    new Point(1, 2, -5),           // view from
                    new Point(0, 2, 0),            // view to
                    new Vector(0, 1, 0)),          // vector up

                ProgressMonitor = new ParallelConsoleProgressMonitor(height),
            };

            // ======================================================
            // light sources
            // ======================================================

            var light = new PointLight(
                new Point(-20, 20, -20),
                new Color(1, 1, 1)
                );
            var light2 = new PointLight(
                new Point(-20, 10, -5),
                new Color(1, 1, 1)
                );
            var areaLight = new AreaLight(
                new Point(-100, 100, -100),
                new Vector(4, 0, 0),
                6,
                new Vector(0, 4, 0),
                6,
                new Color(1.0, 1.0, 1.0)
                );


            var floor = new Plane()
            {
                Material = new Material()
                {
                    Color      = Color.White,
                    Ambient    = 0.1,
                    Diffuse    = 0.1,
                    Specular   = 0.0,
                    Reflective = 0.4,
                },
            };


            FileStream   stream       = File.OpenRead("/Users/rhagan/VSCode Projects/RayTracer/RayTracer.Program/Scenes/Textures/brickwall.ppm");
            StreamReader reader       = new StreamReader(stream);
            var          wallTexture  = PpmReader.ReadCanvasFromPpm(reader);
            var          textureLeft  = new UvImage(wallTexture);
            var          textureFront = textureLeft;
            var          textureRight = textureLeft;
            var          textureBack  = textureLeft;
            var          textureUp    = textureLeft;
            var          textureDown  = textureLeft;

            stream = File.OpenRead("/Users/rhagan/VSCode Projects/RayTracer/RayTracer.Program/Scenes/Textures/brickwall_normal.ppm");
            reader = new StreamReader(stream);
            var wallNormalMap = PpmReader.ReadCanvasFromPpm(reader);
            var normalLeft    = new UvImage(wallNormalMap);
            var normalFront   = normalLeft;
            var normalRight   = normalLeft;
            var normalBack    = normalLeft;
            var normalUp      = normalLeft;
            var normalDown    = normalLeft;

            var mapCubeMaterial = new Material()
            {
                Pattern   = new CubeMap(textureLeft, textureFront, textureRight, textureBack, textureUp, textureDown),
                NormalMap = new CubeMap(normalLeft, normalFront, normalRight, normalBack, normalUp, normalDown),
                Ambient   = 0.7,
                Specular  = 0.0,
                Diffuse   = 0.8,
            };

            var box = new Cube()
            {
                Transform =
                    Transformation.Translation(0, 2, 0) *
                    Transformation.Rotation_y(1.9),
                Material = mapCubeMaterial,
            };

            World world = new World();

            world.Shapes = new List <Shape> {
                floor, box
            };
            world.Lights = new List <ILight> {
                light
            };

            return(world, camera);
        }
示例#26
0
        public (World, Camera) Setup(int width, int height, double fov)
        {
            // ======================================================
            // the camera
            // ======================================================

            var camera = new Camera(width, height, fov)
            {
                Transform = Transformation.ViewTransform(
                    new Point(-10, 10, -15),             // view from
                    new Point(6, 0, 6),                  // view to
                    new Vector(-0.45, 1, 0)),            // vector up

                ProgressMonitor = new ParallelConsoleProgressMonitor(height),
            };

            // ======================================================
            // light sources
            // ======================================================

            var light = new PointLight(
                new Point(50, 100, -50),
                new Color(0.8, 0.8, 0.8)
                );

            // an optional second light for additional illumination
            var light2 = new PointLight(
                new Point(-400, 50, -10),
                new Color(0.2, 0.2, 0.2)
                );

            // ======================================================
            // define some constants to avoid duplication
            // ======================================================
            var white_material = new Material()
            {
                Color      = new Color(1, 1, 1),
                Diffuse    = 0.7,
                Ambient    = 0.1,
                Specular   = 0.0,
                Reflective = 0.1,
            };

            var blue_material = new Material()
            {
                Color      = new Color(0.537, 0.831, 0.914),
                Diffuse    = 0.7,
                Ambient    = 0.1,
                Specular   = 0.0,
                Reflective = 0.1,
            };

            var red_material = new Material()
            {
                Color      = new Color(0.941, 0.322, 0.388),
                Diffuse    = 0.7,
                Ambient    = 0.1,
                Specular   = 0.0,
                Reflective = 0.1,
            };

            var purple_material = new Material()
            {
                Color      = new Color(0.373, 0.404, 0.550),
                Diffuse    = 0.7,
                Ambient    = 0.1,
                Specular   = 0.0,
                Reflective = 0.1,
            };

            var standard_transform =
                Transformation.Scaling(0.5, 0.5, 0.5) *
                Transformation.Translation(1, -1, 1);

            var large_object =
                Transformation.Scaling(3.5, 3.5, 3.5) *
                Transformation.Translation(1, -1, 1);

            var medium_object =
                Transformation.Scaling(3, 3, 3) *
                Transformation.Translation(1, -1, 1);

            var small_object =
                Transformation.Scaling(2, 2, 2) *
                Transformation.Translation(1, -1, 1);

            // ======================================================
            // a white backdrop for the scene
            // ======================================================
            var backdrop = new Plane()
            {
                Material = new Material()
                {
                    Color    = Color.White,
                    Ambient  = 1.0,
                    Diffuse  = 0.0,
                    Specular = 0.0,
                },
                Transform =
                    Transformation.Translation(0, 0, 500) *
                    Transformation.Rotation_x(1.5707963267948966),
            };

            // ======================================================
            // describe the elements of the scene
            // ======================================================
            var obj1 = new Sphere()
            {
                Material = new Material()
                {
                    Color           = new Color(0.373, 0.404, 0.550),
                    Ambient         = 0.0,
                    Specular        = 1.0,
                    Diffuse         = 0.2,
                    Shininess       = 200,
                    Reflective      = 0.7,
                    Transparency    = 0.7,
                    RefractiveIndex = 1.5
                },
                Transform =
                    Transformation.Translation(0, 0, 0) *
                    Transformation.Scaling(3.5, 3.5, 3.5),
            };

            var obj2 = new Cube()
            {
                Material  = white_material,
                Transform =
                    Transformation.Translation(8, 0, 0) *
                    Transformation.Scaling(3, 3, 3),
            };

            var obj3 = new Cube()
            {
                Material  = red_material,
                Transform =
                    Transformation.Translation(0, 0, 8) *
                    Transformation.Scaling(3.5, 3.5, 3.5),
            };

            var obj4 = new Cube()
            {
                Material  = blue_material,
                Transform =
                    Transformation.Translation(16, 1.5, -0.5) *
                    Transformation.Scaling(3.5, 3.5, 3.5),
            };

            var obj5 = new Cube()
            {
                Material  = white_material,
                Transform =
                    Transformation.Translation(8, 0, 8) *
                    Transformation.Scaling(2, 2, 2),
            };

            var obj6 = new Cube()
            {
                Material  = purple_material,
                Transform =
                    Transformation.Translation(16, 0, 8) *
                    Transformation.Scaling(3, 3, 3),
            };

            var obj7 = new Cube()
            {
                Material  = white_material,
                Transform =
                    Transformation.Translation(-0.25, 0.25, 16) *
                    Transformation.Scaling(3, 3, 3),
            };

            var obj8 = new Cube()
            {
                Material  = blue_material,
                Transform =
                    Transformation.Translation(8, 2, 16) *
                    Transformation.Scaling(3.5, 3.5, 3.5),
            };

            var obj9 = new Cube()
            {
                Material  = red_material,
                Transform =
                    Transformation.Translation(18, 4, 16) *
                    Transformation.Scaling(3, 3, 3),
            };

            var obj10 = new Cube()
            {
                Material  = white_material,
                Transform =
                    Transformation.Translation(16, 4, 30) *
                    Transformation.Scaling(2, 2, 2),
            };

            var obj11 = new Cube()
            {
                Material  = white_material,
                Transform =
                    Transformation.Translation(40, 3, 18) *
                    Transformation.Scaling(2, 2, 2),
            };

            var obj12 = new Cube()
            {
                Material  = blue_material,
                Transform =
                    Transformation.Translation(-0.5, -9, 0.25) *
                    Transformation.Scaling(3.5, 3.5, 3.5),
            };

            var obj13 = new Cube()
            {
                Material  = red_material,
                Transform =
                    Transformation.Translation(8, -8, 0) *
                    Transformation.Scaling(3.5, 3.5, 3.5),
            };

            var obj14 = new Cube()
            {
                Material  = white_material,
                Transform =
                    Transformation.Translation(16, -8, 0) *
                    Transformation.Scaling(3.5, 3.5, 3.5),
            };

            var obj15 = new Cube()
            {
                Material  = white_material,
                Transform =
                    Transformation.Translation(0, -8, 8) *
                    Transformation.Scaling(3.5, 3.5, 3.5),
            };

            var obj16 = new Cube()
            {
                Material  = purple_material,
                Transform =
                    Transformation.Translation(-0.5, -8.5, 16) *
                    Transformation.Scaling(3.5, 3.5, 3.5),
            };

            var obj17 = new Cube()
            {
                Material  = white_material,
                Transform =
                    Transformation.Translation(0, -16, 8) *
                    Transformation.Scaling(3.5, 3.5, 3.5),
            };

            var obj18 = new Cube()
            {
                Material  = white_material,
                Transform =
                    Transformation.Translation(-1, -17, 16) *
                    Transformation.Scaling(3.5, 3.5, 3.5),
            };

            World world = new World();

            world.Shapes = new List <Shape> {
                backdrop, obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8, obj9, obj10, obj11, obj12, obj13, obj14, obj15, obj16, obj17, obj18
            };
            world.Lights = new List <ILight> {
                light
            };

            return(world, camera);
        }
        protected override Canvas Render(CameraRenderOptions options)
        {
            var canvas = new MutableCanvas(CanvasWidth, CanvasHeight);

            var sphere        = new Sphere(material: new Material(new Color(1, 0.2, 1)));
            var lightPosition = new Point(-10, 10, -10);
            var lightColor    = Colors.White;
            var light         = new PointLight(lightPosition, lightColor);

            var          rayOrigin = new Point(0, 0, -5);
            const int    wallZ     = 10;
            const double wallSize  = 7.0;

            double       pixelSize    = wallSize / canvas.Width;
            const double halfWallSize = wallSize / 2;
            double       totalPixels  = canvas.Width * canvas.Height;

            // For each row of pixels in the canvas...
            for (int y = 0; y < canvas.Height; y++)
            {
                // Compute the world y coordinate (top = +half, bottom = -half).
                double worldY = halfWallSize - (pixelSize * y);

                // For each pixel in the row...
                for (int x = 0; x < canvas.Width; x++)
                {
                    // See if we should stop.
                    if (options.CancellationToken.IsCancellationRequested)
                    {
                        return(canvas.ToImmutable());
                    }

                    // Compute the world x coordinate (left = -half, right = +half).
                    double worldX = -halfWallSize + (pixelSize * x);

                    // Describe the point on the wall that the ray will target.
                    var position = new Point(worldX, worldY, wallZ);

                    // Cast the ray into the scene to see what it hits.
                    var ray = new Ray(rayOrigin, (position - rayOrigin).Normalize());
                    IntersectionList intersections = sphere.Intersect(ray);
                    Intersection?    hit           = intersections.Hit;

                    if (hit != null)
                    {
                        Point  point  = ray.PositionAt(hit.T);
                        Vector normal = hit.Shape.NormalAt(point);
                        Vector eye    = ray.Direction.Negate();
                        Color  color  = hit.Shape.Material.CalculateLighting(hit.Shape, light, point, eye, normal, false);
                        canvas.SetPixel(x, y, color);
                    }
                }

                // Report the progress.
                double pixelsRendered  = (y * CanvasWidth) + CanvasWidth;
                int    percentComplete = (int)Math.Round((pixelsRendered / totalPixels) * 100.0);
                options.Progress?.Report(new RenderProgressStep(percentComplete, y, canvas.GetRow(y)));
            }

            return(canvas.ToImmutable());
        }
示例#28
0
        public override void Bind(Entity entity, Main main, bool creating = false)
        {
            PointLight light = entity.GetOrCreate <PointLight>("PointLight");

            light.Serialize = false;

            const float defaultLightAttenuation = 15.0f;

            light.Attenuation.Value = defaultLightAttenuation;

            Transform transform = entity.GetOrCreate <Transform>("Transform");

            light.Add(new Binding <Vector3>(light.Position, transform.Position));

            if (!main.EditorEnabled)
            {
                AkGameObjectTracker.Attach(entity);
                SoundKiller.Add(entity, AK.EVENTS.STOP_GLOWSQUARE);
                entity.Add(new PostInitialization
                {
                    delegate()
                    {
                        AkSoundEngine.PostEvent(AK.EVENTS.PLAY_GLOWSQUARE, entity);
                        AkSoundEngine.SetRTPCValue(AK.GAME_PARAMETERS.SFX_GLOWSQUARE_PITCH, -1.0f, entity);
                    }
                });
            }

            AI ai = entity.GetOrCreate <AI>("AI");

            ModelAlpha model = entity.GetOrCreate <ModelAlpha>();

            model.Add(new Binding <Matrix>(model.Transform, transform.Matrix));
            model.Filename.Value  = "AlphaModels\\box";
            model.Serialize       = false;
            model.DrawOrder.Value = 15;

            RaycastAIMovement movement  = entity.GetOrCreate <RaycastAIMovement>("Movement");
            Levitator         levitator = entity.GetOrCreate <Levitator>("Levitator");

            const float defaultModelScale = 1.0f;

            model.Scale.Value = new Vector3(defaultModelScale);

            model.Add(new Binding <Vector3, string>(model.Color, delegate(string state)
            {
                switch (state)
                {
                case "Alert":
                    return(new Vector3(1.5f, 1.5f, 0.5f));

                case "Chase":
                    return(new Vector3(1.5f, 0.5f, 0.5f));

                case "Levitating":
                    return(new Vector3(2.0f, 1.0f, 0.5f));

                default:
                    return(new Vector3(1.0f, 1.0f, 1.0f));
                }
            }, ai.CurrentState));

            entity.Add(new Updater
                       (
                           delegate(float dt)
            {
                float source            = 1.0f + ((float)this.random.NextDouble() - 0.5f) * 2.0f * 0.05f;
                model.Scale.Value       = new Vector3(defaultModelScale * source);
                light.Attenuation.Value = defaultLightAttenuation * source;
            }
                       ));

            light.Add(new Binding <Vector3>(light.Color, model.Color));

            Agent agent = entity.GetOrCreate <Agent>();

            agent.Add(new Binding <Vector3>(agent.Position, transform.Position));

            RaycastAI raycastAI = entity.GetOrCreate <RaycastAI>("RaycastAI");

            raycastAI.Add(new TwoWayBinding <Vector3>(transform.Position, raycastAI.Position));
            raycastAI.Add(new Binding <Quaternion>(transform.Quaternion, raycastAI.Orientation));

            AI.Task checkOperationalRadius = new AI.Task
            {
                Interval = 2.0f,
                Action   = delegate()
                {
                    bool shouldBeActive = (transform.Position.Value - main.Camera.Position).Length() < movement.OperationalRadius;
                    if (shouldBeActive && ai.CurrentState == "Suspended")
                    {
                        ai.CurrentState.Value = "Idle";
                    }
                    else if (!shouldBeActive && ai.CurrentState != "Suspended")
                    {
                        ai.CurrentState.Value = "Suspended";
                    }
                },
            };

            AI.Task updatePosition = new AI.Task
            {
                Action = delegate()
                {
                    raycastAI.Update();
                },
            };

            ai.Add(new AI.AIState
            {
                Name  = "Suspended",
                Tasks = new[] { checkOperationalRadius, },
            });

            const float sightDistance   = 30.0f;
            const float hearingDistance = 15.0f;

            ai.Add(new AI.AIState
            {
                Name  = "Idle",
                Enter = delegate(AI.AIState previous)
                {
                    AkSoundEngine.SetRTPCValue(AK.GAME_PARAMETERS.SFX_GLOWSQUARE_PITCH, -1.0f, entity);
                },
                Tasks = new[]
                {
                    checkOperationalRadius,
                    updatePosition,
                    new AI.Task
                    {
                        Interval = 1.0f,
                        Action   = delegate()
                        {
                            raycastAI.Move(new Vector3(((float)this.random.NextDouble() * 2.0f) - 1.0f, ((float)this.random.NextDouble() * 2.0f) - 1.0f, ((float)this.random.NextDouble() * 2.0f) - 1.0f));
                        }
                    },
                    new AI.Task
                    {
                        Interval = 1.0f,
                        Action   = delegate()
                        {
                            Agent a = Agent.Query(transform.Position, sightDistance, hearingDistance, x => x.Entity.Type == "Player");
                            if (a != null)
                            {
                                ai.CurrentState.Value = "Alert";
                            }
                        },
                    },
                },
            });

            ai.Add(new AI.AIState
            {
                Name  = "Alert",
                Enter = delegate(AI.AIState previous)
                {
                    AkSoundEngine.PostEvent(AK.EVENTS.STOP_GLOWSQUARE, entity);
                },
                Exit = delegate(AI.AIState next)
                {
                    AkSoundEngine.PostEvent(AK.EVENTS.PLAY_GLOWSQUARE, entity);
                },
                Tasks = new[]
                {
                    checkOperationalRadius,
                    updatePosition,
                    new AI.Task
                    {
                        Interval = 1.0f,
                        Action   = delegate()
                        {
                            if (ai.TimeInCurrentState > 3.0f)
                            {
                                ai.CurrentState.Value = "Idle";
                            }
                            else
                            {
                                Agent a = Agent.Query(transform.Position, sightDistance, hearingDistance, x => x.Entity.Type == "Player");
                                if (a != null)
                                {
                                    ai.TargetAgent.Value  = a.Entity;
                                    ai.CurrentState.Value = "Chase";
                                }
                            }
                        },
                    },
                },
            });

            AI.Task checkTargetAgent = new AI.Task
            {
                Action = delegate()
                {
                    Entity target = ai.TargetAgent.Value.Target;
                    if (target == null || !target.Active)
                    {
                        ai.TargetAgent.Value  = null;
                        ai.CurrentState.Value = "Idle";
                    }
                },
            };

            // Levitate

            const int levitateRipRadius = 4;

            Func <bool> tryLevitate = delegate()
            {
                Entity voxelEntity = raycastAI.Voxel.Value.Target;
                if (voxelEntity == null)
                {
                    return(false);
                }

                Voxel       map       = voxelEntity.Get <Voxel>();
                Voxel.Coord?candidate = map.FindClosestFilledCell(raycastAI.Coord, 3);

                if (!candidate.HasValue)
                {
                    return(false);
                }

                if (VoxelRip.Go(map, candidate.Value, levitateRipRadius, delegate(List <DynamicVoxel> spawnedMaps)
                {
                    foreach (DynamicVoxel spawnedMap in spawnedMaps)
                    {
                        if (spawnedMap[candidate.Value] != Voxel.States.Empty)
                        {
                            levitator.LevitatingVoxel.Value = spawnedMap.Entity;
                            break;
                        }
                    }
                }))
                {
                    levitator.GrabCoord.Value = candidate.Value;
                    return(true);
                }

                return(false);
            };

            Action delevitateMap = delegate()
            {
                Entity levitatingMapEntity = levitator.LevitatingVoxel.Value.Target;
                if (levitatingMapEntity == null || !levitatingMapEntity.Active)
                {
                    return;
                }

                DynamicVoxel dynamicMap = levitatingMapEntity.Get <DynamicVoxel>();
                VoxelRip.Consolidate(main, dynamicMap);
            };

            // Chase AI state

            ai.Add(new AI.AIState
            {
                Name  = "Chase",
                Enter = delegate(AI.AIState previous)
                {
                    AkSoundEngine.SetRTPCValue(AK.GAME_PARAMETERS.SFX_GLOWSQUARE_PITCH, 0.0f, entity);
                },
                Tasks = new[]
                {
                    checkOperationalRadius,
                    checkTargetAgent,
                    new AI.Task
                    {
                        Interval = 0.35f,
                        Action   = delegate()
                        {
                            raycastAI.Move(ai.TargetAgent.Value.Target.Get <Transform>().Position.Value - transform.Position);
                        }
                    },
                    updatePosition,
                    new AI.Task
                    {
                        Interval = 0.1f,
                        Action   = delegate()
                        {
                            Entity target          = ai.TargetAgent.Value.Target;
                            Vector3 targetPosition = target.Get <Transform>().Position;
                            if ((targetPosition - transform.Position).Length() < 15.0f)
                            {
                                if (tryLevitate())
                                {
                                    ai.CurrentState.Value = "Levitating";
                                }
                            }
                        }
                    }
                },
            });

            Action findNextPosition = delegate()
            {
                movement.LastPosition.Value = transform.Position.Value;
                float   radius = 5.0f;
                Vector3 center = ai.TargetAgent.Value.Target.Get <Transform>().Position;
                Vector3 candidate;
                do
                {
                    candidate = center + new Vector3((float)this.random.NextDouble() - 0.5f, (float)this.random.NextDouble(), (float)this.random.NextDouble() - 0.5f) * radius;
                    radius   += 1.0f;
                }while (!RaycastAI.DefaultPositionFilter(candidate));

                movement.NextPosition.Value  = candidate;
                movement.PositionBlend.Value = 0.0f;
            };

            ai.Add(new AI.AIState
            {
                Name  = "Levitating",
                Enter = delegate(AI.AIState previous)
                {
                    findNextPosition();
                },
                Exit = delegate(AI.AIState next)
                {
                    delevitateMap();
                    levitator.LevitatingVoxel.Value = null;

                    //volume.Value = defaultVolume;
                    //pitch.Value = 0.0f;
                },
                Tasks = new[]
                {
                    checkTargetAgent,
                    new AI.Task
                    {
                        Action = delegate()
                        {
                            //volume.Value = 1.0f;
                            //pitch.Value = 1.0f;
                            Entity levitatingMapEntity = levitator.LevitatingVoxel.Value.Target;
                            if (levitatingMapEntity == null || !levitatingMapEntity.Active || ai.TimeInCurrentState.Value > 8.0f)
                            {
                                Entity voxel = raycastAI.Voxel.Value.Target;
                                if (voxel != null && voxel.Active)
                                {
                                    raycastAI.Coord.Value = raycastAI.LastCoord.Value = voxel.Get <Voxel>().GetCoordinate(transform.Position);
                                }
                                raycastAI.Move(new Vector3(((float)this.random.NextDouble() * 2.0f) - 1.0f, ((float)this.random.NextDouble() * 2.0f) - 1.0f, ((float)this.random.NextDouble() * 2.0f) - 1.0f));
                                ai.CurrentState.Value = "Alert";
                                return;
                            }

                            DynamicVoxel dynamicMap = levitatingMapEntity.Get <DynamicVoxel>();

                            movement.PositionBlend.Value += (main.ElapsedTime.Value / 1.0f);
                            if (movement.PositionBlend > 1.0f)
                            {
                                findNextPosition();
                            }

                            transform.Position.Value = Vector3.Lerp(movement.LastPosition, movement.NextPosition, movement.PositionBlend);

                            Vector3 grabPoint = dynamicMap.GetAbsolutePosition(levitator.GrabCoord);
                            Vector3 diff      = transform.Position.Value - grabPoint;
                            if (diff.Length() > 15.0f)
                            {
                                ai.CurrentState.Value = "Chase";
                                return;
                            }

                            diff *= (float)Math.Sqrt(dynamicMap.PhysicsEntity.Mass) * 0.5f;
                            dynamicMap.PhysicsEntity.ApplyImpulse(ref grabPoint, ref diff);
                        },
                    },
                },
            });

            this.SetMain(entity, main);
        }
示例#29
0
        /// <summary>
        /// Creates main character.
        /// </summary>
        private void CreateIsis()
        {
            PointLight light = new PointLight("light", new Vector3(-1.783f, 2.503f, 0))
            {
                IsVisible = true,
                Color = new Color("f0f2ff"),
                Attenuation = 20
            };
            EntityManager.Add(light);

            Entity isis = new Entity("Isis")
            .AddComponent(new Transform3D() { Position = Vector3.UnitY * 0.15f, Scale = Vector3.One * 1.14f, Rotation = Vector3.UnitY * MathHelper.ToRadians(-25) })
            .AddComponent(new SkinnedModel("Content/Models/isis.wpk"))
            .AddComponent(new SkinnedModelRenderer())
            .AddComponent(new Animation3D("Content/Models/isis-animations.wpk"))
            .AddComponent(new MaterialsMap(new NormalMappingMaterial("Content/Textures/isis-difuse.wpk", "Content/Textures/isis-normal.wpk", DefaultLayers.Opaque) { AmbientColor = Color.White * 0.6f }));

            EntityManager.Add(isis);
            isis.FindComponent<Animation3D>().PlayAnimation("Idle", true);
        }
示例#30
0
    public Scene Build(int width, int height)
    {
        var camera = new Camera(width, height, 0.785)
        {
            Transform =
                Transform.View(
                    Vector4.CreatePosition(-6, 6, -10),
                    Vector4.CreatePosition(6, 0, 6),
                    Vector4.CreateDirection(-0.45, 1, 0)),
        };

        var light1 = new PointLight(
            Vector4.CreatePosition(50, 100, -50),
            new Color(1, 1, 1));

        var light2 = new PointLight(
            Vector4.CreatePosition(-400, 50, -10),
            new Color(0.2, 0.2, 0.2));

        var whiteMaterial = new Material()
        {
            Color      = new Color(0.8, 0.8, 0.8),
            Diffuse    = 0.7,
            Ambient    = 0.1,
            Specular   = 0.0,
            Reflective = 0.1,
        };

        var blueMaterial = whiteMaterial.Extend(m =>
        {
            m.Color = new Color(0.537, 0.831, 0.914);
        });

        var redMaterial = whiteMaterial.Extend(m =>
        {
            m.Color = new Color(0.941, 0.322, 0.388);
        });

        var purpleMaterial = whiteMaterial.Extend(m =>
        {
            m.Color = new Color(0.373, 0.404, 0.550);
        });

        var standardTransform =
            Matrix4x4.Identity
            .Translate(1, -1, 1)
            .Scale(0.5, 0.5, 0.5);

        var largeObject =
            standardTransform.Scale(3.5, 3.5, 3.5);

        var mediumObject =
            standardTransform.Scale(3, 3, 3);

        var smallObject =
            standardTransform.Scale(2, 2, 2);

        var plane = new Plane()
        {
            Material = new Material()
            {
                Color    = new Color(1, 1, 1),
                Ambient  = 1,
                Diffuse  = 0,
                Specular = 0,
            },

            Transform =
                Matrix4x4.Identity
                .RotateX(Math.PI / 2)
                .Translate(0, 0, 500),
        };

        var sphere = new Sphere()
        {
            Material = new Material()
            {
                Color           = new Color(0.373, 0.404, 0.550),
                Diffuse         = 0.2,
                Ambient         = 0.0,
                Specular        = 1.0,
                Shininess       = 200,
                Reflective      = 0.7,
                Transparency    = 0.5,
                RefractiveIndex = 1.5,
            },

            Transform = largeObject,
        };

        var cube1 = new Cube()
        {
            Material  = whiteMaterial,
            Transform =
                mediumObject.Translate(4, 0, 0),
        };

        var cube2 = new Cube()
        {
            Material  = blueMaterial,
            Transform =
                largeObject.Translate(8.5, 1.5, -0.6),
        };

        var cube3 = new Cube()
        {
            Material  = redMaterial,
            Transform =
                largeObject.Translate(0, 0, 4),
        };

        var cube4 = new Cube()
        {
            Material  = whiteMaterial,
            Transform =
                smallObject.Translate(4, 0, 4),
        };

        var cube5 = new Cube()
        {
            Material  = purpleMaterial,
            Transform =
                mediumObject.Translate(7.5, 0.5, 4),
        };

        var cube6 = new Cube()
        {
            Material  = whiteMaterial,
            Transform =
                mediumObject.Translate(-0.25, 0.25, 8),
        };

        var cube7 = new Cube()
        {
            Material  = blueMaterial,
            Transform =
                largeObject.Translate(4, 1, 7.5),
        };

        var cube8 = new Cube()
        {
            Material  = redMaterial,
            Transform =
                mediumObject.Translate(10, 2, 7.5),
        };

        var cube9 = new Cube()
        {
            Material  = whiteMaterial,
            Transform =
                smallObject.Translate(8, 2, 12),
        };

        var cube10 = new Cube()
        {
            Material  = whiteMaterial,
            Transform =
                smallObject.Translate(20, 1, 9),
        };

        var cube11 = new Cube()
        {
            Material  = blueMaterial,
            Transform =
                largeObject.Translate(-0.5, -5, 0.25),
        };

        var cube12 = new Cube()
        {
            Material  = redMaterial,
            Transform =
                largeObject.Translate(4, -4, 0),
        };

        var cube13 = new Cube()
        {
            Material  = whiteMaterial,
            Transform =
                largeObject.Translate(8.5, -4, 0),
        };

        var cube14 = new Cube()
        {
            Material  = whiteMaterial,
            Transform =
                largeObject.Translate(0, -4, 4),
        };

        var cube15 = new Cube()
        {
            Material  = purpleMaterial,
            Transform =
                largeObject.Translate(-0.5, -4.5, 8),
        };

        var cube16 = new Cube()
        {
            Material  = whiteMaterial,
            Transform =
                largeObject.Translate(0, -8, 4),
        };

        var cube17 = new Cube()
        {
            Material  = whiteMaterial,
            Transform =
                largeObject.Translate(-0.5, -8.5, 8),
        };

        var world = new World();

        world.Objects.Add(plane);
        world.Objects.Add(sphere);
        world.Objects.Add(cube1);
        world.Objects.Add(cube2);
        world.Objects.Add(cube3);
        world.Objects.Add(cube4);
        world.Objects.Add(cube5);
        world.Objects.Add(cube6);
        world.Objects.Add(cube7);
        world.Objects.Add(cube8);
        world.Objects.Add(cube9);
        world.Objects.Add(cube10);
        world.Objects.Add(cube11);
        world.Objects.Add(cube12);
        world.Objects.Add(cube13);
        world.Objects.Add(cube14);
        world.Objects.Add(cube15);
        world.Objects.Add(cube16);
        world.Objects.Add(cube17);
        world.Lights.Add(light1);
        world.Lights.Add(light2);

        return(new Scene(world, camera));
    }
        public async ValueTask CreateScene()
        {
            var canvas = await Canvas.GetElementById(
                "game-window"
                );

            var engine = await Engine.NewEngine(
                canvas,
                true
                );

            var scene = await Scene.NewScene(
                engine
                );

            var light0 = await PointLight.NewPointLight(
                "Omni",
                await Vector3.NewVector3(
                    0,
                    100,
                    8
                    ),
                scene
                );

            var light1 = await HemisphericLight.NewHemisphericLight(
                "HemisphericLight",
                await Vector3.NewVector3(
                    0,
                    100,
                    8
                    ),
                scene
                );

            var advancedTexture = await AdvancedDynamicTexture.CreateFullscreenUI("UI");

            var UiPanel = await StackPanel.NewStackPanel("name");

            await UiPanel.set_width("220px");

            await UiPanel.set_fontSize("14px");

            await UiPanel.set_horizontalAlignment(await Control.get_HORIZONTAL_ALIGNMENT_RIGHT());

            await UiPanel.set_verticalAlignment(await Control.get_VERTICAL_ALIGNMENT_CENTER());

            await advancedTexture.addControl(UiPanel);

            var house = await SceneLoader.ImportMesh(
                null,
                "assets/",
                "Player.glb",
                scene,
                new Server.Interop.Callbacks.ActionCallback <AbstractMesh[], IParticleSystem[], Skeleton[], AnimationGroup[]>(async(arg1, arg2, arg3, arg4) =>
            {
                foreach (var animation in arg4)
                {
                    await animation.stop();
                    _animationMap.Add(await animation.get_name(), animation);
                    await AddRunAnimationButton(
                        UiPanel,
                        await animation.get_name()
                        );
                }
                if (_animationMap.Count > 0)
                {
                    _runningAnimation = _animationMap.First().Value;
                    await _runningAnimation.start(true);
                }
            })
                );

            var camera = await ArcRotateCamera.NewArcRotateCamera(
                "ArcRotateCamera",
                (decimal)(System.Math.PI / 2),
                (decimal)(System.Math.PI / 4),
                3,
                await Vector3.NewVector3(0, 1, 0),
                scene
                );

            await camera.set_lowerRadiusLimit(2);

            await camera.set_upperRadiusLimit(10);

            await camera.set_wheelDeltaPercentage(0.01m);

            await scene.set_activeCamera(camera);

            await camera.attachControl(
                canvas,
                false
                );

            await engine.runRenderLoop(() => Task.Run(() => scene.render(true, false)));

            _engine = engine;
        }
示例#32
0
        public void Execute(ref WooState state)
        {
            Vector3 colourVec = _ColourExpr.EvaluateVector(ref state);
            Colour colour = new Colour(colourVec.x, colourVec.y, colourVec.z);

            Vector3 position = _PositionExpr.EvaluateVector(ref state);

            PointLight pointLight = new PointLight(colour, position);
            pointLight.CreateElement(state._Parent, position);
        }
        public PlanarShadows()
        {
            InitializeComponent();

            _disposables = new DisposeList();

            MainDXViewportView.DXSceneInitialized += delegate(object sender, EventArgs args)
            {
                if (MainDXViewportView.DXScene != null)
                {
                    // Load texture file into ShaderResourceView (in our case we load dds file; but we could also load png file)
                    string textureFileName          = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Resources/10x10-texture.png");
                    var    loadedShaderResourceView = Ab3d.DirectX.TextureLoader.LoadShaderResourceView(MainDXViewportView.DXScene.DXDevice.Device, textureFileName);

                    _disposables.Add(loadedShaderResourceView);


                    _planarShadowRenderingProvider = new PlanarShadowRenderingProvider()
                    {
                        ShadowPlaneCenterPosition  = new Vector3(0, 0, 0),
                        ShadowPlaneSize            = new Vector2(400, 400),
                        ShadowPlaneNormalVector    = new Vector3(0, 1, 0),
                        ShadowPlaneHeightDirection = new Vector3(0, 0, -1),

                        ShadowPlaneMaterial = new StandardMaterial()
                        {
                            DiffuseColor    = Color3.White, // When DiffuseTextures are set, then DiffuseColor is used as a color filter (White means no filter)
                            DiffuseTextures = new ShaderResourceView[] { loadedShaderResourceView }
                        },

                        ShadowPlaneBackMaterial = new StandardMaterial()
                        {
                            DiffuseColor = Colors.DimGray.ToColor3()
                        },

                        ShadowColor        = Color3.Black,
                        ShadowTransparency = 0.65f,

                        // Because shadow is rendered as standard 3D object, we need to offset it from the shadow plane
                        // to prevent z-fighting problems that occur when two 3D objects are rendered to the same 3D position.
                        // This value need to be very small so that it is not seen that the shadow is above the plane.
                        // Default value is 0.01f.
                        ShadowOffsetFromPlane = 0.01f,

                        // When using PlanarShadowRenderingProvider we do not need PlanarShadowMeshCreator from Ab3d.PowerToys
                        // to prepare a special MeshGeometry3D for us. Also PlanarShadowMeshCreator does not need to manually (on the CPU)
                        // cut the shadow to the plane bounds but this can be done with using hardware accelerated algorithm (using stencil buffer).
                        // But if we still want to use PlanarShadowMeshCreator we can set the following two properties to false
                        // (for example if we wanted to use PlanarShadowRenderingProvider just to provide proper transparent shadows).
                        ApplyShadowMatrix      = true,
                        CutShadowToPlaneBounds = true,

                        // To use a custom light that does not illuminate the 3D scene set the CustomShadowLight.
                        // Otherwise the first light that has DXAttributeType.IsCastingShadow attribute set to true is used.
                        // If no light has IsCastingShadow attribute set, then the first directional or point light is used.
                        //CustomShadowLight = new Ab3d.DirectX.Lights.DirectionalLight(new Vector3(0, -1, 1))
                        //CustomShadowLight = new Ab3d.DirectX.Lights.PointLight(new Vector3(0, 500, 0), 300)
                    };

                    _disposables.Add(_planarShadowRenderingProvider);


                    MainDXViewportView.DXScene.InitializeShadowRendering(_planarShadowRenderingProvider);
                }


                _lightHorizontalAngle = -60;
                _lightVerticalAngle   = 60;
                _lightDistance        = 500;

                _ambientLight = new AmbientLight(System.Windows.Media.Color.FromRgb(40, 40, 40));

                _shadowPointLight       = new PointLight();
                _shadowDirectionalLight = new DirectionalLight();

                Camera1.ShowCameraLight = ShowCameraLightType.Never; // prevent adding camera's light

                SetShadowLight(isDirectionalLight: true);

                UpdateLights();

                CreateSampleObjects();
            };



            this.PreviewKeyDown += OnPreviewKeyDown;

            // This will allow receiving keyboard events
            this.Focusable = true;
            this.Focus();

            this.Unloaded += delegate(object sender, RoutedEventArgs args)
            {
                StopAnimation();

                _disposables.Dispose();
                MainDXViewportView.Dispose();
            };
        }
示例#34
0
 public void AddPointLight(PointLight light)
 {
     PointLights[Buffer].Add(light);
 }
示例#35
0
        public (World, Camera) Setup(int width, int height, double fov)
        {
            // ======================================================
            // the camera
            // ======================================================

            var camera = new Camera(width, height, fov)
            {
                Transform = Transformation.ViewTransform(
                    new Point(0, 0.5, -2),            // view from
                    new Point(0, 0, 0),               // view to
                    new Vector(0, 1, 0)),             // vector up

                ProgressMonitor = new ParallelConsoleProgressMonitor(height),
            };

            // ======================================================
            // light sources
            // ======================================================

            var light = new PointLight(
                new Point(5, 5, -5),
                new Color(1, 1, 1)
                );

            // ======================================================
            // describe the elements of the scene
            // ======================================================

            var objFile = "/Users/rhagan/VSCode Projects/RayTracer/RayTracer.Program/Scenes/Models/teapot-low.obj";
            //var objFile = "/Users/ryan.hagan/Documents/VSCode Proejects/RayTracer/RayTracer.Program/Scenes/teapot.obj";
            FileStream   instream = File.OpenRead(objFile);
            StreamReader reader   = new StreamReader(instream);
            var          objData  = reader.ReadToEnd();
            var          parser   = new ObjParser(objData);

            parser.Parse();

            var teapot = new Group();

            teapot.Transform = Transformation.Rotation_x(-Math.PI / 2);
            var material = new Material()
            {
                Color      = new Color(0.9, 0.9, 1),
                Ambient    = 0.1,
                Diffuse    = 0.6,
                Specular   = 0.4,
                Shininess  = 5,
                Reflective = 0.1,
            };

            teapot.AddShapes(parser.Groups);
            teapot.SetMaterial(material);

            var boundingBoxMaterial = new Material()
            {
                Color           = new Color(1, 1, 0),
                Ambient         = 0.2,
                Diffuse         = 0.0,
                Specular        = 0.0,
                Shininess       = 0,
                Reflective      = 0.0,
                Transparency    = 0.8,
                RefractiveIndex = 1,
            };
            var box = new Cube(teapot.GetBounds().Min, teapot.GetBounds().Max)
            {
                Material = boundingBoxMaterial,
                HitBy    = RayType.Primary,
            };

            var floor = new Plane()
            {
                Material = new Material()
                {
                    Pattern  = new Checkers(Color.White, Color.Black),
                    Ambient  = 0.9,
                    Diffuse  = 0.2,
                    Specular = 0.0,
                },
                Transform = Transformation.Translation(0, -1, 0),
            };

            World world = new World();

            world.Shapes = new List <Shape> {
                floor, teapot, box
            };
            world.Lights = new List <ILight> {
                light
            };

            return(world, camera);
        }
示例#36
0
        public void Draw(Player player, GraphicsDevice graphicsDevice, SharpDX.Toolkit.Graphics.Effect effect, GameTime gameTime)
        {
            Matrix transformation = Matrix.Identity;

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

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

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

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

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

            PointLight[] pointLights = new PointLight[1];

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

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

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

            for (int x = playerTilePosition.X - DRAWING_RANGE; x <= playerTilePosition.X + DRAWING_RANGE; ++x)
            {
                for (int y = playerTilePosition.Y - DRAWING_RANGE; y <= playerTilePosition.Y + DRAWING_RANGE; ++y)
                {
                    transformation = Matrix.Translation((x + 0.5f) * tileSize.Width, -player.Height, (y + 0.5f) * tileSize.Height);
                    if (x >= 0 && y >= 0 && x <= tiles.GetUpperBound(0) && y <= tiles.GetUpperBound(1))
                    {
                        switch (tiles[x, y])
                        {
                        case TileType.Wall:
                            Helpers.drawModel(wallModel, graphicsDevice, effect, transformation, player, gameTime);
                            break;
                        }
                    }
                    else
                    {
                        Helpers.drawModel(wallModel, graphicsDevice, effect, transformation, player, gameTime);
                    }
                    transformation *= Matrix.Translation(0, 25, 0);
                    Helpers.drawModel(ceilingModel, graphicsDevice, effect, transformation, player, gameTime);
                }
            }
            for (int x = playerTilePosition.X - DRAWING_RANGE; x <= playerTilePosition.X + DRAWING_RANGE; ++x)
            {
                for (int y = playerTilePosition.Y - DRAWING_RANGE; y <= playerTilePosition.Y + DRAWING_RANGE; ++y)
                {
                    if (x >= 0 && y >= 0 && x <= tiles.GetUpperBound(0) && y <= tiles.GetUpperBound(1))
                    {
                        switch (tiles[x, y])
                        {
                        case TileType.Wall:
                            transformation = Matrix.Translation((x + 0.5f) * tileSize.Width, -player.Height, (y + 0.5f) * tileSize.Height);
                            Helpers.drawModel(wallModel, graphicsDevice, effect, transformation, player, gameTime);
                            break;
                        }
                    }
                }
            }
            for (int x = playerTilePosition.X - DRAWING_RANGE; x <= playerTilePosition.X + DRAWING_RANGE; ++x)
            {
                for (int y = playerTilePosition.Y - DRAWING_RANGE; y <= playerTilePosition.Y + DRAWING_RANGE; ++y)
                {
                    if (x >= 0 && y >= 0 && x <= tiles.GetUpperBound(0) && y <= tiles.GetUpperBound(1))
                    {
                        switch (tiles[x, y])
                        {
                        case TileType.Floor_With_Key:
                            transformation = Matrix.Translation((x + 0.5f) * tileSize.Width, -player.Height, (y + 0.5f) * tileSize.Height);
                            Helpers.drawModel(floorKeyModel, graphicsDevice, effect, transformation, player, gameTime);
                            Helpers.drawModel(floorModel, graphicsDevice, effect, transformation, player, gameTime);
                            break;
                        }
                    }
                }
            }
            for (int x = playerTilePosition.X - DRAWING_RANGE; x <= playerTilePosition.X + DRAWING_RANGE; ++x)
            {
                for (int y = playerTilePosition.Y - DRAWING_RANGE; y <= playerTilePosition.Y + DRAWING_RANGE; ++y)
                {
                    if (x >= 0 && y >= 0 && x <= tiles.GetUpperBound(0) && y <= tiles.GetUpperBound(1))
                    {
                        switch (tiles[x, y])
                        {
                        case TileType.Door:
                            transformation = Matrix.Translation((x + 0.5f) * tileSize.Width, -player.Height, (y + 0.5f) * tileSize.Height);
                            Helpers.drawModel(doorModel, graphicsDevice, effect, transformation, player, gameTime);
                            break;
                        }
                    }
                }
            }
            for (int x = playerTilePosition.X - DRAWING_RANGE; x <= playerTilePosition.X + DRAWING_RANGE; ++x)
            {
                for (int y = playerTilePosition.Y - DRAWING_RANGE; y <= playerTilePosition.Y + DRAWING_RANGE; ++y)
                {
                    if (x >= 0 && y >= 0 && x <= tiles.GetUpperBound(0) && y <= tiles.GetUpperBound(1))
                    {
                        switch (tiles[x, y])
                        {
                        case TileType.Floor:
                            transformation = Matrix.Translation((x + 0.5f) * tileSize.Width, -player.Height, (y + 0.5f) * tileSize.Height);
                            Helpers.drawModel(floorModel, graphicsDevice, effect, transformation, player, gameTime);
                            break;
                        }
                    }
                }
            }
            for (int x = playerTilePosition.X - DRAWING_RANGE; x <= playerTilePosition.X + DRAWING_RANGE; ++x)
            {
                for (int y = playerTilePosition.Y - DRAWING_RANGE; y <= playerTilePosition.Y + DRAWING_RANGE; ++y)
                {
                    if (x >= 0 && y >= 0 && x <= tiles.GetUpperBound(0) && y <= tiles.GetUpperBound(1))
                    {
                        switch (tiles[x, y])
                        {
                        case TileType.Goal:
                            transformation = Matrix.Translation((x + 0.5f) * tileSize.Width, -player.Height, (y + 0.5f) * tileSize.Height);
                            Helpers.drawModel(floorModel, graphicsDevice, effect, transformation, player, gameTime);
                            break;
                        }
                    }
                }
            }
        }
示例#37
0
        /// <summary>
        /// Main Logic for the editor part
        /// </summary>
        /// <param name="gameTime"></param>
        /// <param name="entities"></param>
        /// <param name="data"></param>
        public void Update(GameTime gameTime,
                           List <BasicEntity> entities,
                           List <Decal> decals,
                           List <PointLight> pointLights,
                           List <DirectionalLight> dirLights,
                           EnvironmentSample envSample,
                           List <DebugEntity> debugEntities,
                           EditorReceivedData data,
                           MeshMaterialLibrary meshMaterialLibrary)
        {
            if (!GameSettings.e_enableeditor)
            {
                return;
            }

            if (!DebugScreen.ConsoleOpen)
            {
                if (Input.WasKeyPressed(Keys.R))
                {
                    GameStats.e_gizmoMode = GizmoModes.Rotation;
                }
                if (Input.WasKeyPressed(Keys.T))
                {
                    GameStats.e_gizmoMode = GizmoModes.Translation;
                }
                if (Input.WasKeyPressed(Keys.Z))
                {
                    GameStats.e_gizmoMode = GizmoModes.Scale;
                }
            }

            _gizmoMode = GameStats.e_gizmoMode;

            int hoveredId = data.HoveredId;

            if (_gizmoTransformationMode)
            {
                if (Input.mouseState.LeftButton == ButtonState.Pressed)
                {
                    GizmoControl(_gizmoId, data);
                }
                else
                {
                    _gizmoTransformationMode = false;
                }
            }
            else if (Input.WasLMBClicked() && !GUIControl.UIWasUsed)
            {
                previousMouseX = Input.mouseState.X;
                previousMouseY = Input.mouseState.Y;

                //Gizmos
                if (hoveredId >= 1 && hoveredId <= 3)
                {
                    _gizmoId = hoveredId;
                    GizmoControl(_gizmoId, data);
                    return;
                }

                if (hoveredId <= 0)
                {
                    SelectedObject = null;
                    return;
                }

                bool foundnew = false;
                //Get the selected entity!
                for (int index = 0; index < entities.Count; index++)
                {
                    var VARIABLE = entities[index];
                    if (VARIABLE.Id == hoveredId)
                    {
                        SelectedObject = VARIABLE;
                        foundnew       = true;
                        break;
                    }
                }
                if (foundnew == false)
                {
                    for (int index = 0; index < decals.Count; index++)
                    {
                        Decal decal = decals[index];
                        if (decal.Id == hoveredId)
                        {
                            SelectedObject = decal;
                            break;
                        }
                    }

                    for (int index = 0; index < pointLights.Count; index++)
                    {
                        PointLight pointLight = pointLights[index];
                        if (pointLight.Id == hoveredId)
                        {
                            SelectedObject = pointLight;
                            break;
                        }
                    }

                    for (int index = 0; index < dirLights.Count; index++)
                    {
                        DirectionalLight directionalLight = dirLights[index];
                        if (directionalLight.Id == hoveredId)
                        {
                            SelectedObject = directionalLight;
                            break;
                        }
                    }

                    {
                        if (envSample.Id == hoveredId)
                        {
                            SelectedObject = envSample;
                        }
                    }

                    for (int index = 0; index < debugEntities.Count; index++)
                    {
                        DirectionalLight debugEntity = dirLights[index];
                        if (debugEntity.Id == hoveredId)
                        {
                            SelectedObject = debugEntity;
                            break;
                        }
                    }
                }
            }

            //Controls

            if (Input.WasKeyPressed(Keys.Delete))
            {
                //Find object
                if (SelectedObject is BasicEntity)
                {
                    entities.Remove((BasicEntity)SelectedObject);
                    meshMaterialLibrary.DeleteFromRegistry((BasicEntity)SelectedObject);

                    SelectedObject = null;
                }
                else if (SelectedObject is Decal)
                {
                    decals.Remove((Decal)SelectedObject);

                    SelectedObject = null;
                }
                else if (SelectedObject is PointLight)
                {
                    pointLights.Remove((PointLight)SelectedObject);

                    SelectedObject = null;
                }
                else if (SelectedObject is DirectionalLight)
                {
                    dirLights.Remove((DirectionalLight)SelectedObject);

                    SelectedObject = null;
                }
            }

            if (Input.WasKeyPressed(Keys.Insert) || (Input.keyboardState.IsKeyDown(Keys.LeftControl) && Input.WasKeyPressed(Keys.C)))
            {
                if (SelectedObject is BasicEntity)
                {
                    BasicEntity copy = (BasicEntity)SelectedObject.Clone;
                    copy.RegisterInLibrary(meshMaterialLibrary);

                    entities.Add(copy);
                }
                else if (SelectedObject is Decal)
                {
                    Decal copy = (Decal)SelectedObject.Clone;
                    decals.Add(copy);
                }
                else if (SelectedObject is PointLight)
                {
                    PointLight copy = (PointLight)SelectedObject.Clone;
                    pointLights.Add(copy);
                }
                else if (SelectedObject is DirectionalLight)
                {
                    DirectionalLight copy = (DirectionalLight)SelectedObject.Clone;
                    dirLights.Add(copy);
                }
            }
        }
        public override void Update(float elapsedTime)
        {
            if (this.DieNextFrame && this.Active)
            {
                this.Die((GameplayObject)this, false);
            }
            else
            {
                if (!this.Active)
                    return;
                this.TimeElapsed += elapsedTime;
                //Projectile projectile = this;
                Vector2 vector2 = this.Position + this.Velocity * elapsedTime;
                this.Position = vector2;
                this.Scale = this.weapon.Scale;
                if (this.weapon.Animated == 1)
                {
                    this.frameTimer += elapsedTime;
                    if (this.weapon.LoopAnimation == 0 && (double)this.frameTimer > (double)this.switchFrames)
                    {
                        this.frameTimer = 0.0f;
                        ++this.AnimationFrame;
                        if (this.AnimationFrame >= this.weapon.Frames)
                            this.AnimationFrame = 0;
                    }
                    else if (this.weapon.LoopAnimation == 1)
                    {
                        ++this.AnimationFrame;
                        if (this.AnimationFrame >= this.weapon.Frames)
                            this.AnimationFrame = 0;
                    }
                    this.texturePath = this.weapon.AnimationPath + this.AnimationFrame.ToString(this.fmt);
                }
                if (!string.IsNullOrEmpty(this.InFlightCue) && this.inFlight == null)
                {
                    this.inFlight = AudioManager.GetCue(this.InFlightCue);
                    this.inFlight.Apply3D(Projectile.universeScreen.listener, this.emitter);
                    this.inFlight.Play();
                }
                this.particleDelay -= elapsedTime;
                if ((double)this.duration > 0.0)
                {
                    this.duration -= elapsedTime;
                    if ((double)this.duration < 0.0)
                    {
                        this.Health = 0.0f;
                        this.Die((GameplayObject)null, false);
                        return;
                    }
                }
                if (this.missileAI != null)
                    this.missileAI.Think(elapsedTime);
                if (this.droneAI != null)
                    this.droneAI.Think(elapsedTime);
                if (this.ProjSO !=null &&(this.WeaponType == "Rocket" || this.WeaponType == "Drone" || this.WeaponType == "Missile") && (this.system != null && this.system.isVisible && (!this.wasAddedToSceneGraph && Projectile.universeScreen.viewState <= UniverseScreen.UnivScreenState.SystemView)))
                {
                    this.wasAddedToSceneGraph = true;
                    lock (GlobalStats.ObjectManagerLocker)
                        Projectile.universeScreen.ScreenManager.inter.ObjectManager.Submit((ISceneObject)this.ProjSO);
                }
                if (this.firstRun && this.moduleAttachedTo != null)
                {
                    this.Position = this.moduleAttachedTo.Center;
                    this.Center = this.moduleAttachedTo.Center;
                    this.firstRun = false;
                }
                else
                    this.Center = new Vector2(this.Position.X, this.Position.Y);
                this.emitter.Position = new Vector3(this.Center, 0.0f);
                if (this.ProjSO !=null && (this.isInDeepSpace || this.system != null && this.system.isVisible) && Projectile.universeScreen.viewState <= UniverseScreen.UnivScreenState.SystemView)
                {
                    if ((double)this.zStart < -25.0)
                        this.zStart += this.velocityMaximum * elapsedTime;
                    else
                        this.zStart = -25f;
                    this.ProjSO.World = Matrix.Identity * Matrix.CreateScale(this.Scale) * Matrix.CreateRotationZ(this.Rotation) * Matrix.CreateTranslation(this.Center.X, this.Center.Y, -this.zStart);
                    this.WorldMatrix = this.ProjSO.World;
                }
                Vector3 newPosition = new Vector3(this.Center.X, this.Center.Y, -this.zStart);
                if (this.firetrailEmitter != null && this.WeaponEffectType == "Plasma" && ((double)this.duration > (double)this.initialDuration * 0.699999988079071 && (double)this.particleDelay <= 0.0))
                    this.firetrailEmitter.UpdateProjectileTrail(elapsedTime, newPosition, new Vector3(this.Velocity, 0.0f) + Vector3.Normalize(new Vector3(this.direction, 0.0f)) * this.speed * 1.75f);

                if (this.firetrailEmitter != null && this.WeaponEffectType == "MuzzleSmoke" && ((double)this.duration > (double)this.initialDuration * 0.97 && (double)this.particleDelay <= 0.0))
                    this.firetrailEmitter.UpdateProjectileTrail(elapsedTime, newPosition, new Vector3(this.Velocity, 0.0f) + Vector3.Normalize(new Vector3(this.direction, 0.0f)) * this.speed * 1.75f);

                if (this.firetrailEmitter != null && this.WeaponEffectType == "MuzzleSmokeFire" && ((double)this.duration > (double)this.initialDuration * 0.97 && (double)this.particleDelay <= 0.0))
                {
                    this.firetrailEmitter.UpdateProjectileTrail(elapsedTime, newPosition, new Vector3(this.Velocity, 0.0f) + Vector3.Normalize(new Vector3(this.direction, 0.0f)) * this.speed * 1.75f);
                }
                if (this.trailEmitter != null && this.WeaponEffectType == "MuzzleSmokeFire" && ((double)this.duration > (double)this.initialDuration * 0.96 && (double)this.particleDelay <= 0.0))
                {
                    this.trailEmitter.Update(elapsedTime, newPosition);
                }

                if (this.firetrailEmitter != null && this.WeaponEffectType == "FullSmokeMuzzleFire")
                {
                    this.trailEmitter.Update(elapsedTime, newPosition);
                }
                if (this.trailEmitter != null && this.WeaponEffectType == "FullSmokeMuzzleFire" && ((double)this.duration > (double)this.initialDuration * 0.96 && (double)this.particleDelay <= 0.0))
                {
                    this.firetrailEmitter.Update(elapsedTime, newPosition);
                }

                if (this.firetrailEmitter != null && this.WeaponEffectType == "RocketTrail")
                    this.firetrailEmitter.Update(elapsedTime, newPosition);

                if (this.firetrailEmitter != null && this.WeaponEffectType == "SmokeTrail")
                    this.firetrailEmitter.Update(elapsedTime, newPosition);

                if (this.trailEmitter != null && this.WeaponEffectType != "MuzzleSmokeFire" && this.WeaponEffectType != "FullSmokeMuzzleFire")
                    this.trailEmitter.Update(elapsedTime, newPosition);

                if (this.system != null && this.system.isVisible && (this.light == null && this.weapon.Light != null) && (Projectile.universeScreen.viewState < UniverseScreen.UnivScreenState.SystemView && !this.LightWasAddedToSceneGraph))
                {
                    this.LightWasAddedToSceneGraph = true;
                    this.light = new PointLight();
                    this.light.Position = new Vector3(this.Center.X, this.Center.Y, -25f);
                    this.light.World = Matrix.Identity * Matrix.CreateTranslation(this.light.Position);
                    this.light.Radius = 100f;
                    this.light.ObjectType = ObjectType.Dynamic;
                    if (this.weapon.Light == "Green")
                        this.light.DiffuseColor = new Vector3(0.0f, 0.8f, 0.0f);
                    else if (this.weapon.Light == "Red")
                        this.light.DiffuseColor = new Vector3(1f, 0.0f, 0.0f);
                    else if (this.weapon.Light == "Orange")
                        this.light.DiffuseColor = new Vector3(0.9f, 0.7f, 0.0f);
                    else if (this.weapon.Light == "Purple")
                        this.light.DiffuseColor = new Vector3(0.8f, 0.8f, 0.95f);
                    else if (this.weapon.Light == "Blue")
                        this.light.DiffuseColor = new Vector3(0.0f, 0.8f, 1f);
                    this.light.Intensity = 1.7f;
                    this.light.FillLight = true;
                    this.light.Enabled = true;
                    lock (GlobalStats.ObjectManagerLocker)
                        Projectile.universeScreen.ScreenManager.inter.LightManager.Submit((ILight)this.light);
                }
                else if (this.weapon.Light != null && this.LightWasAddedToSceneGraph)
                {
                    this.light.Position = new Vector3(this.Center.X, this.Center.Y, -25f);
                    this.light.World = Matrix.Identity * Matrix.CreateTranslation(this.light.Position);
                }
                if (this.moduleAttachedTo != null)
                {
                    if (this.owner.ProjectilesFired.Count < 30 && this.system != null && (this.system.isVisible && this.MuzzleFlash == null) && (this.moduleAttachedTo.InstalledWeapon.MuzzleFlash != null && Projectile.universeScreen.viewState < UniverseScreen.UnivScreenState.SystemView && !this.muzzleFlashAdded))
                    {
                        this.muzzleFlashAdded = true;
                        this.MuzzleFlash = new PointLight();
                        this.MuzzleFlash.Position = new Vector3(this.moduleAttachedTo.Center.X, this.moduleAttachedTo.Center.Y, -45f);
                        this.MuzzleFlash.World = Matrix.Identity * Matrix.CreateTranslation(this.MuzzleFlash.Position);
                        this.MuzzleFlash.Radius = 65f;
                        this.MuzzleFlash.ObjectType = ObjectType.Dynamic;
                        this.MuzzleFlash.DiffuseColor = new Vector3(1f, 0.97f, 0.9f);
                        this.MuzzleFlash.Intensity = 1f;
                        this.MuzzleFlash.FillLight = false;
                        this.MuzzleFlash.Enabled = true;
                        lock (GlobalStats.ObjectManagerLocker)
                            Projectile.universeScreen.ScreenManager.inter.LightManager.Submit((ILight)this.MuzzleFlash);
                        this.flashTimer -= elapsedTime;
                        this.flash = new MuzzleFlash();
                        this.flash.WorldMatrix = Matrix.Identity * Matrix.CreateRotationZ(this.rotation) * Matrix.CreateTranslation(this.MuzzleFlash.Position);
                        this.flash.Owner = (GameplayObject)this;
                        lock (GlobalStats.ExplosionLocker)
                            MuzzleFlashManager.FlashList.Add(this.flash);
                    }
                    else if ((double)this.flashTimer > 0.0 && this.moduleAttachedTo.InstalledWeapon.MuzzleFlash != null && this.muzzleFlashAdded)
                    {
                        this.flashTimer -= elapsedTime;
                        this.MuzzleFlash.Position = new Vector3(this.moduleAttachedTo.Center.X, this.moduleAttachedTo.Center.Y, -45f);
                        this.flash.WorldMatrix = Matrix.Identity * Matrix.CreateRotationZ(this.rotation) * Matrix.CreateTranslation(this.MuzzleFlash.Position);
                        this.MuzzleFlash.World = Matrix.Identity * Matrix.CreateTranslation(this.MuzzleFlash.Position);
                    }
                }
                if ((double)this.flashTimer <= 0.0 && this.muzzleFlashAdded)
                {
                    lock (GlobalStats.ObjectManagerLocker)
                        Projectile.universeScreen.ScreenManager.inter.LightManager.Remove((ILight)this.MuzzleFlash);
                }
                base.Update(elapsedTime);
            }
        }
示例#39
0
 public PointLightUniform(PointLight light)
 {
     Position      = new Vector4(light.Position, 0f);
     ColorAndRange = new Vector4(light.Color, light.Radius);
 }
示例#40
0
        public void AddLight() {
            var color = new Vector3((float)_random.NextDouble(), (float)_random.NextDouble(),
                    (float)_random.NextDouble());
            color.Normalize();
            var light = new PointLight {
                // Radius = 0.01f * _random.Next(100, 500),
                Radius = 0.004f * _random.Next(100, 500),
                Color = FixLight(color)
            };

            Lights.Add(light);
            _pointLights.Add(new PointLightDesc {
                Light = light,
                A = (float)_random.NextDouble(),
                B = (float)_random.NextDouble(),
                C = 5.0f + (float)_random.NextDouble(),
                D = (float)_random.NextDouble(),
                E = (float)_random.NextDouble(),
                F = (float)_random.NextDouble(),
                G = 3.0f + (float)_random.NextDouble()
            });
        }
        public void CreateScene()
        {
            var canvas = Canvas.GetElementById(
                "game-window"
                );
            var engine = new Engine(
                canvas,
                true
                );
            var scene = new Scene(
                engine
                );

            scene.clearColor = new Color4(0, 0, 0, 0);
            var light0 = new PointLight(
                "Omni",
                new Vector3(
                    0,
                    100,
                    8
                    ),
                scene
                );
            var light1 = new HemisphericLight(
                "HemisphericLight",
                new Vector3(
                    0,
                    100,
                    8
                    ),
                scene
                );
            var advancedTexture = AdvancedDynamicTexture.CreateFullscreenUI("UI");
            var UiPanel         = new StackPanel("name")
            {
                width               = "220px",
                fontSize            = "14px",
                horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_RIGHT,
                verticalAlignment   = Control.VERTICAL_ALIGNMENT_CENTER
            };

            advancedTexture.addControl(UiPanel);

            var house = SceneLoader.ImportMesh(
                null,
                "assets/",
                "Player.glb",
                scene,
                new Interop.Callbacks.ActionCallback <AbstractMesh[], IParticleSystem[], Skeleton[], AnimationGroup[], TransformNode[], Geometry[], Light[]>((arg1, arg2, arg3, arg4, arg5, arg6, arg7) =>
            {
                foreach (var animation in arg4)
                {
                    animation.stop();
                    _animationMap.Add(animation.name, animation);
                    AddRunAnimationButton(
                        UiPanel,
                        animation.name
                        );
                }
                if (_animationMap.Count > 0)
                {
                    _runningAnimation = _animationMap.First().Value;
                    _runningAnimation.start(true);
                }
                return(Task.CompletedTask);
            })
                );
            var camera = new ArcRotateCamera(
                "ArcRotateCamera",
                (decimal)(System.Math.PI / 2),
                (decimal)(System.Math.PI / 4),
                3,
                new Vector3(0, 1, 0),
                scene
                )
            {
                lowerRadiusLimit     = 2,
                upperRadiusLimit     = 10,
                wheelDeltaPercentage = 0.01m
            };

            scene.activeCamera = camera;
            camera.attachControl(
                false
                );
            engine.runRenderLoop(new ActionCallback(
                                     () => Task.Run(() => scene.render(true, false))
                                     ));

            _engine = engine;
        }
示例#42
0
        public void Run()
        {
            GameHelper.SetGame(this);

            Window = new RenderWindow(mode, title, Styles.Close);
            RStates = new RenderStates(RenderStates.Default);

            Window.Closed += (s, e) =>
            {
                Console.WriteLine("Closing");
                Window.Close();
            };

            Window.SetVerticalSyncEnabled(true);

            BackgroundColor = new Color(100, 149, 237);

            World = new World.World(this);

            World.AddObject(new Box(this, new Vector2f(50, 50), new Vector2f(64, 64), Color.White));
            World.AddObject(new Box(this, new Vector2f(300, 200), new Vector2f(64, 64), Color.White));
            World.AddObject(new Box(this, new Vector2f(450, 350), new Vector2f(64, 64), Color.White));
            World.AddObject(new Box(this, new Vector2f(100, 250), new Vector2f(64, 64), Color.White));
            World.AddObject(new Box(this, new Vector2f(200, 150), new Vector2f(64, 64), Color.White));
            World.AddObject(new Box(this, new Vector2f(150, 400), new Vector2f(64, 64), Color.White));
            World.AddObject(new Box(this, new Vector2f(400, 100), new Vector2f(64, 64), Color.White));
            World.AddObject(new Box(this, new Vector2f(500, 250), new Vector2f(64, 64), Color.White));
            World.AddObject(new Box(this, new Vector2f(600, 300), new Vector2f(64, 64), Color.White));
            World.AddObject(new Box(this, new Vector2f(350, 450), new Vector2f(64, 64), Color.White));
            World.AddObject(new Box(this, new Vector2f(650, 500), new Vector2f(64, 64), Color.White));
            World.AddObject(new Box(this, new Vector2f(400, 100), new Vector2f(64, 64), Color.White));
            World.AddObject(new Box(this, new Vector2f(250, 350), new Vector2f(64, 64), Color.White));
            World.AddObject(new Box(this, new Vector2f(400, 100), new Vector2f(64, 64), Color.White));
            World.AddObject(new Box(this, new Vector2f(650, 50), new Vector2f(64, 64), Color.White));

            Lighting = new Lighting(this);
            var light = new PointLight(this, new Vector2f(100, 10), Color.Blue, 100f, 32);

            Lighting.AddLight(light);

            Stopwatch timer = new Stopwatch();
            while (Window.IsOpen)
            {
                timer.Restart();

                Window.DispatchEvents();

                Window.Clear(BackgroundColor);

                World.Update(Frametime);
                Lighting.Update(Frametime);

                light.Position = new Vector2f(Mouse.GetPosition(Window).X, Mouse.GetPosition(Window).Y);

                World.Draw(Window, RStates);
                Lighting.Draw(Window, RStates);

                Debug.Draw(Window);

                Window.Display();

                timer.Stop();
                Frametime = (float)timer.Elapsed.TotalMilliseconds;
                Window.SetTitle($"{title} ({Math.Round(Frametime, 1):0.0}ms)");
            }
        }
示例#43
0
        public void CreateMineral(MaterialManager materialManager, Map map, SharedVisuals sharedVisuals, Vector3D position, bool randomOrientation, double volumeInCubicMeters)
        {
            _map           = map;
            _sharedVisuals = sharedVisuals;

            if (_mineralType == MineralType.Custom)
            {
                #region Validate

                if (_numSides < 3)
                {
                    throw new ApplicationException("The number of sides must at least be 3");
                }

                if (_rings.Count == 0)
                {
                    throw new ApplicationException("Need at least one ring");
                }

                #endregion
            }
            else
            {
                // Overwrite my public properties based on the mineral type
                StoreSettingsForMineralType(volumeInCubicMeters);
            }

            RotateTransform3D randomRotation = null;
            if (randomOrientation)
            {
                randomRotation = new RotateTransform3D(new AxisAngleRotation3D(Math3D.GetRandomVector_Spherical(1d), Math1D.GetNearZeroValue(360d)));
            }

            if (_mineralType == MineralType.Rixium)
            {
                #region Rixium Visuals

                Model3DGroup ringModels = new Model3DGroup();

                ringModels.Children.Add(GetRixiumTorusVisual(new Vector3D(0, 0, -.6), .38, .5, randomRotation));
                ringModels.Children.Add(GetRixiumTorusVisual(new Vector3D(0, 0, -.3), .44, .75, randomRotation));
                ringModels.Children.Add(GetRixiumTorusVisual(new Vector3D(0, 0, 0), .5, 1, randomRotation));
                ringModels.Children.Add(GetRixiumTorusVisual(new Vector3D(0, 0, .3), .44, .75, randomRotation));
                ringModels.Children.Add(GetRixiumTorusVisual(new Vector3D(0, 0, .6), .38, .5, randomRotation));

                //TODO:  Look at the global lighting options
                PointLight pointLight = new PointLight();
                pointLight.Color             = Color.FromArgb(255, 54, 147, 168);
                pointLight.Range             = 20;
                pointLight.LinearAttenuation = .33;
                ringModels.Children.Add(pointLight);

                ModelVisual3D ringModel = new ModelVisual3D();        // this is the expensive one, so as few of these should be made as possible
                ringModel.Content = ringModels;

                _visuals.Add(ringModel);
                _map.Viewport.Children.Add(ringModel);

                #endregion
            }

            #region WPF Model

            // Material
            MaterialGroup materials = new MaterialGroup();
            if (_diffuseColor.A > 0)
            {
                materials.Children.Add(new DiffuseMaterial(new SolidColorBrush(_diffuseColor)));
            }

            if (_specularColor.A > 0)
            {
                materials.Children.Add(new SpecularMaterial(new SolidColorBrush(_specularColor), _specularPower));
            }

            if (_emissiveColor.A > 0)
            {
                materials.Children.Add(new EmissiveMaterial(new SolidColorBrush(_emissiveColor)));
            }

            // Geometry Model
            GeometryModel3D geometry = new GeometryModel3D();
            geometry.Material     = materials;
            geometry.BackMaterial = materials;

            if (_mineralType == MineralType.Custom)
            {
                geometry.Geometry = UtilityWPF.GetMultiRingedTube_ORIG(_numSides, _rings, false, true);
            }
            else
            {
                geometry.Geometry = _sharedVisuals.GetMineralMesh(_mineralType);
            }
            if (randomOrientation)
            {
                geometry.Transform = randomRotation;
            }

            // Model Visual
            ModelVisual3D model = new ModelVisual3D();
            model.Content   = geometry;
            model.Transform = new TranslateTransform3D(position);

            // Add to the viewport
            _visuals.Add(model);
            _map.Viewport.Children.Add(model);

            #endregion

            #region Physics Body

            // Make a physics body that represents this shape
            _physicsBody = new ConvexBody3D(_map.World, model);

            _physicsBody.MaterialGroupID = materialManager.MineralMaterialID;

            _physicsBody.NewtonBody.UserData = this;

            _physicsBody.Mass = Convert.ToSingle(_mass);

            _physicsBody.LinearDamping  = .01f;
            _physicsBody.AngularDamping = new Vector3D(.01f, .01f, .01f);
            _physicsBody.Override2DEnforcement_Rotation = true;

            _physicsBody.ApplyForce += new BodyForceEventHandler(Body_ApplyForce);

            #endregion

            // Add to the map
            _map.AddItem(this);
        }
示例#44
0
        //public event OnDropBombHandler DroppedBomb;
        //public event OnBombExplodeHandler BombExploded;
        //public event OnGenericBlockEventHandler BombPlacedBonus;
        //public event OnGenericMultiblockEventHandler BombBrokeBlocks;

        /*protected void FireBombBrokeBlocks(object sender, MultiCaseEventArgs e)
         * {
         *  BombBrokeBlocks?.Invoke(sender, e);
         * }
         * protected void FireBombPlacedBonus(object sender, CaseEventArgs e)
         * {
         *  BombPlacedBonus?.Invoke(sender, e);
         * }
         * public void FireDroppedBomb(object sender, CaseEventArgs e)
         * {
         *  DroppedBomb?.Invoke(sender, e);
         * }*/

        public Joueur(int x, int y, Map m) : base(x, y, m)
        {
            Size            = 25;
            _textureVariant = 0;

            //BombsLeft = 1;

            m_WeaponList = new Weapons[] { new Pistol(this), new AssaultRifle(this), new Shotgun(this) };

            for (int i = 0; i < m_WeaponList.Length; i++)
            {
                switch (Game1.Arma[i])
                {
                case WeaponType.Pistol:
                    m_WeaponList[i] = new Pistol(this);
                    break;

                case WeaponType.AssaultRifle:
                    m_WeaponList[i] = new AssaultRifle(this);
                    break;

                case WeaponType.Shotgun:
                    m_WeaponList[i] = new Shotgun(this);
                    break;

                case WeaponType.SemiAutoSniper:
                    m_WeaponList[i] = new SemiAutomaticSniper(this);
                    break;

                case WeaponType.BoltAction:
                    m_WeaponList[i] = new BoltActionSniper(this);
                    break;
                }
            }
            _Hp = MaxHealth;

            Lights = new Light[2];

            Lights[0] = new PointLight
            {
                Color        = Color.DarkGray,
                Intensity    = 1f,
                Scale        = new Vector2(Game1.Screen.ClientBounds.Width * 3 / 4, Game1.Screen.ClientBounds.Height * 3 / 4),
                CastsShadows = true,
                ShadowType   = ShadowType.Occluded,
                Radius       = 5
            };
            Game1.Penumbra.Lights.Add(Lights[0]);

            Lights[1]              = new PointLight();
            Lights[1].Color        = Color.DarkGray;
            Lights[1].Intensity    = 1f;
            Lights[1].Scale        = new Vector2(Game1.Screen.ClientBounds.Width * 3 / 4, Game1.Screen.ClientBounds.Height * 3 / 4);
            Lights[1].CastsShadows = false;
            Lights[1].ShadowType   = ShadowType.Solid;
            Lights[1].Radius       = 5;
            Game1.Penumbra.Lights.Add(Lights[1]);

            ChangedCase += Joueur_ChangedCase;
            Moved       += Joueur_Moved;
            Died        += Die;
        }
示例#45
0
        static Scene Test3()
        {
            Scene scene = new Scene();

            MashTrigle[] objs;
            MashTrigle   obj;

            //objs = OBJLoader.LoadModel("A:\\m3_1.obj");
            objs = OBJLoaderWNormalSmooth.LoadModel("A:\\m3_1.obj");
            obj  = objs[0];
            obj.Material.Roughness = 0.8f;
            scene.Objects.Add(obj);

            objs = OBJLoader.LoadModel("A:\\m3_2.obj");
            obj  = objs[0];
            obj.Material.Metallic.Metallic = 0.9f;
            obj.Material.Roughness         = 0.8f;
            obj.Material.BaseColor         = new PureXYZColorMaterialMap(new RGBSpectrum(0.3f, 0.3f, 0.3f));
            scene.Objects.Add(obj);

            objs = OBJLoaderWNormalSmooth.LoadModel("A:\\m3_b1.obj");
            obj  = objs[0];
            obj.Material.Metallic.Metallic     = 0.0f;
            obj.Material.Refraction.Enable     = true;
            obj.Material.Refraction.Refraction = 0.9f;
            obj.Material.Refraction.IOR        = 1.4f;
            obj.Material.Roughness             = 0.1f;
            obj.Material.BaseColor             = new PureXYZColorMaterialMap(new RGBSpectrum(0.9f, 0.95f, 0.9f));
            scene.Objects.Add(obj);

            //obj.Material.BaseColor = new PureColorMaterialMap(new Color(0.1f));

            PointLight pLight1 = new PointLight()
            {
                Position = new Vector3f(-5, 5, 0),
                R        = 0.2f,
            };

            pLight1.Material.Light.Intensity = new RGBSpectrum(200.0f, 10.0f, 10.0f);
            PointLight pLight2 = new PointLight()
            {
                Position = new Vector3f(5, 5, -1),
                R        = 0.2f,
            };

            pLight2.Material.Light.Intensity = new RGBSpectrum(10.0f, 10.0f, 200.0f);
            //scene.LightObjects.Add(pLight1);
            //scene.LightObjects.Add(pLight2);
            scene.Objects.Add(pLight1);
            scene.Objects.Add(pLight2);

            PointLight pLight;

            pLight = new PointLight()
            {
                Position = new Vector3f(0, 5, 2)
            };
            pLight.Material.Light.Intensity = new RGBSpectrum(30.0f);
            scene.Objects.Add(pLight);
            //scene.LightObjects.Add(pLight);

            return(scene);
        }
示例#46
0
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // Overlay component, used to draw the pause menu and game over menu
            overlayComponent = new OverlayComponent(Game, spriteBatch);
            Game.Components.Add(overlayComponent);

            projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
                GraphicsDevice.Viewport.AspectRatio, 0.1f, 50000);

            directionalLight = new DirectionalLight(
                new Vector3(-1.25f, -2f, 5.0f), // Direction
                new Vector3(.1f, .1f, .1f),//new Vector3(.15f, .14f, .29f), // Ambient
                new Vector3(.46f, .33f, .75f)); // Diffuse

            Game.AddService(typeof(DirectionalLight), directionalLight);

            #region Level terrain generation

            int heightMapSize = terrainSegmentsCount * terrainSegmentSize + 1;
            float halfHeightMapSize = heightMapSize / 2f;
            HeightMap heightmapGenerator = new HeightMap(heightMapSize);
            var heightMap = heightmapGenerator.Generate();

            var roadMap = new float[heightMapSize, heightMapSize];
            raceTrack = new RaceTrack(heightMapSize, terrainScale);

            navMesh = new NavMesh(GraphicsDevice, raceTrack.Curve, //1500, roadWidth, terrainScale);
                750, roadWidth, terrainScale);

            Vector3 lastPosition = raceTrack.Curve.GetPoint(.01f) / terrainScale;

            for (float t = 0; t < 1; t += .0002f)
            {
                var e = raceTrack.Curve.GetPoint(t) / terrainScale;

                for (float j = -roadFalloff; j <= roadFalloff; j++)
                {
                    var pos = e + j * Vector3.Normalize(Vector3.Cross(lastPosition - e, Vector3.Up));

                    // Indices
                    int x = (int)(pos.X + halfHeightMapSize),
                        z = (int)(pos.Z + halfHeightMapSize);

                    float height = e.Y;

                    if (Math.Abs(j) <= roadWidth)
                    {
                        heightMap[x, z] = height;
                        roadMap[x, z] = 1;
                    }
                    else
                    {
                        float amount = (Math.Abs(j) - roadWidth) / (roadFalloff - roadWidth);
                        heightMap[x, z] = MathHelper.Lerp(height,
                            heightMap[x, z], amount);
                        roadMap[x, z] = amount / 10f;
                    }
                }
                lastPosition = e;
            }

            heightmapGenerator.Smoothen();
            heightmapGenerator.Perturb(30f);

            for (int i = 0; i < 5; i++)
            {
                heightmapGenerator.Smoothen();
            }

            terrainEffect = content.Load<Effect>(@"Effects\TerrainShading");

            //terrainEffect.Parameters["TextureMap0"].SetValue(content.Load<Texture2D>(@"Terrain\sand"));
            #region TEXTURE RENDERING

            //var unprocessedGrassTexture = content.Load<Texture2D>(@"Terrain\grass");
            //var grassTexture = new RenderTarget2D(GraphicsDevice, unprocessedGrassTexture.Width, unprocessedGrassTexture.Height);

            //GraphicsDevice.SetRenderTarget(grassTexture);
            //spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
            //spriteBatch.Draw(unprocessedGrassTexture, new Rectangle(0, 0, unprocessedGrassTexture.Width, unprocessedGrassTexture.Height), Color.White);
            //spriteBatch.Draw(content.Load<Texture2D>(@"Particles\fire"), new Rectangle(0, 0, unprocessedGrassTexture.Width, unprocessedGrassTexture.Height), Color.White);
            //spriteBatch.End();
            //GraphicsDevice.SetRenderTarget(null);

            //terrainEffect.Parameters["TextureMap1"].SetValue(grassTexture);

            #endregion
            terrainEffect.Parameters["TextureMap0"].SetValue(content.Load<Texture2D>(@"Terrain\road"));
            terrainEffect.Parameters["TextureMap1"].SetValue(content.Load<Texture2D>(@"Terrain\grass"));
            terrainEffect.Parameters["TextureMap2"].SetValue(content.Load<Texture2D>(@"Terrain\rock"));
            terrainEffect.Parameters["TextureMap3"].SetValue(content.Load<Texture2D>(@"Terrain\snow"));
            terrainEffect.Parameters["RoadNormalMap"].SetValue(content.Load<Texture2D>(@"Terrain\road_n"));
            terrainEffect.Parameters["Projection"].SetValue(projectionMatrix);

            // Creates a terrainmodel around Vector3.Zero
            terrainSegments = new TerrainModel[terrainSegmentsCount, terrainSegmentsCount];

            float terrainStart = -.5f * heightMapSize;

            for (int z = 0; z < terrainSegmentsCount; z++)
            {
                for (int x = 0; x < terrainSegmentsCount; x++)
                {
                    terrainSegments[x, z] = new TerrainModel(GraphicsDevice,
                        terrainSegmentSize, terrainSegmentsCount, terrainStart,
                        x * terrainSegmentSize, z * terrainSegmentSize,
                        terrainScale, heightMap, roadMap, terrainEffect, directionalLight);
                }
            }

            #endregion

            #region Car

            Car = MakeCar();
            gameInstance.AddService(typeof(Car), Car);
            Player localPlayer = gameInstance.GetService<ServerClient>().LocalPlayer;
            gameInstance.GetService<CarControlComponent>().Cars[localPlayer] = Car;
            gameInstance.AddService(typeof(Player), localPlayer);

            #endregion

            #region Lights

            // Load model to represent our lightsources
            var pointLightModel = content.Load<Model>(@"Models\light");

            //spotLightModel = content.Load<Model>(@"Models\Cone");

            Vector3 pointLightOffset = new Vector3(0, 250, 0);

            var cr = new CurveRasterization(raceTrack.Curve, 50);

            float colorOffset = 0f;

            foreach (var point in cr.Points)
            {
                Random r = UniversalRandom.GetInstance();

                Vector3 color = new Vector3(0f,0f,0f);
                PointLight pl = new PointLight(point.Position + pointLightOffset +
                    Vector3.Transform(50 * Vector3.Up, Matrix.CreateRotationZ(MathHelper.TwoPi * (float)UniversalRandom.GetInstance().NextDouble())),
                    color, 450)
                {
                    Model = pointLightModel,
                    ColorTimeOffset = colorOffset
                };

                pointLights.Add(pl);
                GraphicalObjects.Add(pl);

                colorOffset += 100 / cr.Points.Count;
            }

            #endregion

            dustEmitter = new ParticleEmitter(dustSystem, 150, Car.Position);

            #region SkySphere

            skyBoxModel = content.Load<Model>(@"Models/skybox");
            skyBoxEffect = content.Load<Effect>(@"Effects/SkyBox");

            skyMap = new TextureCube(GraphicsDevice, 2048, false, SurfaceFormat.Color);
            string[] cubemapfaces = { @"SkyBoxes/PurpleSky/skybox_right1",
                @"SkyBoxes/PurpleSky/skybox_left2",
                @"SkyBoxes/PurpleSky/skybox_top3",
                @"SkyBoxes/PurpleSky/skybox_bottom4",
                @"SkyBoxes/PurpleSky/skybox_front5",
                @"SkyBoxes/PurpleSky/skybox_back6_2"
            };

            //cubeMap = new TextureCube(GraphicsDevice, 1024, false, SurfaceFormat.Color);
            //string[] cubemapfaces = {
            //    @"SkyBoxes/StormyDays/stormydays_ft",
            //    @"SkyBoxes/StormyDays/stormydays_bk",
            //    @"SkyBoxes/StormyDays/stormydays_up",
            //    @"SkyBoxes/StormyDays/stormydays_dn",
            //    @"SkyBoxes/StormyDays/stormydays_rt",
            //    @"SkyBoxes/StormyDays/stormydays_lf"
            //};

            //cubeMap = new TextureCube(GraphicsDevice, 1024, false, SurfaceFormat.Color);
            //string[] cubemapfaces = {
            //    @"SkyBoxes/Miramar/miramar_ft",
            //    @"SkyBoxes/Miramar/miramar_bk",
            //    @"SkyBoxes/Miramar/miramar_up",
            //    @"SkyBoxes/Miramar/miramar_dn",
            //    @"SkyBoxes/Miramar/miramar_rt",
            //    @"SkyBoxes/Miramar/miramar_lf"
            //};

            for (int i = 0; i < cubemapfaces.Length; i++)
                LoadCubemapFace(skyMap, cubemapfaces[i], (CubeMapFace)i);

            skyBoxEffect.Parameters["SkyboxTexture"].SetValue(skyMap);

            foreach (var mesh in skyBoxModel.Meshes)
                foreach (var part in mesh.MeshParts)
                    part.Effect = skyBoxEffect;

            #endregion

            #region Weather

            thunderBoltGenerator = new ThunderBoltGenerator(gameInstance, thunderParticleSystem);
            gameInstance.Components.Add(thunderBoltGenerator);

            #endregion

            #region GameObjects

            OakTree.LoadMaterial(content);
            BirchTree.LoadMaterial(content);
            Stone.LoadMaterial(content);

            int numObjects = 75;

            for (int i = 0; i < numObjects; i++)
            {

                var t = navMesh.triangles[UniversalRandom.GetInstance().Next(navMesh.triangles.Length)];
                float v = (float)UniversalRandom.GetInstance().NextDouble();

                //float u = (float) (UniversalRandom.GetInstance().NextDouble() - 1/2f);
                //if (u < 0)
                //    u -= .5f;
                //else
                //    u += 1.5f;

                float u = 0;
                if (UniversalRandom.GetInstance().NextDouble() <= .5)
                    u = -.5f - .3f * (float)(-UniversalRandom.GetInstance().NextDouble());
                else
                    u = (float)(1.5f + .3f * UniversalRandom.GetInstance().NextDouble());

                var pos = (t.vertices[0] + u * t.ab + v * t.ac) / terrainScale;
                //var treePos = new Vector3(-halfHeightMapSize + (float)UniversalRandom.GetInstance().NextDouble() * (heightMapSize-50), 0,
                //    -halfHeightMapSize + (float)UniversalRandom.GetInstance().NextDouble() * (heightMapSize-50));

                float X = pos.X + heightMapSize / 2f,
                    Z = pos.Z +heightMapSize / 2f;

                float Xlerp = X % 1f,
                    Zlerp = Z % 1f;

                int x0 = (int)X,
                    z0 = (int)Z,
                    x1 = x0 + 1,
                    z1 = z0 + 1;

                float height;
                float k;
                if (Xlerp + Zlerp > 1)
                {
                    float h1 = MathHelper.Lerp(heightMap[x0, z1], heightMap[x1, z1], Xlerp);
                    float h2 = MathHelper.Lerp(heightMap[x1, z0], heightMap[x1, z1], Zlerp);
                    k = h2 / h1;
                    height = MathHelper.Lerp(h1, h2, .5f);
                }
                else
                {
                    float h1 = MathHelper.Lerp(heightMap[x0, z0], heightMap[x1, z0], Xlerp),
                        h2 = MathHelper.Lerp(heightMap[x0, z0], heightMap[x0, z1], Zlerp);
                    k = h2 / h1;
                    height = MathHelper.Lerp(h1, h2, .5f);
                }
                pos.Y = height - 0.002f;

                if (k > 1.02 ) continue;

                GameObject obj;
                switch(UniversalRandom.GetInstance().Next(0, 3))
                {
                case 0:
                    obj = new OakTree(gameInstance);
                    obj.Scale = 3 + 3 * (float)UniversalRandom.GetInstance().NextDouble();
                    FireflyCandidates.Add(obj);
                    break;
                case 1:
                    obj = new BirchTree(gameInstance);
                    obj.Scale = 3 + 3 * (float)UniversalRandom.GetInstance().NextDouble();
                    FireflyCandidates.Add(obj);
                    break;
                default:
                    obj = new Stone(gameInstance);
                    obj.Scale = 0.5f + (float)(.25 * UniversalRandom.GetInstance().NextDouble());
                    break;
                }

                obj.Position = terrainScale * pos;
                obj.Rotation = new Vector3(0, MathHelper.Lerp(0, MathHelper.Pi * 2, (float)UniversalRandom.GetInstance().NextDouble()), 0);

                GraphicalObjects.Add(obj);
                ShadowCasterObjects.Add(obj);
            }

            for (int i = 0; i < FireflyCandidates.Count; i+=5)
            {
                ParticleEmitter emitter = new ParticleEmitter(fireflySystem, 80, FireflyCandidates[i].Position);
                emitter.Origin = FireflyCandidates[i].Position + Vector3.Up * 500;
                fireflyEmitter.Add(emitter);
            }

            #endregion

            //foreach (GameObject obj in GraphicalObjects)
            //{
            //    pointLights.Add(new PointLight(obj.Position + Vector3.Up * 500, new Vector3(0.7f, 0.7f, 0.7f), 450)
            //    {
            //        Model = pointLightModel
            //    });
            //}
            //GraphicalObjects.AddRange(pointLights);

            //List<FireObject> list = new List<FireObject>();
            //foreach (PointLight p in pointLights)
            //{
            //    FireObject obj = new FireObject(gameInstance, content, p.Position, p.Position + Vector3.Up * 10);
            //    list.Add(obj);

            //}
            //pointLights.AddRange(list);
            //GraphicalObjects.AddRange(list);

            #region Cameras

            var input = gameInstance.GetService<InputComponent>();

            gameInstance.GetService<CameraComponent>().AddCamera(new DebugCamera(new Vector3(-11800, 3000, -8200), input));
            Camera c;
            gameInstance.GetService<CameraComponent>().AddCamera(c = new ThirdPersonCamera(Car, input));
            gameInstance.GetService<CameraComponent>().CurrentCamera = c;

            #endregion

            #region DynamicEnvironment

            // TODO: CARMOVE
            environmentCubeMap = new RenderTargetCube(this.GraphicsDevice, 256, true, SurfaceFormat.Color, DepthFormat.Depth16);
            Car.EnvironmentMap = skyMap;

            #endregion

            #region PostProcess

            postProcessingComponent = new PostProcessingComponent(Game);
            Game.Components.Add(postProcessingComponent);

            postProcessTexture = new RenderTarget2D(GraphicsDevice,
                GraphicsDevice.Viewport.Width,
                GraphicsDevice.Viewport.Height,
                true, SurfaceFormat.Color, DepthFormat.Depth24);

            #endregion

            // Adding a prelighingrenderer as a service
            prelightingRenderer = new PrelightingRenderer(GraphicsDevice, content);
            Game.AddService(typeof(PrelightingRenderer), prelightingRenderer);

            #region ShadowMapEffect

            shadowMapEffect = content.Load<Effect>(@"Effects\ShadowMap");

            #endregion

            #region Gameplay Trigger Manager (with sample)

            /// <summary>
            /// Gets the triggermanager
            /// Add new PositionTrigger
            /// Hook up to listener => when hit, use the thunderBoltGenerator and spawn a flash
            /// Adds it to triggers.
            /// </summary>

            //var triggerManager = gameInstance.GetService<TriggerManager>();

            //int noOfCheckpoints = 10;
            //for (int i = 0; i < noOfCheckpoints; i++)
            //{
            //    var trigger = new PositionTrigger(raceTrack.CurveRasterization, (int)(((float)i / noOfCheckpoints) * raceTrack.CurveRasterization.Points.Count), true, true);
            //    string cp = "Checkpoint " + i;
            //    trigger.Triggered += (sender, e) =>
            //    {
            //        Console.WriteLine(cp);
            //    };
            //    triggerManager.Triggers.Add("checkpoint"+i, trigger);
            //}

            #endregion

            #region Game Mode
            if (gameInstance.GetService<ServerClient>().connected)
            {
                foreach (var player in gameInstance.GetService<ServerClient>().Players.Values)
                {
                    gameInstance.GetService<CarControlComponent>().AddCar(player, null, this);
                }
                var carList = gameInstance.GetService<CarControlComponent>().Cars.OrderBy(pc => pc.Key.ID).Select(pc => pc.Value).ToList();
                SetCarsAtStart(carList);
            }

            int cp = 6;
            if (gameModeChoice == GameModeChoice.SimpleRace)
                this.mode = new SimpleRaceMode(gameInstance, 3, cp, raceTrack, Car);
            else if (gameModeChoice == GameModeChoice.Multiplayer)
                this.mode = new MultiplayerRaceMode(gameInstance, 3, cp, raceTrack, Car);
            else
                throw new Exception("Stop choosing weird game modes");

            gameInstance.AddService(typeof(GameplayMode), mode);

            #endregion

            #region Checkpoint lights
            for (int i=0; i<cp; i++) {
                var point = raceTrack.GetCurveRasterization(cp).Points[i];

                var pl = new CheckpointLight(point.Position + 500 * Vector3.Up)
                {
                    Model = pointLightModel
                };
                pointLights.Add(pl);
                GraphicalObjects.Add(pl);

                #region Fire
                int halfnumberoffire = 5;

                for (int o = -halfnumberoffire + 1; o < halfnumberoffire; o++)
                {
                    Vector3 side = Vector3.Cross(Vector3.Normalize(raceTrack.Curve.GetPoint((i) / (float)cp + .001f) - point.Position), Vector3.Up);

                    var fire = new FireObject(content, fireSystem, fireSmokeSystem, point.Position + side * 100 * o -
                        Vector3.Up * 400 +
                        Vector3.Up * 650 * (float)Math.Cos(o/(float)halfnumberoffire), Vector3.Up * 10);
                    pointLights.Add(fire);
                    GraphicalObjects.Add(fire);
                }
                #endregion
            }
            #endregion

            #region BackgroundSound
            loopSoundManager.AddNewSound("forestambient");
            #endregion

            prelightingRenderer.GameObjects = GraphicalObjects;

            init = true;
        }
示例#47
0
        public override void Bind(Entity entity, Main main, bool creating = false)
        {
            Main.Config settings  = main.Settings;
            Transform   transform = entity.GetOrCreate <Transform>("Transform");

            entity.CannotSuspend = true;

            PlayerFactory.Instance = entity;

            this.SetMain(entity, main);

            FPSInput input = new FPSInput();

            input.EnabledWhenPaused = false;
            entity.Add("Input", input);

            Updater parkour = entity.Create <Updater>();
            Updater jumper  = entity.Create <Updater>();

            Player player = entity.GetOrCreate <Player>("Player");

            AnimatedModel firstPersonModel = entity.GetOrCreate <AnimatedModel>("FirstPersonModel");

            firstPersonModel.MapContent            = false;
            firstPersonModel.Serialize             = false;
            firstPersonModel.Filename.Value        = "Models\\joan-firstperson";
            firstPersonModel.CullBoundingBox.Value = false;

            AnimatedModel model = entity.GetOrCreate <AnimatedModel>("Model");

            model.MapContent            = false;
            model.Serialize             = false;
            model.Filename.Value        = "Models\\joan";
            model.CullBoundingBox.Value = false;

            AnimationController anim      = entity.GetOrCreate <AnimationController>("AnimationController");
            RotationController  rotation  = entity.GetOrCreate <RotationController>("Rotation");
            BlockPredictor      predictor = entity.GetOrCreate <BlockPredictor>("BlockPredictor");
            Jump          jump            = entity.GetOrCreate <Jump>("Jump");
            RollKickSlide rollKickSlide   = entity.GetOrCreate <RollKickSlide>("RollKickSlide");
            Vault         vault           = entity.GetOrCreate <Vault>("Vault");
            WallRun       wallRun         = entity.GetOrCreate <WallRun>("WallRun");
            VoxelTools    voxelTools      = entity.GetOrCreate <VoxelTools>("VoxelTools");
            Footsteps     footsteps       = entity.GetOrCreate <Footsteps>("Footsteps");
            FallDamage    fallDamage      = entity.GetOrCreate <FallDamage>("FallDamage");
            FPSCamera     fpsCamera       = entity.GetOrCreate <FPSCamera>("FPSCamera");

            fpsCamera.Enabled.Value = false;
            Rumble           rumble        = entity.GetOrCreate <Rumble>("Rumble");
            CameraController cameraControl = entity.GetOrCreate <CameraController>("CameraControl");

            Property <Vector3> floor = new Property <Vector3>();

            transform.Add(new Binding <Vector3>(floor, () => transform.Position + new Vector3(0, player.Character.Height * -0.5f, 0), transform.Position, player.Character.Height));
            Sound.AttachTracker(entity, floor);

            predictor.Add(new Binding <Vector3>(predictor.FootPosition, floor));
            predictor.Add(new Binding <Vector3>(predictor.LinearVelocity, player.Character.LinearVelocity));
            predictor.Add(new Binding <float>(predictor.Rotation, rotation.Rotation));
            predictor.Add(new Binding <float>(predictor.MaxSpeed, player.Character.MaxSpeed));
            predictor.Add(new Binding <float>(predictor.JumpSpeed, player.Character.JumpSpeed));
            predictor.Add(new Binding <bool>(predictor.IsSupported, player.Character.IsSupported));

            jump.Add(new Binding <bool>(jump.Crouched, player.Character.Crouched));
            jump.Add(new TwoWayBinding <bool>(player.Character.IsSupported, jump.IsSupported));
            jump.Add(new TwoWayBinding <bool>(player.Character.HasTraction, jump.HasTraction));
            jump.Add(new TwoWayBinding <Vector3>(player.Character.LinearVelocity, jump.LinearVelocity));
            jump.Add(new TwoWayBinding <BEPUphysics.Entities.Entity>(jump.SupportEntity, player.Character.SupportEntity));
            jump.Add(new TwoWayBinding <Vector3>(jump.SupportVelocity, player.Character.SupportVelocity));
            jump.Add(new Binding <Vector2>(jump.AbsoluteMovementDirection, player.Character.MovementDirection));
            jump.Add(new Binding <WallRun.State>(jump.WallRunState, wallRun.CurrentState));
            jump.Add(new Binding <float>(jump.Rotation, rotation.Rotation));
            jump.Add(new Binding <Vector3>(jump.Position, transform.Position));
            jump.Add(new Binding <Vector3>(jump.FloorPosition, floor));
            jump.Add(new Binding <float>(jump.MaxSpeed, player.Character.MaxSpeed));
            jump.Add(new Binding <float>(jump.JumpSpeed, player.Character.JumpSpeed));
            jump.Add(new Binding <float>(jump.Mass, player.Character.Mass));
            jump.Add(new Binding <float>(jump.LastRollKickEnded, rollKickSlide.LastRollKickEnded));
            jump.Add(new Binding <Voxel>(jump.WallRunMap, wallRun.WallRunVoxel));
            jump.Add(new Binding <Direction>(jump.WallDirection, wallRun.WallDirection));
            jump.Add(new CommandBinding <Voxel, Voxel.Coord, Direction>(jump.WalkedOn, footsteps.WalkedOn));
            jump.Add(new CommandBinding(jump.DeactivateWallRun, (Action)wallRun.Deactivate));
            jump.Add(new CommandBinding <float>(jump.FallDamage, fallDamage.ApplyJump));
            jump.Predictor = predictor;
            jump.Bind(model);
            jump.Add(new TwoWayBinding <Voxel>(wallRun.LastWallRunMap, jump.LastWallRunMap));
            jump.Add(new TwoWayBinding <Direction>(wallRun.LastWallDirection, jump.LastWallDirection));
            jump.Add(new TwoWayBinding <bool>(rollKickSlide.CanKick, jump.CanKick));
            jump.Add(new TwoWayBinding <float>(player.Character.LastSupportedSpeed, jump.LastSupportedSpeed));

            wallRun.Add(new Binding <bool>(wallRun.IsSwimming, player.Character.IsSwimming));
            wallRun.Add(new TwoWayBinding <Vector3>(player.Character.LinearVelocity, wallRun.LinearVelocity));
            wallRun.Add(new TwoWayBinding <Vector3>(transform.Position, wallRun.Position));
            wallRun.Add(new TwoWayBinding <bool>(player.Character.IsSupported, wallRun.IsSupported));
            wallRun.Add(new CommandBinding(wallRun.LockRotation, (Action)rotation.Lock));
            wallRun.Add(new CommandBinding <float>(wallRun.UpdateLockedRotation, rotation.UpdateLockedRotation));
            vault.Add(new CommandBinding(wallRun.Vault, delegate() { vault.Go(true); }));
            wallRun.Predictor = predictor;
            wallRun.Add(new Binding <float>(wallRun.Height, player.Character.Height));
            wallRun.Add(new Binding <float>(wallRun.JumpSpeed, player.Character.JumpSpeed));
            wallRun.Add(new Binding <float>(wallRun.MaxSpeed, player.Character.MaxSpeed));
            wallRun.Add(new TwoWayBinding <float>(rotation.Rotation, wallRun.Rotation));
            wallRun.Add(new TwoWayBinding <bool>(player.Character.AllowUncrouch, wallRun.AllowUncrouch));
            wallRun.Add(new TwoWayBinding <bool>(player.Character.HasTraction, wallRun.HasTraction));
            wallRun.Add(new Binding <float>(wallRun.LastWallJump, jump.LastWallJump));
            wallRun.Add(new Binding <float>(player.Character.LastSupportedSpeed, wallRun.LastSupportedSpeed));
            player.Add(new Binding <WallRun.State>(player.Character.WallRunState, wallRun.CurrentState));

            input.Bind(rollKickSlide.RollKickButton, settings.RollKick);
            rollKickSlide.Add(new Binding <bool>(rollKickSlide.EnableCrouch, player.EnableCrouch));
            rollKickSlide.Add(new Binding <float>(rollKickSlide.Rotation, rotation.Rotation));
            rollKickSlide.Add(new Binding <bool>(rollKickSlide.IsSwimming, player.Character.IsSwimming));
            rollKickSlide.Add(new Binding <bool>(rollKickSlide.IsSupported, player.Character.IsSupported));
            rollKickSlide.Add(new Binding <Vector3>(rollKickSlide.FloorPosition, floor));
            rollKickSlide.Add(new Binding <float>(rollKickSlide.Height, player.Character.Height));
            rollKickSlide.Add(new Binding <float>(rollKickSlide.MaxSpeed, player.Character.MaxSpeed));
            rollKickSlide.Add(new Binding <float>(rollKickSlide.JumpSpeed, player.Character.JumpSpeed));
            rollKickSlide.Add(new Binding <Vector3>(rollKickSlide.SupportVelocity, player.Character.SupportVelocity));
            rollKickSlide.Add(new TwoWayBinding <bool>(wallRun.EnableEnhancedWallRun, rollKickSlide.EnableEnhancedRollSlide));
            rollKickSlide.Add(new TwoWayBinding <bool>(player.Character.AllowUncrouch, rollKickSlide.AllowUncrouch));
            rollKickSlide.Add(new TwoWayBinding <bool>(player.Character.Crouched, rollKickSlide.Crouched));
            rollKickSlide.Add(new TwoWayBinding <bool>(player.Character.EnableWalking, rollKickSlide.EnableWalking));
            rollKickSlide.Add(new TwoWayBinding <Vector3>(player.Character.LinearVelocity, rollKickSlide.LinearVelocity));
            rollKickSlide.Add(new TwoWayBinding <Vector3>(transform.Position, rollKickSlide.Position));
            rollKickSlide.Predictor = predictor;
            rollKickSlide.Bind(model);
            rollKickSlide.VoxelTools = voxelTools;
            rollKickSlide.Add(new CommandBinding(rollKickSlide.DeactivateWallRun, (Action)wallRun.Deactivate));
            rollKickSlide.Add(new CommandBinding(rollKickSlide.Footstep, footsteps.Footstep));
            rollKickSlide.Add(new CommandBinding(rollKickSlide.LockRotation, (Action)rotation.Lock));
            SoundKiller.Add(entity, AK.EVENTS.STOP_PLAYER_SLIDE_LOOP);

            vault.Add(new Binding <Vector3>(vault.Position, transform.Position));
            vault.Add(new Binding <Vector3>(vault.FloorPosition, floor));
            vault.Add(new Binding <float>(vault.MaxSpeed, player.Character.MaxSpeed));
            vault.Add(new Binding <WallRun.State>(vault.WallRunState, wallRun.CurrentState));
            vault.Add(new CommandBinding(vault.LockRotation, (Action)rotation.Lock));
            vault.Add(new CommandBinding(vault.DeactivateWallRun, (Action)wallRun.Deactivate));
            vault.Add(new TwoWayBinding <float>(player.Character.LastSupportedSpeed, vault.LastSupportedSpeed));
            vault.Add(new CommandBinding <float>(vault.FallDamage, fallDamage.Apply));
            vault.Bind(model);
            vault.Predictor = predictor;
            vault.Add(new TwoWayBinding <float>(rotation.Rotation, vault.Rotation));
            vault.Add(new TwoWayBinding <bool>(player.Character.IsSupported, vault.IsSupported));
            vault.Add(new TwoWayBinding <bool>(player.Character.HasTraction, vault.HasTraction));
            vault.Add(new TwoWayBinding <Vector3>(player.Character.LinearVelocity, vault.LinearVelocity));
            vault.Add(new TwoWayBinding <bool>(player.Character.EnableWalking, vault.EnableWalking));
            vault.Add(new TwoWayBinding <bool>(player.Character.AllowUncrouch, vault.AllowUncrouch));
            vault.Add(new TwoWayBinding <bool>(player.Character.Crouched, vault.Crouched));
            vault.Add(new Binding <float>(vault.Radius, player.Character.Radius));

            rotation.Add(new TwoWayBinding <Vector2>(rotation.Mouse, input.Mouse));
            rotation.Add(new Binding <bool>(rotation.Rolling, rollKickSlide.Rolling));
            rotation.Add(new Binding <bool>(rotation.Kicking, rollKickSlide.Kicking));
            rotation.Add(new Binding <Vault.State>(rotation.VaultState, vault.CurrentState));
            rotation.Add(new Binding <WallRun.State>(rotation.WallRunState, wallRun.CurrentState));

            voxelTools.Add(new Binding <float>(voxelTools.Height, player.Character.Height));
            voxelTools.Add(new Binding <float>(voxelTools.SupportHeight, player.Character.SupportHeight));
            voxelTools.Add(new Binding <Vector3>(voxelTools.Position, transform.Position));

            anim.Add(new Binding <bool>(anim.IsSupported, player.Character.IsSupported));
            anim.Add(new Binding <WallRun.State>(anim.WallRunState, wallRun.CurrentState));
            anim.Add(new Binding <bool>(anim.EnableWalking, player.Character.EnableWalking));
            anim.Add(new Binding <bool>(anim.Crouched, player.Character.Crouched));
            anim.Add(new Binding <Vector3>(anim.LinearVelocity, player.Character.LinearVelocity));
            anim.Add(new Binding <Vector2>(anim.Movement, input.Movement));
            anim.Add(new Binding <Vector2>(anim.Mouse, input.Mouse));
            anim.Add(new Binding <float>(anim.Rotation, rotation.Rotation));
            anim.Add(new Binding <Voxel>(anim.WallRunMap, wallRun.WallRunVoxel));
            anim.Add(new Binding <Direction>(anim.WallDirection, wallRun.WallDirection));
            anim.Add(new Binding <bool>(anim.IsSwimming, player.Character.IsSwimming));
            anim.Add(new Binding <bool>(anim.Kicking, rollKickSlide.Kicking));
            anim.Add(new Binding <Vector3>(anim.SupportVelocity, player.Character.SupportVelocity));
            anim.Add
            (
                new Binding <bool>
                (
                    anim.EnableLean,
                    () => player.Character.EnableWalking.Value && player.Character.IsSupported.Value && input.Movement.Value.Y > 0.5f,
                    player.Character.EnableWalking, player.Character.IsSupported, input.Movement
                )
            );
            anim.Bind(model);

            // Camera control
            model.UpdateWorldTransforms();

            cameraControl.Add(new Binding <Vector2>(cameraControl.Mouse, input.Mouse));
            cameraControl.Add(new Binding <float>(cameraControl.Lean, x => x * (float)Math.PI * 0.05f, anim.Lean));
            cameraControl.Add(new Binding <Vector3>(cameraControl.LinearVelocity, player.Character.LinearVelocity));
            cameraControl.Add(new Binding <float>(cameraControl.MaxSpeed, player.Character.MaxSpeed));
            cameraControl.Add(new Binding <Matrix>(cameraControl.CameraBone, model.GetBoneTransform("Camera")));
            cameraControl.Add(new Binding <Matrix>(cameraControl.HeadBone, model.GetBoneTransform("ORG-head")));
            cameraControl.Add(new Binding <Matrix>(cameraControl.ModelTransform, model.Transform));
            cameraControl.Add(new Binding <float>(cameraControl.BaseCameraShakeAmount, () => MathHelper.Clamp((player.Character.LinearVelocity.Value.Length() - (player.Character.MaxSpeed * 2.5f)) / (player.Character.MaxSpeed * 4.0f), 0, 1), player.Character.LinearVelocity, player.Character.MaxSpeed));
            cameraControl.Offset = model.GetBoneTransform("Camera").Value.Translation - model.GetBoneTransform("ORG-head").Value.Translation;

            float heightOffset = 0.1f;

#if VR
            if (main.VR)
            {
                heightOffset = 0.4f;
            }
#endif
            cameraControl.Offset += new Vector3(0, heightOffset, 0);

            rumble.Add(new Binding <float>(rumble.CameraShake, cameraControl.TotalCameraShake));
            rumble.Add(new CommandBinding <float>(fallDamage.Rumble, rumble.Go));
            rumble.Add(new CommandBinding <float>(player.Rumble, rumble.Go));
            rumble.Add(new CommandBinding <float>(rollKickSlide.Rumble, rumble.Go));

            firstPersonModel.Add(new Binding <bool>(firstPersonModel.Enabled, x => !x, cameraControl.ThirdPerson));

            model.Add(new ChangeBinding <bool>(cameraControl.ThirdPerson, delegate(bool old, bool value)
            {
                if (value && !old)
                {
                    model.UnsupportedTechniques.Remove(Technique.Clip);
                    model.UnsupportedTechniques.Remove(Technique.Render);
                }
                else if (old && !value)
                {
                    model.UnsupportedTechniques.Add(Technique.Clip);
                    model.UnsupportedTechniques.Add(Technique.Render);
                }
            }));

            Lemma.Console.Console.AddConCommand(new Console.ConCommand("third_person", "Toggle third-person view (WARNING: EXPERIMENTAL)", delegate(Console.ConCommand.ArgCollection args)
            {
                cameraControl.ThirdPerson.Value = !cameraControl.ThirdPerson;
            }));
            entity.Add(new CommandBinding(entity.Delete, delegate()
            {
                Lemma.Console.Console.RemoveConCommand("third_person");
            }));

            // When rotation is locked, we want to make sure the player can't turn their head
            // 180 degrees from the direction they're facing

#if VR
            if (main.VR)
            {
                input.MaxY.Value = input.MinY.Value = 0;
            }
            else
#endif
            input.Add(new Binding <float>(input.MaxY, () => rotation.Locked ? (float)Math.PI * 0.3f : (float)Math.PI * 0.4f, rotation.Locked));

            input.Add(new Binding <float>(input.MinX, () => rotation.Locked ? rotation.Rotation + ((float)Math.PI * -0.4f) : 0.0f, rotation.Rotation, rotation.Locked));
            input.Add(new Binding <float>(input.MaxX, () => rotation.Locked ? rotation.Rotation + ((float)Math.PI * 0.4f) : 0.0f, rotation.Rotation, rotation.Locked));
            input.Add(new NotifyBinding(delegate() { input.Mouse.Changed(); }, rotation.Locked));             // Make sure the rotation locking takes effect even if the player doesn't move the mouse

            // Setup rendering properties

            model.Materials = firstPersonModel.Materials = new Model.Material[3];

            // Hoodie and shoes
            model.Materials[0] = new Model.Material
            {
                SpecularIntensity = 0.0f,
                SpecularPower     = 1.0f,
            };

            // Hands
            model.Materials[1] = new Model.Material
            {
                SpecularIntensity = 0.3f,
                SpecularPower     = 2.0f,
            };

            // Pants and skin
            model.Materials[2] = new Model.Material
            {
                SpecularIntensity = 0.5f,
                SpecularPower     = 20.0f,
            };

            firstPersonModel.Bind(model);

            // Third person model only gets rendered for shadows. No regular rendering or reflections.
            model.UnsupportedTechniques.Add(Technique.Clip);
            model.UnsupportedTechniques.Add(Technique.Render);

            // First-person model only used for regular rendering. No shadows or reflections.
            firstPersonModel.UnsupportedTechniques.Add(Technique.Shadow);
            firstPersonModel.UnsupportedTechniques.Add(Technique.Clip);

            // Build UI
            UIRenderer ui = new UIRenderer();
            ui.DrawOrder.Value   = -1;
            ui.EnabledWhenPaused = true;
            ui.EnabledInEditMode = false;
            entity.Add("UI", ui);

            input.Add(new Binding <float>(input.MouseSensitivity, settings.MouseSensitivity));
            input.Add(new Binding <bool>(input.InvertMouseX, settings.InvertMouseX));
            input.Add(new Binding <bool>(input.InvertMouseY, settings.InvertMouseY));
            input.Add(new Binding <PCInput.PCInputBinding>(input.LeftKey, settings.Left));
            input.Add(new Binding <PCInput.PCInputBinding>(input.RightKey, settings.Right));
            input.Add(new Binding <PCInput.PCInputBinding>(input.BackwardKey, settings.Backward));
            input.Add(new Binding <PCInput.PCInputBinding>(input.ForwardKey, settings.Forward));

            model.StartClip("Idle", 0, true, AnimatedModel.DefaultBlendTime);

            // Set up AI agent
            Agent agent = entity.GetOrCreate <Agent>();
            agent.Add(new TwoWayBinding <float>(player.Health, agent.Health));
            agent.Add(new Binding <Vector3>(agent.Position, () => transform.Position.Value + new Vector3(0, player.Character.Height * -0.5f, 0), transform.Position, player.Character.Height));
            agent.Add(new Binding <bool>(agent.Loud, () => player.Character.MovementDirection.Value.LengthSquared() > 0 && !player.Character.Crouched, player.Character.Crouched));

            // Blocks
            BlockCloud blockCloud = entity.GetOrCreate <BlockCloud>("BlockCloud");
            blockCloud.Scale.Value = 0.5f;
            blockCloud.Add(new Binding <Vector3>(blockCloud.Position, () => transform.Position.Value + new Vector3(0, player.Character.Height * 0.5f + player.Character.LinearVelocity.Value.Y, 0), transform.Position, player.Character.Height, player.Character.LinearVelocity));
            blockCloud.Blocks.ItemAdded += delegate(int index, Entity.Handle block)
            {
                Entity e = block.Target;
                if (e != null)
                {
                    e.Serialize = false;
                    PhysicsBlock.CancelPlayerCollisions(e.Get <PhysicsBlock>());
                }
            };
            predictor.Add(new Binding <Voxel.t>(predictor.BlockType, blockCloud.Type));

            PointLight blockLight = entity.Create <PointLight>();
            blockLight.Add(new Binding <Vector3>(blockLight.Position, blockCloud.AveragePosition));
            blockLight.Add(new Binding <bool, int>(blockLight.Enabled, x => x > 0, blockCloud.Blocks.Length));
            blockLight.Attenuation.Value = 30.0f;
            blockLight.Add(new Binding <Vector3, Voxel.t>(blockLight.Color, delegate(Voxel.t t)
            {
                switch (t)
                {
                case Voxel.t.GlowBlue:
                    return(new Vector3(0.7f, 0.7f, 0.9f));

                case Voxel.t.GlowYellow:
                    return(new Vector3(0.9f, 0.9f, 0.7f));

                default:
                    return(new Vector3(0.8f, 0.8f, 0.8f));
                }
            }, blockCloud.Type));

            blockLight.Add(new ChangeBinding <bool>(blockLight.Enabled, delegate(bool old, bool value)
            {
                if (!old && value)
                {
                    AkSoundEngine.PostEvent(AK.EVENTS.PLAY_MAGIC_CUBE_LOOP, entity);
                }
                else if (old && !value)
                {
                    AkSoundEngine.PostEvent(AK.EVENTS.STOP_MAGIC_CUBE_LOOP, entity);
                }
            }));
            if (blockLight.Enabled)
            {
                AkSoundEngine.PostEvent(AK.EVENTS.PLAY_MAGIC_CUBE_LOOP, entity);
            }

            // Death
            entity.Add(new CommandBinding(player.Die, blockCloud.Clear));
            entity.Add(new CommandBinding(player.Die, delegate()
            {
                Session.Recorder.Event(main, "Die");
                if (agent.Killed || Agent.Query(transform.Position, 0.0f, 10.0f, x => x != agent) != null)
                {
                    Session.Recorder.Event(main, "Killed");
                    AkSoundEngine.PostEvent(AK.EVENTS.PLAY_PLAYER_DEATH, entity);
                    main.Spawner.RespawnDistance = Spawner.KilledRespawnDistance;
                    main.Spawner.RespawnInterval = Spawner.KilledRespawnInterval;
                }
                entity.Add(new Animation(new Animation.Execute(entity.Delete)));
            }));

            player.EnabledInEditMode = false;

            player.Add(new TwoWayBinding <Matrix>(transform.Matrix, player.Character.Transform));

            model.Add(new Binding <Matrix>(model.Transform, delegate()
            {
                const float leanAmount = (float)Math.PI * 0.1f;
                return(Matrix.CreateTranslation(0, (player.Character.Height * -0.5f) - player.Character.SupportHeight, 0) * Matrix.CreateRotationZ(anim.Lean * leanAmount) * Matrix.CreateRotationY(rotation.Rotation) * transform.Matrix);
            }, transform.Matrix, rotation.Rotation, player.Character.Height, player.Character.SupportHeight, anim.Lean));

            firstPersonModel.Add(new Binding <Matrix>(firstPersonModel.Transform, model.Transform));
            firstPersonModel.Add(new Binding <Vector3>(firstPersonModel.Scale, model.Scale));

            WallRun.State[] footstepWallrunStates = new[]
            {
                WallRun.State.Left,
                WallRun.State.Right,
                WallRun.State.Straight,
                WallRun.State.None,
            };
            footsteps.Add(new Binding <bool>(footsteps.SoundEnabled, () => !player.Character.Crouched && footstepWallrunStates.Contains(wallRun.CurrentState) || (player.Character.IsSupported && player.Character.EnableWalking), player.Character.IsSupported, player.Character.EnableWalking, wallRun.CurrentState, player.Character.Crouched));
            footsteps.Add(new Binding <Vector3>(footsteps.Position, transform.Position));
            footsteps.Add(new Binding <float>(footsteps.Rotation, rotation.Rotation));
            footsteps.Add(new Binding <float>(footsteps.CharacterHeight, player.Character.Height));
            footsteps.Add(new Binding <float>(footsteps.SupportHeight, player.Character.SupportHeight));
            footsteps.Add(new Binding <bool>(footsteps.IsSupported, player.Character.IsSupported));
            footsteps.Add(new Binding <bool>(footsteps.IsSwimming, player.Character.IsSwimming));
            footsteps.Add(new CommandBinding <float>(footsteps.Damage, agent.Damage));
            footsteps.Add(new CommandBinding <Voxel, Voxel.Coord, Direction>(wallRun.WalkedOn, footsteps.WalkedOn));
            model.Trigger("Run", 0.16f, footsteps.Footstep);
            model.Trigger("Run", 0.58f, footsteps.Footstep);
            model.Trigger("WallRunLeft", 0.16f, footsteps.Footstep);
            model.Trigger("WallRunLeft", 0.58f, footsteps.Footstep);
            model.Trigger("WallRunRight", 0.16f, footsteps.Footstep);
            model.Trigger("WallRunRight", 0.58f, footsteps.Footstep);
            model.Trigger("WallRunStraight", 0.16f, footsteps.Footstep);
            model.Trigger("WallRunStraight", 0.58f, footsteps.Footstep);
            model.Trigger("TurnLeft", 0.15f, footsteps.Footstep);
            model.Trigger("TurnRight", 0.15f, footsteps.Footstep);
            model.Trigger("TopOut", 1.0f, new Command
            {
                Action = delegate()
                {
                    AkSoundEngine.PostEvent(AK.EVENTS.PLAY_PLAYER_GRUNT, entity);
                }
            });

            main.UI.IsMouseVisible.Value = false;

            SkinnedModel.Clip sprintAnimation = model["Sprint"], runAnimation = model["Run"];

            // Movement binding
            player.Add(new Binding <Vector2>(player.Character.MovementDirection, delegate()
            {
                Vector2 movement = input.Movement;
                if (movement.LengthSquared() == 0.0f)
                {
                    return(Vector2.Zero);
                }

                Matrix matrix = Matrix.CreateRotationY(rotation.Rotation);

                Vector2 forwardDir = new Vector2(matrix.Forward.X, matrix.Forward.Z);
                Vector2 rightDir   = new Vector2(matrix.Right.X, matrix.Right.Z);
                return(-(forwardDir * movement.Y) - (rightDir * movement.X));
            }, input.Movement, rotation.Rotation));

            player.Character.Crouched.Value      = true;
            player.Character.AllowUncrouch.Value = true;

            // Fall damage
            fallDamage.Add(new Binding <bool>(fallDamage.IsSupported, player.Character.IsSupported));
            fallDamage.Add(new TwoWayBinding <Vector3>(player.Character.LinearVelocity, fallDamage.LinearVelocity));
            fallDamage.Add(new TwoWayBinding <float>(player.Health, fallDamage.Health));
            fallDamage.Add(new CommandBinding <BEPUphysics.BroadPhaseEntries.Collidable, ContactCollection>(player.Character.Collided, fallDamage.Collided));
            fallDamage.Add(new TwoWayBinding <bool>(player.Character.EnableWalking, fallDamage.EnableWalking));
            fallDamage.Add(new TwoWayBinding <bool>(player.EnableMoves, fallDamage.EnableMoves));
            fallDamage.Add(new TwoWayBinding <bool>(fallDamage.Landing, rotation.Landing));
            fallDamage.Add(new CommandBinding(fallDamage.LockRotation, (Action)rotation.Lock));
            fallDamage.Add(new CommandBinding <float>(fallDamage.PhysicsDamage, agent.Damage));
            fallDamage.Bind(model);

            // Swim up
            input.Bind(player.Character.SwimUp, settings.Jump);

            float parkourTime = 0;
            float jumpTime = 0;
            jumper.Action = delegate(float dt)
            {
                if (player.EnableMoves && player.Character.EnableWalking &&
                    vault.CurrentState.Value == Vault.State.None &&
                    !rollKickSlide.Rolling && !rollKickSlide.Kicking &&
                    jumpTime < Player.SlowmoTime)
                {
                    if (jump.Go())
                    {
                        parkour.Enabled.Value = false;
                        jumper.Enabled.Value  = false;
                    }
                    jumpTime += dt;
                }
                else
                {
                    jumper.Enabled.Value = false;
                }
            };
            jumper.Add(new CommandBinding(jumper.Enable, delegate() { jumpTime = 0; }));
            jumper.Enabled.Value = false;
            entity.Add(jumper);

            // Jumping
            input.Bind(settings.Jump, PCInput.InputState.Down, delegate()
            {
                jumper.Enabled.Value = true;
            });

            input.Bind(settings.Jump, PCInput.InputState.Up, delegate()
            {
                jumper.Enabled.Value = false;
            });

            // Wall-run, vault, predictive
            parkour.Action = delegate(float dt)
            {
                if (player.EnableMoves &&
                    player.Character.EnableWalking &&
                    !(player.Character.Crouched && player.Character.IsSupported) &&
                    vault.CurrentState.Value == Vault.State.None &&
                    !rollKickSlide.Kicking &&
                    !rollKickSlide.Rolling &&
                    wallRun.CurrentState.Value == WallRun.State.None &&
                    parkourTime < Player.SlowmoTime)
                {
                    bool didSomething = false;

                    bool parkourBeganThisFrame = parkourTime == 0;
                    if (predictor.PossibilityCount > 0)
                    {
                        // In slow motion, prefer left and right wall-running
                        if (!(didSomething = wallRun.Activate(WallRun.State.Left, parkourBeganThisFrame)))
                        {
                            if (!(didSomething = wallRun.Activate(WallRun.State.Right, parkourBeganThisFrame)))
                            {
                                if (!(didSomething = vault.Go(parkourBeganThisFrame)))
                                {
                                    didSomething = wallRun.Activate(WallRun.State.Straight, parkourBeganThisFrame);
                                }
                            }
                        }
                    }
                    else
                    {
                        // In normal mode, prefer straight wall-running
                        if (!(didSomething = vault.Go(parkourBeganThisFrame)))
                        {
                            if (!(didSomething = wallRun.Activate(WallRun.State.Straight, parkourBeganThisFrame)))
                            {
                                if (!(didSomething = wallRun.Activate(WallRun.State.Left, parkourBeganThisFrame)))
                                {
                                    didSomething = wallRun.Activate(WallRun.State.Right, parkourBeganThisFrame);
                                }
                            }
                        }
                    }

                    if (didSomething)
                    {
                        jumper.Enabled.Value    = false;
                        player.SlowMotion.Value = false;
                        parkour.Enabled.Value   = false;
                    }
                    else if (parkourBeganThisFrame && player.Character.LinearVelocity.Value.Y > FallDamage.RollingDeathVelocity)
                    {
                        if (blockCloud.Blocks.Length > 0)
                        {
                            player.SlowMotion.Value = true;
                            predictor.ClearPossibilities();
                            predictor.PredictPlatforms();
                            predictor.PredictWalls();
                        }
                        else if (player.EnableSlowMotion)
                        {
                            player.SlowMotion.Value = true;
                        }
                    }

                    parkourTime += dt;
                }
                else
                {
                    parkour.Enabled.Value = false;
                }
            };
            parkour.Add(new CommandBinding(parkour.Enable, delegate()
            {
                parkourTime = 0;
            }));
            entity.Add(parkour);
            parkour.Enabled.Value = false;

            input.Bind(settings.Parkour, PCInput.InputState.Down, delegate()
            {
                parkour.Enabled.Value = true;
            });

            input.Bind(settings.Parkour, PCInput.InputState.Up, delegate()
            {
                parkour.Enabled.Value = false;
                wallRun.Deactivate();
                if (player.SlowMotion)
                {
                    player.SlowMotion.Value = false;
                }
            });

            input.Bind(settings.RollKick, PCInput.InputState.Down, delegate()
            {
                if (player.EnableMoves && player.Character.EnableWalking)
                {
                    rollKickSlide.Go();
                    parkour.Enabled.Value = false;
                    jumper.Enabled.Value  = false;
                }
            });

            input.Bind(settings.RollKick, PCInput.InputState.Up, delegate()
            {
                if (!rollKickSlide.Rolling && !rollKickSlide.Kicking)
                {
                    player.Character.AllowUncrouch.Value = true;
                }
            });

            // Special ability

            /*
             * input.Bind(settings.SpecialAbility, PCInput.InputState.Down, delegate()
             * {
             *      Voxel.GlobalRaycastResult hit = Voxel.GlobalRaycast(main.Camera.Position, main.Camera.Forward, main.Camera.FarPlaneDistance, null);
             *      if (hit.Voxel != null && hit.Voxel.GetType() != typeof(DynamicVoxel))
             *      {
             *              VoxelRip.Go(hit.Voxel, hit.Coordinate.Value, 7, delegate(List<DynamicVoxel> results)
             *              {
             *                      foreach (DynamicVoxel v in results)
             *                      {
             *                              v.IsAffectedByGravity.Value = false;
             *                              v.LinearVelocity.Value = hit.Voxel.GetAbsoluteVector(hit.Normal.GetVector()) * 7.0f
             + new Vector3((float)this.random.NextDouble() * 2.0f - 1.0f, (float)this.random.NextDouble() * 2.0f - 1.0f, (float)this.random.NextDouble() * 2.0f - 1.0f);
             +                      }
             +              });
             +      }
             + });
             */

            // Player data bindings

            entity.Add(new PostInitialization(delegate()
            {
                Entity dataEntity     = PlayerDataFactory.Instance;
                PlayerData playerData = dataEntity.Get <PlayerData>();

                // HACK. Overwriting the property rather than binding the two together. Oh well.
                // This is because I haven't written a two-way list binding.
                footsteps.RespawnLocations = playerData.RespawnLocations;

                // Bind player data properties
                entity.Add(new TwoWayBinding <float>(WorldFactory.Instance.Get <World>().CameraShakeAmount, cameraControl.CameraShakeAmount));
                entity.Add(new TwoWayBinding <bool>(playerData.EnableRoll, rollKickSlide.EnableRoll));
                entity.Add(new TwoWayBinding <bool>(playerData.EnableCrouch, player.EnableCrouch));
                entity.Add(new TwoWayBinding <bool>(playerData.EnableKick, rollKickSlide.EnableKick));
                entity.Add(new TwoWayBinding <bool>(playerData.EnableWallRun, wallRun.EnableWallRun));
                entity.Add(new TwoWayBinding <bool>(playerData.EnableWallRunHorizontal, wallRun.EnableWallRunHorizontal));
                entity.Add(new TwoWayBinding <bool>(playerData.EnableEnhancedWallRun, wallRun.EnableEnhancedWallRun));
                entity.Add(new TwoWayBinding <bool>(playerData.EnableMoves, player.EnableMoves));
                entity.Add(new TwoWayBinding <float>(playerData.MaxSpeed, player.Character.MaxSpeed));
                entity.Add(new Binding <bool>(fallDamage.PhoneOrNoteActive, () => playerData.PhoneActive || playerData.NoteActive, playerData.PhoneActive, playerData.NoteActive));

                if (playerData.CloudType.Value == Voxel.t.Empty)                 // This makes everything work if we spawn next to a power block socket
                {
                    entity.Add(new TwoWayBinding <Voxel.t>(blockCloud.Type, playerData.CloudType));
                }
                else
                {
                    entity.Add(new TwoWayBinding <Voxel.t>(playerData.CloudType, blockCloud.Type));
                }

                entity.Add(new TwoWayBinding <bool>(playerData.ThirdPerson, cameraControl.ThirdPerson));
                entity.Add(new TwoWayBinding <bool>(playerData.EnableSlowMotion, player.EnableSlowMotion));

                Phone phone = dataEntity.GetOrCreate <Phone>("Phone");

                entity.Add
                (
                    new Binding <bool>
                    (
                        phone.CanReceiveMessages,
                        () => player.Character.IsSupported && !player.Character.IsSwimming && !player.Character.Crouched,
                        player.Character.IsSupported,
                        player.Character.IsSwimming,
                        player.Character.Crouched
                    )
                );

                PhoneNote.Attach(main, entity, player, model, input, phone, player.Character.EnableWalking, playerData.PhoneActive, playerData.NoteActive);

                PlayerUI.Attach(main, entity, ui, player.Health, rotation.Rotation, playerData.NoteActive, playerData.PhoneActive);
            }));

            fpsCamera.Add(new Binding <Vector2>(fpsCamera.Mouse, input.Mouse));
            fpsCamera.Add(new Binding <Vector2>(fpsCamera.Movement, input.Movement));
            input.Bind(fpsCamera.SpeedMode, settings.Parkour);
            input.Bind(fpsCamera.Up, settings.Jump);
            fpsCamera.Add(new Binding <bool>(fpsCamera.Down, input.GetKey(Keys.LeftControl)));
            Lemma.Console.Console.AddConCommand(new ConCommand("noclip", "Toggle free camera mode", delegate(ConCommand.ArgCollection args)
            {
                bool freeCameraMode            = !fpsCamera.Enabled;
                fpsCamera.Enabled.Value        = freeCameraMode;
                cameraControl.Enabled.Value    = !freeCameraMode;
                firstPersonModel.Enabled.Value = !freeCameraMode;
                model.Enabled.Value            = !freeCameraMode;
                ui.Enabled.Value = !freeCameraMode;
                player.Character.EnableWalking.Value      = !freeCameraMode;
                player.EnableMoves.Value                  = !freeCameraMode;
                player.Character.Body.IsAffectedByGravity = !freeCameraMode;
                if (freeCameraMode)
                {
                    AkSoundEngine.PostEvent(AK.EVENTS.STOP_PLAYER_BREATHING_SOFT, entity);
                }
                else
                {
                    transform.Position.Value = main.Camera.Position;
                }
            }));

            entity.Add(new CommandBinding(entity.Delete, delegate()
            {
                Lemma.Console.Console.RemoveConCommand("noclip");
                if (fpsCamera.Enabled)                 // Movement is disabled. Re-enable it.
                {
                    player.Character.EnableWalking.Value = true;
                    player.EnableMoves.Value             = true;
                }
                PlayerFactory.Instance = null;
            }));
        }
示例#48
0
        // Constructor for bar graph.
        // To insert graph, call the constructor then use barGraph.Root to get the container to parent.
        public BarGraph(Compositor compositor,
                        string title,
                        string xAxisLabel,
                        string yAxisLabel,
                        float width,
                        float height,
                        double dpiX,
                        double dpiY,
                        WindowRenderTarget renderTarget,
                        double[] data                = null,
                        bool AnimationsOn            = true,
                        GraphBarStyle graphBarStyle  = GraphBarStyle.Single,
                        Windows.UI.Color[] barColors = null)
        {
            _compositor  = compositor;
            _graphWidth  = (float)(width * dpiX / 96.0);
            _graphHeight = (float)(height * dpiY / 96.0);

            _graphData = data;

            _graphTitle = title;
            _xAxisLabel = xAxisLabel;
            _yAxisLabel = yAxisLabel;

            _graphBarStyle  = graphBarStyle;
            _graphBarColors = barColors ?? new Windows.UI.Color[] { Colors.Blue };

            _textRenderTarget    = renderTarget;
            _textSceneColorBrush = new SolidColorBrush(renderTarget, _black);

            // Generate graph structure.
            GraphRoot = GenerateGraphStructure();

            _barRoot = _compositor.CreateContainerVisual();
            GraphRoot.Children.InsertAtBottom(_barRoot);

            // Ambient light
            _ambientLight       = _compositor.CreateAmbientLight();
            _ambientLight.Color = Colors.White;
            _ambientLight.Targets.Add(_mainContainer);

            // Spot light
            var innerConeColor = Colors.White;
            var outerConeColor = Colors.AntiqueWhite;

            _barOutlineLight = _compositor.CreateSpotLight();
            _barOutlineLight.InnerConeColor          = innerConeColor;
            _barOutlineLight.OuterConeColor          = outerConeColor;
            _barOutlineLight.CoordinateSpace         = _mainContainer;
            _barOutlineLight.InnerConeAngleInDegrees = 45;
            _barOutlineLight.OuterConeAngleInDegrees = 80;
            _barOutlineLight.Offset = new SnVector3(0, 0, 80);

            // Point light
            _barLight                 = _compositor.CreatePointLight();
            _barLight.Color           = outerConeColor;
            _barLight.CoordinateSpace = _mainContainer;
            _barLight.Intensity       = 0.5f;
            _barLight.Offset          = new SnVector3(0, 0, 120);

            // If data has been provided, initialize bars and animations; otherwise, leave graph empty.
            if (_graphData != null && _graphData.Length > 0)
            {
                _bars = new Bar[_graphData.Length];
                var bars = CreateBars(_graphData);
                AddBarsToTree(bars);
            }
        }
        public void CreateScene()
        {
            var canvas = Canvas.GetElementById(
                "game-window"
                );
            var engine = new Engine(
                canvas,
                true
                );
            var scene = new Scene(
                engine
                );
            var light0 = new PointLight(
                "Omni",
                new Vector3(
                    0,
                    100,
                    8
                    ),
                scene
                );
            var light1 = new HemisphericLight(
                "HemisphericLight",
                new Vector3(
                    0,
                    100,
                    8
                    ),
                scene
                );
            var advancedTexture = AdvancedDynamicTexture.CreateFullscreenUI("UI");
            var button          = Button.CreateSimpleButton(
                "button", "Click Me"
                );

            button.width      = "90%";
            button.height     = "90%";
            button.color      = "white";
            button.background = "green";
            button.onPointerClickObservable.add(async(Vector2WithInfo arg1, EventState state) =>
            {
                var x      = arg1.x.ToString();
                var fds    = arg1.buttonIndex;
                var vector = new Vector3(2.1m, 3.2m, 4.1m);
                Console.WriteLine(
                    $"Clicked: {arg1.x}, {arg1.y}"
                    );
                var xx        = vector.getClassName();
                ClickPosition = arg1;
                await InvokeAsync(StateHasChanged);
            });
            advancedTexture.addControl(
                button
                );
            var freeCamera = new FreeCamera(
                "FreeCamera",
                new Vector3(
                    0,
                    0,
                    -100
                    ),
                scene
                )
            {
                rotation = new Vector3(
                    0,
                    0,
                    0
                    ),
            };

            scene.activeCamera = freeCamera;
            freeCamera.attachControl(
                false
                );
            engine.runRenderLoop(
                new ActionCallback(
                    () => Task.Run(() => scene.render(true, false))
                    )
                );

            _engine = engine;
        }
示例#50
0
        public void InitSceneRefractions()
        {
            World world = new World();

            #region Shaders

            Shader black            = new Phong(new Vector4(0, 0, 0.5));
            Shader white            = new Phong(new Vector4(1, 1, 1));
            Shader unsaturatedGreen = new Phong(new Vector4(86 / 255.0, 116 / 255.0, 86 / 255.0));

            Shader checker = new Checker()
            {
                Shader0 = white, Shader1 = unsaturatedGreen, CubeSize = 2
            };

            Shader glass0 = new Phong(new Vector4(0.5, 0.1, 0.1), new Vector4(0.1, 0.1, 0.1))
            {
                RefractionFactor = 0.4, RefractionIndex = 1.00
            };
            Shader glass1 = new Phong(new Vector4(0.5, 0.1, 0.1), new Vector4(0.1, 0.1, 0.1))
            {
                RefractionFactor = 0.6, RefractionIndex = 1.05
            };
            Shader glass2 = new Phong(new Vector4(0.5, 0.1, 0.1), new Vector4(0.1, 0.1, 0.1))
            {
                RefractionFactor = 0.8, RefractionIndex = 1.10
            };
            Shader glass3 = new Phong(new Vector4(0.5, 0.1, 0.1), new Vector4(0.1, 0.1, 0.1))
            {
                RefractionFactor = 0.8, RefractionIndex = 1.15
            };
            Shader glass4 = new Phong(new Vector4(0.5, 0.1, 0.1), new Vector4(0.1, 0.1, 0.1))
            {
                RefractionFactor = 0.8, RefractionIndex = 1.20
            };
            Shader glass5 = new Phong(new Vector4(0.5, 0.1, 0.1), new Vector4(0.1, 0.1, 0.1))
            {
                RefractionFactor = 0.8, RefractionIndex = 1.25
            };

            Shader glass6 = new Phong(new Vector4(0.1, 0.5, 0.1), new Vector4(0.1, 0.1, 0.1))
            {
                RefractionFactor = 0.8, RefractionIndex = 1.40
            };

            #endregion

            #region Models

            world.Models.Add(new Plane(checker, new Vector4(0, 0, 0), new Vector4(0, 0, 1)));

            world.Models.Add(new Sphere(glass0, new Vector4(0, 0, 2), 1.2));
            world.Models.Add(new Sphere(glass1, new Vector4(0, 3, 2), 1.2));
            world.Models.Add(new Sphere(glass2, new Vector4(0, 6, 2), 1.2));
            world.Models.Add(new Sphere(glass3, new Vector4(0, 9, 2), 1.2));
            world.Models.Add(new Sphere(glass4, new Vector4(0, 12, 2), 1.2));
            world.Models.Add(new Sphere(glass5, new Vector4(0, 15, 2), 1.2));

            world.Models.Add(new AABB(glass6, new Vector4(3, 5, 0), new Vector4(4, 13, 8)));

            #endregion

            #region Lights

            PointLight point = new PointLight()
            {
                Origin               = new Vector4(5, 5, 15),
                Intensity            = 1.3,
                Range                = 80.0,
                LinearAttenuation    = 1,
                QuadraticAttenuation = 0
            };
            world.Lights.Add(point);

            #endregion

            camera = new Camera(700, 500)
            {
                Position = new Vector4(18, 15, 10),
                Target   = new Vector4(0, 8, 3),
                zNear    = 0.01,
                zFar     = 100.0,
                World    = world,
            };
            WriteValues();
        }
        public override void Bind(Entity entity, Main main, bool creating = false)
        {
            Transform transform = entity.GetOrCreate <Transform>("Transform");

            this.SetMain(entity, main);

            Sound.AttachTracker(entity);
            VoxelAttachable attachable = VoxelAttachable.MakeAttachable(entity, main, true, false);

            attachable.Offset.Value  = 1;
            attachable.Enabled.Value = true;

            PowerBlockSocket socket = entity.GetOrCreate <PowerBlockSocket>("PowerBlockSocket");

            socket.Add(new Binding <Voxel.Coord>(socket.Coord, attachable.Coord));
            socket.Add(new Binding <Entity.Handle>(socket.AttachedVoxel, attachable.AttachedVoxel));

            const float maxLightAttenuation = 15.0f;
            PointLight  light = entity.Create <PointLight>();

            light.Attenuation.Value = maxLightAttenuation;
            light.Add(new Binding <Vector3>(light.Position, transform.Position));
            light.Add(new Binding <Vector3, Voxel.t>(light.Color, delegate(Voxel.t t)
            {
                switch (t)
                {
                case Voxel.t.GlowBlue:
                    return(new Vector3(0.8f, 0.9f, 1.2f));

                case Voxel.t.GlowYellow:
                    return(new Vector3(1.2f, 1.2f, 0.8f));

                default:
                    return(Vector3.One);
                }
            }, socket.Type));
            light.Add(new Binding <bool>(light.Enabled, socket.Powered));

            PointLight animationLight = entity.Create <PointLight>();

            animationLight.Add(new Binding <Vector3>(animationLight.Position, light.Position));
            animationLight.Add(new Binding <Vector3>(animationLight.Color, light.Color));
            animationLight.Enabled.Value = false;

            PlayerTrigger trigger = entity.GetOrCreate <PlayerTrigger>("PlayerTrigger");

            trigger.Radius.Value = 7;
            trigger.Add(new Binding <Vector3>(trigger.Position, transform.Position));
            const float minimumChangeTime = 1.5f;
            float       lastChange        = -minimumChangeTime;

            trigger.Add(new CommandBinding(trigger.PlayerEntered, delegate()
            {
                if (main.TotalTime - lastChange > minimumChangeTime)
                {
                    BlockCloud cloud = PlayerFactory.Instance.Get <BlockCloud>();

                    bool changed    = false;
                    Voxel sockVoxel = attachable.AttachedVoxel.Value.Target.Get <Voxel>();
                    if (!socket.Powered && cloud.Type.Value == socket.Type.Value)
                    {
                        // Plug in to the socket
                        List <Voxel.Coord> coords = new List <Voxel.Coord>();
                        Queue <Voxel.Coord> queue = new Queue <Voxel.Coord>();
                        queue.Enqueue(sockVoxel.GetCoordinate(transform.Position));
                        while (queue.Count > 0)
                        {
                            Voxel.Coord c = queue.Dequeue();
                            coords.Add(c);
                            if (coords.Count >= cloud.Blocks.Length)
                            {
                                break;
                            }

                            Voxel.CoordSetCache.Add(c);
                            foreach (Direction adjacentDirection in DirectionExtensions.Directions)
                            {
                                Voxel.Coord adjacentCoord = c.Move(adjacentDirection);
                                if (!Voxel.CoordSetCache.Contains(adjacentCoord))
                                {
                                    Voxel.t adjacentID = sockVoxel[adjacentCoord].ID;
                                    if (adjacentID == Voxel.t.Empty)
                                    {
                                        queue.Enqueue(adjacentCoord);
                                    }
                                }
                            }
                        }
                        Voxel.CoordSetCache.Clear();

                        EffectBlockFactory factory = Factory.Get <EffectBlockFactory>();
                        int i = 0;
                        foreach (Entity block in cloud.Blocks)
                        {
                            Entity effectBlockEntity = factory.CreateAndBind(main);
                            Voxel.States.All[cloud.Type].ApplyToEffectBlock(effectBlockEntity.Get <ModelInstance>());
                            EffectBlock effectBlock      = effectBlockEntity.Get <EffectBlock>();
                            effectBlock.DoScale          = false;
                            Transform blockTransform     = block.Get <Transform>();
                            effectBlock.StartPosition    = blockTransform.Position;
                            effectBlock.StartOrientation = blockTransform.Quaternion;
                            effectBlock.TotalLifetime    = (i + 1) * 0.04f;
                            effectBlock.Setup(sockVoxel.Entity, coords[i], cloud.Type);
                            main.Add(effectBlockEntity);
                            block.Delete.Execute();
                            i++;
                        }
                        cloud.Blocks.Clear();
                        cloud.Type.Value     = Voxel.t.Empty;
                        socket.Powered.Value = true;
                        changed = true;
                    }
                    else if (socket.Powered && cloud.Type.Value == Voxel.t.Empty && !socket.PowerOnOnly)
                    {
                        // Pull blocks out of the socket
                        AkSoundEngine.PostEvent(AK.EVENTS.PLAY_MAGIC_CUBES, entity);
                        SceneryBlockFactory factory = Factory.Get <SceneryBlockFactory>();
                        Quaternion quat             = Quaternion.CreateFromRotationMatrix(sockVoxel.Transform);
                        cloud.Type.Value            = socket.Type;
                        List <Voxel.Coord> coords   = sockVoxel.GetContiguousByType(new[] { sockVoxel.GetBox(transform.Position) }).SelectMany(x => x.GetCoords()).ToList();
                        sockVoxel.Empty(coords, true);
                        sockVoxel.Regenerate();
                        ParticleSystem particles = ParticleSystem.Get(main, "WhiteShatter");
                        int count = 0;
                        foreach (Voxel.Coord c in coords)
                        {
                            Vector3 pos = sockVoxel.GetAbsolutePosition(c);
                            for (int j = 0; j < 20; j++)
                            {
                                Vector3 offset = new Vector3((float)this.random.NextDouble() - 0.5f, (float)this.random.NextDouble() - 0.5f, (float)this.random.NextDouble() - 0.5f);
                                particles.AddParticle(pos + offset, offset);
                            }
                            if (count < BlockCloud.TotalBlocks)
                            {
                                Entity block                    = factory.CreateAndBind(main);
                                Transform blockTransform        = block.Get <Transform>();
                                blockTransform.Position.Value   = pos;
                                blockTransform.Quaternion.Value = quat;
                                SceneryBlock sceneryBlock       = block.Get <SceneryBlock>();
                                sceneryBlock.Type.Value         = socket.Type;
                                sceneryBlock.Scale.Value        = 0.5f;
                                cloud.Blocks.Add(block);
                                main.Add(block);
                            }
                            count++;
                        }
                        socket.Powered.Value = false;
                        changed = true;
                    }

                    if (changed)
                    {
                        lastChange = main.TotalTime;
                        animationLight.Enabled.Value     = true;
                        animationLight.Attenuation.Value = 0.0f;
                        entity.Add(new Animation
                                   (
                                       new Animation.FloatMoveTo(animationLight.Attenuation, maxLightAttenuation, 0.25f),
                                       new Animation.FloatMoveTo(animationLight.Attenuation, 0.0f, 2.0f),
                                       new Animation.Set <bool>(animationLight.Enabled, false)
                                   ));
                    }
                }
            }));

            entity.Add("Type", socket.Type);
            entity.Add("Powered", socket.Powered, new PropertyEntry.EditorData {
                Readonly = true
            });
            entity.Add("PowerOnOnly", socket.PowerOnOnly);
            entity.Add("OnPowerOn", socket.OnPowerOn);
            entity.Add("OnPowerOff", socket.OnPowerOff);
            entity.Add("Enabled", trigger.Enabled);
            entity.Add("Enable", trigger.Enable);
            entity.Add("Disable", trigger.Disable);
        }
示例#52
0
        public void InitSceneReflections()
        {
            World world = new World();

            #region Shaders

            Shader red              = new Phong(new Vector4(0.5, 0, 0));
            Shader white            = new Phong(new Vector4(1, 1, 1));
            Shader blue             = new Phong(new Vector4(0, 0, 1));
            Shader lightBlue        = new Phong(new Vector4(91 / 255.0, 142 / 255.0, 210 / 255.0));
            Shader unsaturatedGreen = new Phong(new Vector4(86 / 255.0, 116 / 255.0, 86 / 255.0));
            Shader brown            = new Phong(new Vector4(80 / 255.0, 48 / 255.0, 34 / 255.0));
            Shader lightBrown       = new Phong(new Vector4(195 / 255.0, 152 / 255.0, 101 / 255.0));

            Shader checker = new Checker()
            {
                Shader0  = unsaturatedGreen,
                Shader1  = white,
                CubeSize = 2
            };

            Shader mirror = new Phong(new Vector4(0.0, 0.0, 0.0), new Vector4(0.1, 0.1, 0.1))
            {
                ReflectionFactor = 0.98, RefractionFactor = 0.0, RefractionIndex = 1
            };

            #endregion

            #region Models

            world.Models.Add(new Plane(mirror, new Vector4(-20, 0, 0), new Vector4(1, 0, 0)));
            world.Models.Add(new Plane(mirror, new Vector4(20, 0, 0), new Vector4(-1, 0, 0)));
            world.Models.Add(new Plane(mirror, new Vector4(0, -20, 0), new Vector4(0, -1, 0)));
            world.Models.Add(new Plane(mirror, new Vector4(0, 20, 0), new Vector4(0, 1, 0)));
            world.Models.Add(new Plane(checker, new Vector4(0, 0, 0), new Vector4(0, 0, 1)));

            world.Models.Add(new Sphere(lightBlue, new Vector4(0, 0, 2), 1));

            #endregion

            #region Lights

            PointLight point = new PointLight()
            {
                Origin               = new Vector4(0, 0, 10),
                Intensity            = 0.9,
                Range                = 20.0,
                LinearAttenuation    = 1,
                QuadraticAttenuation = 0
            };
            world.Lights.Add(point);

            #endregion

            camera = new Camera(700, 500)
            {
                Position = new Vector4(18, 10, 7),
                Target   = new Vector4(0, 1, 4),
                World    = world,
                zNear    = 0.01,
                zFar     = 100.0,
            };

            WriteValues();
        }
示例#53
0
        private void InitializeLights(int lightCount)
        {
            lights = new PointLight[lightCount];
            Random r = new Random();

            for (int i = 0; i < lights.Length; i++)
            {
                lights[i] = new PointLight(new Vector3(r.Next(-10, 10), r.Next(-20,20), r.Next(-20, -10)),
                                           new Color((float)r.NextDouble(), (float)r.NextDouble(), (float)r.NextDouble(), 1));

            }
        }
示例#54
0
        protected override Canvas Render(CameraRenderOptions options)
        {
            // Patterns
            var checkerPattern = new CheckerPattern(
                new StripePattern(
                    Colors.LightGray,
                    Colors.Gray,
                    Matrix4x4.CreateScaling(0.25, 0.25, 0.25).RotateY(-Math.PI / 8)),
                new GradientPattern(new Color(1, 0.75, 0.75), new Color(1, 0.5, 0.5)),
                Matrix4x4.CreateScaling(0.4, 0.4, 0.4));

            var blendedPattern = new BlendedPattern(
                new StripePattern(new Color(0.9, 1, 0.9), new Color(0, 1, 0), Matrix4x4.CreateRotationY(Math.PI / 2)),
                new StripePattern(new Color(0.9, 1, 0.9), new Color(0, 1, 0)),
                0.5);

            var stripePattern = new StripePattern(
                new GradientPattern(new Color(0.8, 0.8, 1), Colors.Blue),
                new GradientPattern(Colors.Blue, new Color(0.8, 0.8, 1)),
                Matrix4x4.CreateScaling(0.25, 0.25, 0.25)
                .RotateZ(-Math.PI / 4)
                .RotateY(-Math.PI / 6)
                .Translate(0.4, 0, 0));

            var gradientPattern = new RadialGradientPattern(
                Colors.Green,
                Colors.Yellow,
                Matrix4x4.CreateScaling(0.25, 0.25, 0.25).RotateX(-Math.PI / 2));

            var ringPattern = new RingPattern(
                Colors.Red,
                Colors.White,
                Matrix4x4.CreateScaling(0.15, 0.15, 0.15).RotateX(-Math.PI / 2));

            // Shapes
            var floor = new Plane(
                "Floor",
                Matrix4x4.CreateRotationY(Math.PI / 4),
                new Material(pattern: blendedPattern, specular: 0));

            var backWall = new Plane(
                "BackWall",
                Matrix4x4.CreateRotationX(Math.PI / 2).Translate(0, 0, 5),
                new Material(pattern: checkerPattern));

            var left = new Sphere(
                "Left",
                Matrix4x4.CreateScaling(0.33, 0.33, 0.33).Translate(-2, 0.33, -0.75),
                new Material(pattern: ringPattern, diffuse: 0.7, specular: 0.3));

            var middle = new Sphere(
                "Middle",
                Matrix4x4.CreateTranslation(-0.5, 1, 0.5),
                new Material(pattern: stripePattern, diffuse: 0.7, specular: 0.3));

            var right = new Sphere(
                "Right",
                Matrix4x4.CreateScaling(0.5, 0.5, 0.5).Translate(1.5, 0.5, -0.5),
                new Material(pattern: gradientPattern, diffuse: 0.7, specular: 0.3));

            var light = new PointLight(new Point(-10, 10, -10), Colors.White);
            var world = new World(light, floor, backWall, left, middle, right);

            var cameraTransform = Matrix4x4.CreateLookAt(new Point(0, 1.5, -5), new Point(0, 1, 0), Vector.UnitY);
            var camera          = new Camera(CanvasWidth, CanvasHeight, Math.PI / 3, cameraTransform);

            Canvas canvas = camera.Render(world, options);

            return(canvas);
        }
示例#55
0
文件: MyScene.cs 项目: kantorn/test1
        protected override void CreateScene()
        {
            RenderManager.BackgroundColor = Color.CornflowerBlue;

            //ViewCamera camera = new ViewCamera("MainCamera", new Vector3(0, 2f, -2.5f), new Vector3(0, 1, 0));
            camera = new FreeCamera("freeCamera", new Vector3(0, 2f, -3.5f), Vector3.UnitY * 0.9f)
            {
                Speed = 5
            };
            Entity animatedModel = new Entity("Isis")
                .AddComponent(new Transform3D())
                .AddComponent(new BoxCollider())
                .AddComponent(new SkinnedModel("Content/isis.wpk"))
                .AddComponent(new MaterialsMap(new BasicMaterial("Content/isis-difuse.wpk") { ReferenceAlpha = 0.5f }))
                .AddComponent(new Animation3D("Content/isis-animations.wpk"))
                .AddComponent(new SkinnedModelRenderer())
                .AddComponent(new TimBehavior());

            anim = animatedModel.FindComponent<Animation3D>();
            EntityManager.Add(animatedModel);

            Entity floor = new Entity("Floor")
                       .AddComponent(new Transform3D())
                       .AddComponent(new BoxCollider())
                       .AddComponent(new Model("Content/Model/floor.wpk"))
                       .AddComponent(new MaterialsMap(new BasicMaterial("Content/Texture/floorNight.wpk")))
                       .AddComponent(new ModelRenderer());

            //Suddenly columns! Thousand of them!  (4x2 columns)

            EntityManager.Add(floor);

            //Suddenly columns! Thousand of them!  (4x2 columns)
            /*int nColumns = 0;
            for (int i = 0; i < 4; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    Entity column = new Entity("column_" + nColumns++)
                        .AddComponent(new Transform3D() { Position = new Vector3(4 - (8 * j), 0, 8 * i) })
                       .AddComponent(new Model("Content/Model/floor.wpk"))
                        .AddComponent(new ModelRenderer())
                       .AddComponent(new MaterialsMap(new BasicMaterial("Content/Texture/floorNight.wpk")));

                    EntityManager.Add(column);
                    Entity fern = new Entity("Fern" + nColumns++)
                             .AddComponent(new Transform3D() { Position = new Vector3(2f - (8 * j), 0f, 2.5f*i) })
                             .AddComponent(new BoxCollider())
                             .AddComponent(new Model("Content/Model/fern.wpk"))
                             .AddComponent(new MaterialsMap(new BasicMaterial("Content/Texture/FernTexture.wpk") { ReferenceAlpha = 0.5f }))
                             .AddComponent(new ModelRenderer());

                    EntityManager.Add(fern);
                }
            }*/

            camera.Entity.AddComponent(new CameraBehavior(EntityManager.Find("Isis")));

            //Add some light!
            PointLight light = new PointLight("light", Vector3.Zero)
            {
                Attenuation = 75,
                Color = new Color(1, 0.6f, 0.4f),
                IsVisible = true
            };
            light.Entity.AddComponent(new FollowCameraBehavior(camera.Entity));
            light.Entity.AddComponent(new TorchLightBehaviour());

            EntityManager.Add(light);
            EntityManager.Add(camera);
            RenderManager.SetActiveCamera(camera.Entity);
        }
示例#56
0
        void InitLight()
        {
            RenderManagerAccessor.Instance.ClearDirectionalLight();

            DirectionalLight0.Direction = -Vector3.One;
            DirectionalLight0.Color = new Color(3.0f, 3.0f, 3.0f, 1.0f);
            RenderManagerAccessor.Instance.AddDirectionalLight(DirectionalLight0);

            RenderManagerAccessor.Instance.ClearPointLight();

            for (var i = 0; i < 128; ++i)
            {
                PointLightPositions.Add(new Vector3(Rand.NextFloat(-400.0f, 400.0f), Rand.NextFloat(0.0f, 20.0f), Rand.NextFloat(-400.0f, 400.0f)));

                var light = new PointLight()
                {
                    Position = PointLightPositions[i],// + Player.Transform.Translation,
                    Color = new Color(Rand.NextFloat(1.0f, 50.0f), Rand.NextFloat(1.0f, 50.0f), Rand.NextFloat(1.0f, 50.0f)),
                    AttenuationBegin = Rand.NextFloat(0.0f, 10.0f),
                    AttenuationEnd = Rand.NextFloat(20.0f, 30.0f),
                };
                PointLights.Add(light);
            }

            PointLights.ForEach((light) => { RenderManagerAccessor.Instance.AddPointLight(light); });
        }
示例#57
0
 public void AddPointLight(PointLight light)
 {
     lights.Add(light);
 }
示例#58
0
文件: frmMain.cs 项目: zulis/Sandbox
        private void tvObjects_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            var type = Helpers.GetObjectType(e.Node.FullPath);
            var fullPath = Path.Combine(Application.StartupPath, e.Node.FullPath);
            var position = core.Camera.GetFrontPosition(10.0f);

            position.x = (float)Math.Round(position.x);
            position.y = (float)Math.Round(position.y);
            position.z = (float)Math.Round(position.z);

            bool skyBoxExists, skySphereExists = false;
            switch (type)
            {
                case Helpers.ObjectType.DirectionalLight:
                    var sunId = -1;
                    sunId = core.LightEngine.GetLightFromName(Helpers.SUN);
                    if (sunId == -1)
                    {
                        var directionalLight = new DirectionalLight(core, position);
                        directionalLight.Update();
                        selectedObject = directionalLight;
                        AddToSceneTreeView(sceneLightsNode, directionalLight);
                    }
                    else
                    {
                        MessageBox.Show("There should be only one directional light.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    break;
                case Helpers.ObjectType.PointLight:
                    var pointLight = new PointLight(core, position);
                    pointLight.Update();
                    selectedObject = pointLight;
                    AddToSceneTreeView(sceneLightsNode, pointLight);
                    break;
                case Helpers.ObjectType.SpotLight:
                    MessageBox.Show("Not implemented.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
                case Helpers.ObjectType.StaticMesh:
                    var mesh = new Engine.Mesh(core, Settings, fullPath)
                                   {
                                       Position = new VECTOR3D(position.x, position.y, position.z)
                                   };
                    mesh.Update();
                    selectedObject = mesh;
                    AddToSceneTreeView(sceneObjectsNode, mesh);
                    break;
                case Helpers.ObjectType.AnimatedMesh:
                    var animatedMesh = new Engine.Mesh(core, Settings, fullPath)
                    {
                        Position = new VECTOR3D(position.x, position.y, position.z)
                    };
                    animatedMesh.Update();
                    selectedObject = animatedMesh;
                    AddToSceneTreeView(sceneObjectsNode, animatedMesh);
                    break;
                case Helpers.ObjectType.Sound:
                    var sound = new Sound(core, fullPath);
                    sound.Update();
                    selectedObject = sound;
                    AddToSceneTreeView(sceneSoundsNode, sound);
                    break;
                case Helpers.ObjectType.SkyBox:
                    skyBoxExists = core.AllObjects.FindLast(o => o.GetType() == typeof(SkyBox)) == null ? false : true;
                    if (skyBoxExists)
                        break;
                    skySphereExists = core.AllObjects.FindLast(o => o.GetType() == typeof(SkySphere)) == null ? false : true;
                    if (skySphereExists)
                    {
                        if (MessageBox.Show("This will remove existing sky sphere. Remove?", "Remove sky sphere?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.OK)
                        {
                            selectedObject = core.AllObjects.FindLast(o => o.GetType() == typeof(SkySphere));
                            RemoveSelectedObject();
                        }
                        else
                            break;
                    }
                    var skyBox = new SkyBox(core);
                    skyBox.Update();
                    AddToSceneTreeView(sceneSkyNode, skyBox);
                    selectedObject = skyBox;
                    break;
                case Helpers.ObjectType.SkySphere:
                    skySphereExists = core.AllObjects.FindLast(o => o.GetType() == typeof(SkySphere)) == null ? false : true;
                    if (skySphereExists)
                        break;
                    skyBoxExists = core.AllObjects.FindLast(o => o.GetType() == typeof(SkyBox)) == null ? false : true;
                    if (skyBoxExists)
                    {
                        if (MessageBox.Show("This will remove existing sky box. Remove?", "Remove sky box?", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.OK)
                        {
                            selectedObject = core.AllObjects.FindLast(o => o.GetType() == typeof(SkyBox));
                            RemoveSelectedObject();
                        }
                        else
                            break;
                    }
                    var skySphere = new SkySphere(core);
                    skySphere.Update();
                    AddToSceneTreeView(sceneSkyNode, skySphere);
                    selectedObject = skySphere;
                    break;
                case Helpers.ObjectType.Water:
                    var water = new Water(core);
                    selectedObject = water;
                    AddToSceneTreeView(sceneWaterNode, water);
                    break;
                case Helpers.ObjectType.Landscape:
                    var landscape = new Landscape(core)
                    {
                        Position = new VECTOR3D(position.x, position.y, position.z)
                    };
                    landscape.Update();
                    selectedObject = landscape;
                    AddToSceneTreeView(sceneLandscapeNode, landscape);
                    break;
                case Helpers.ObjectType.Trigger:
                    var trigger = new Trigger(core)
                    {
                        Position = new VECTOR3D(position.x, position.y, position.z)
                    };
                    trigger.Update();
                    selectedObject = trigger;
                    AddToSceneTreeView(sceneTriggersNode, trigger);
                    break;
                case Helpers.ObjectType.Particle:
                    var particle = new Particle(core, fullPath);
                    particle.Update();
                    selectedObject = particle;
                    AddToSceneTreeView(sceneParticlesNode, particle);
                    break;
                case Helpers.ObjectType.NotDetected:
                    RunRegisteredExtension(fullPath);
                    break;
            }

            propertyGrid.SelectedObject = selectedObject;

            Cursor = Cursors.Default;
        }
示例#59
0
文件: Game.cs 项目: noatom/Samples
        protected override void CreateScene()
        {
            RenderManager.BackgroundColor = Color.Black;
            //RenderManager.DebugLines = true;

            FreeCamera camera = new FreeCamera("MainCamera", new Vector3(0, 4, 12), new Vector3(0, 4, 0)) { Speed = 5 };
            EntityManager.Add(camera.Entity);

            RenderManager.SetActiveCamera(camera.Entity);

            PointLight Light0 = new PointLight("Light0", new Vector3(-5, 8, 10))
            {
                Color = Color.White,
                Attenuation = 20,
            };

            Light0.Entity.AddComponent(new MoveBehavior() { Speed = 0.2f });

            EntityManager.Add(Light0.Entity);

            float value = 0.0f;
            Color c = new Color(value, value, value, 1);

            Entity cubeModel = new Entity("Cube")
                .AddComponent(new Transform3D() { Scale = new Vector3(6) })
                //.AddComponent(new Spinner() { IncreaseY = 0.02f })
                .AddComponent(new BoxCollider())
                .AddComponent(new Model("Content/Cube.wpk"))
                .AddComponent(new MaterialsMap(new NormalMappingMaterial("Content/floor.wpk", "Content/floor_normal_spec.wpk", "Content/lightmap.wpk") { AmbientColor = c }))  // "Content/lightmap.wpk"
                .AddComponent(new ModelRenderer());

            EntityManager.Add(cubeModel);

            #region UI
            Slider slider1 = new Slider()
            {
                Margin = new Thickness(10, 90, 0, 0),
                Width = 500,
                Minimum = 4,
                Maximum = 40,
                Value = 30
            };

            slider1.RealTimeValueChanged += (s, e) =>
            {
                var entity = EntityManager.Find("Light0");
                var component = entity.FindComponent<PointLightProperties>();
                component.Attenuation = e.NewValue;
            };

            EntityManager.Add(slider1);

            Slider slider2 = new Slider()
            {
                Margin = new Thickness(10, 140, 0, 0),
                Width = 500,
                Minimum = 1,
                Maximum = 100
            };

            slider2.RealTimeValueChanged += (s, e) =>
            {
                var entity = EntityManager.Find("Cube");
                var component = entity.FindComponent<MaterialsMap>();
                var material = (component.DefaultMaterial as NormalMappingMaterial);

                float v = (float)e.NewValue / 100.0f;
                Color c1 = new Color(v, v, v, 1);
                material.AmbientColor = c1;
            };

            EntityManager.Add(slider2);

            ToggleSwitch lightmapEnabled = new ToggleSwitch()
            {
                Margin = new Thickness(10, 10, 0, 0),
                IsOn = true,
                OnText = "LightMap On",
                OffText = "LightMap Off",
            };

            lightmapEnabled.Toggled += (s, e) =>
            {
                var entity = EntityManager.Find("Cube");
                var component = entity.FindComponent<MaterialsMap>();
                var material = (component.DefaultMaterial as NormalMappingMaterial);
                material.LightMapEnabled = !material.LightMapEnabled;
            };

            EntityManager.Add(lightmapEnabled);

            ToggleSwitch textureEnabled = new ToggleSwitch()
            {
                Margin = new Thickness(10, 40, 0, 0),
                IsOn = true,
                OnText = "Texture On",
                OffText = "Texture Off"
            };

            textureEnabled.Toggled += (s, o) =>
            {
                var entity = EntityManager.Find("Cube");
                var component = entity.FindComponent<MaterialsMap>();
                var material = (component.DefaultMaterial as NormalMappingMaterial);
                material.TextureEnabled = !material.TextureEnabled;
            };

            EntityManager.Add(textureEnabled);

            ToggleSwitch normalMapEnabled = new ToggleSwitch()
            {
                Margin = new Thickness(300, 10, 0, 0),
                IsOn = true,
                OnText = "NormalMap On",
                OffText = "NormalMap Off"
            };

            normalMapEnabled.Toggled += (s, o) =>
            {
                var entity = EntityManager.Find("Cube");
                var component = entity.FindComponent<MaterialsMap>();
                var material = (component.DefaultMaterial as NormalMappingMaterial);
                material.NormalMappingEnabled = !material.NormalMappingEnabled;
            };

            EntityManager.Add(normalMapEnabled);
            #endregion
        }
示例#60
0
        /// <summary>
        /// Create scene environment:
        /// - Projectiles, Explosions
        /// - Asteroid field,
        /// - Starfield
        /// </summary>
        private void CreateEnvironment()
        {
            // Projectiles
            Entity blueProjectiles = new Entity("Projectiles")
                .AddComponent(new ProjectileManager())
                .AddComponent(new ProjectilesRenderer())
                .AddComponent(new MaterialsMap(new BasicMaterial("Content/Textures/Blaster.png", DefaultLayers.Additive)));
            this.EntityManager.Add(blueProjectiles);

            // Explosion
            ExplosionDecorator explosion = new ExplosionDecorator("explosion", 2556);
            explosion.Transform3D.Position = new Vector3(-1109.993f, 0.437f, -3785.457f);
            this.EntityManager.Add(explosion.Entity);

            // Add asteroidfield
            var asteroidField = new AsteroidFieldDecorator("asteroidField", new Vector3(2000, 2000, 0));
            this.EntityManager.Add(asteroidField);

            // Add starfield
            var starField = new StarfieldDecorator("starfield");
            this.EntityManager.Add(starField);

            Dictionary<string, Material> materials = new Dictionary<string, Material>()
            {
                {
                    "Planet",
                    new BasicMaterial("Content/Textures/planet.png", typeof(PlanetLayer))
                },
                {
                    "BackSun",
                    new BasicMaterial("Content/Textures/StarShine.png", typeof(StarfieldLayer)){DiffuseColor = Color.White * 0.8f}
                },
                {
                    "FrontSun",
                    new BasicMaterial("Content/Textures/StarShine.png", DefaultLayers.Additive){DiffuseColor = Color.White * 0.4f}
                }
            };

            // Add background planet
            var planet = new Entity("planet")
            .AddComponent(new Transform3D())
            .AddComponent(new Model("Content/Models/Planet.FBX"))
            .AddComponent(new ModelRenderer())
            .AddComponent(new MaterialsMap(materials))
            .AddComponent(new FollowCameraBehavior())
            ;
            this.EntityManager.Add(planet);

            PointLight light = new PointLight("light", new Vector3(-30000, 17000, -15000))
            {
                Attenuation = 1900000,
                IsVisible = true,
                Color = Color.White
            };

            this.EntityManager.Add(light);
        }