Exemplo n.º 1
0
			protected override void OnRenderToolStripBackground(ToolStripRenderEventArgs e) {
				GraphicsHelper helper = new GraphicsHelper(e.Graphics);
				Rectangle bounds = new Rectangle(-1, -1, e.AffectedBounds.Width + 1, e.AffectedBounds.Height + 1);

				//helper.Clear(UColor.Argb(255, 0, 0, 0));
				helper.Gradient(UColor.Rgb(0x30, 0x30, 0x30), UColor.Rgb(0x1D, 0x1D, 0x1D), bounds, 90);
			}
Exemplo n.º 2
0
			protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) {
				GraphicsHelper helper = new GraphicsHelper(e.Graphics);
				ToolStripButton button = e.Item as ToolStripButton;
				Rectangle bounds = new Rectangle(0, 0, e.Item.Width - 1, e.Item.Height - 1);

				if (e.Item.Selected) {
					helper.RoundedGradient(UColor.Rgb(0x06, 0x88, 0xB8), UColor.Rgb(0x06, 0x88, 0xB8), bounds, 90, 2);
				}
			}
Exemplo n.º 3
0
		public void OnPaintItem(PaintEventArgs e, MenuBarItem item) {
			GraphicsHelper helper = new GraphicsHelper(e.Graphics);
			const int radius = 3;
			Rectangle bound = item.Bound;
			helper.RoundedGradient(UColor.Rgb(0x4d, 0x9f, 0xcf), UColor.Rgb(0x15, 0x69, 0x97), item.Bound, 90, radius);
			helper.Gradient(UColor.Blend(130, UColor.White), UColor.Blend(70, UColor.White), new Rectangle(item.Bound.X, item.Bound.Y + 1, 1, item.Bound.Height - radius), 90);
			helper.Gradient(UColor.Blend(130, UColor.White), UColor.Blend(70, UColor.White), new Rectangle(item.Bound.X + item.Bound.Width - radius + 2, item.Bound.Y + 1, 1, item.Bound.Height - radius), 90);
			helper.RoundedOutline(UColor.Rgb(0x18, 0x18, 0x18), item.Bound, radius);
			helper.Line(UColor.White, bound.X + radius, bound.Y + bound.Height - 1, bound.Width - radius, bound.Y + bound.Height-1);
		}
Exemplo n.º 4
0
		public void OnPaintBarBackground(PaintEventArgs e) {
			GraphicsHelper graphics = new GraphicsHelper(e.Graphics);
			const int radius = 7;
			const int blend = 245;
			Rectangle bound = new Rectangle(DisplayRectangle.X + 1, DisplayRectangle.Y, Width - 3, Height - 2);
			graphics.RoundedFill(UColor.White, bound, radius);
			graphics.RoundedGradient(UColor.Blend(blend, UColor.Rgb(60, 60, 60)), UColor.Blend(blend, UColor.Rgb(38, 38, 38)), bound, 90, radius);
			graphics.RoundedOutline(UColor.Black, new Rectangle(bound.X + 1, bound.Y + 1, bound.Width - 1, bound.Height - 1), radius);
			graphics.Line(UColor.Blend(50, UColor.White), radius, 0, Width - radius, 0);
		}
Exemplo n.º 5
0
			protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) {
				GraphicsHelper helper = new GraphicsHelper(e.Graphics);
				Rectangle bounds = e.AffectedBounds;

				helper.Line(UColor.Blend(155 / 2, UColor.Rgb(0x06, 0x88, 0xD8)), 0, bounds.Width, bounds.Height - 3);
				helper.Line(UColor.Blend(155, UColor.Rgb(0x06, 0x88, 0xD8)), 0, bounds.Width, bounds.Height - 2);
				helper.Line(UColor.Rgb(0x06, 0x88, 0xD8), 0, bounds.Width, bounds.Height - 1);
				//				helper.Line(UColor.Rgb(25, 25, 25), 0, bounds.Width, bounds.Height - 1);

				base.OnRenderToolStripBorder(e);
			}
Exemplo n.º 6
0
        private void Form1_Load(object sender, EventArgs e)
        {
            //инциализируем отрисовку и физику
            gh = new GraphicsHelper(pictureBox1);
            ghover = new GraphicsHelper(pictureBoxOverlay);
            ph = new Physics();
            Vec2 target = new Vec2(75F, 6f); //Координаты конечной точки

            // рожаем машину
            var p = new CarParams();
            p.InitDefault(); //Задает машине параметры по умолчанию
            p.h = 2.5f; //Поправляем форму машинки
            p.h_base = 2f;
            var ps = new Pose() { xc = 5, yc = 15, angle_rad = 30 * Helper.angle_to_rad }; //Задаем начальное положение машины
            car = new Car(p, 0);
            car.Create(ph, ps);

            //создание агента и среды
            carAgent = new LICStreeAgent(ps,target);
            pictureBox2.Image = new Bitmap(pictureBox2.Width, pictureBox2.Height);
            env = new Environment(ph, car, target,pictureBox2);

            //создание объектов среды
            //ВАЖНО!!! -- в каком порядке объекты создаются, в таком они и отрисовываются, поэтому в первую очередь создаются объекты заднего плана.
            //занятно...-- НЕсамообучающийся по картинке агент ооочень туго переваривает динамические препятствия. Хотя, всё же, переваривает.

            env.CreateRectZone(new Pose { xc = 30f, yc = 23f, angle_rad = 45 * k_PI }, new Vec2(15f, 25f), 2f);
            env.CreateRectZone(new Pose { xc = 70f, yc = 20f, angle_rad = 45 * k_PI }, new Vec2(10f, 5f), 3f);
            env.CreateWall( new Pose { xc = 25f, yc = 17f, angle_rad = 20 * k_PI },new Vec2(2f, 10f));
            env.CreateWall(new Pose { xc = 20f, yc = 35f, angle_rad = 35 * k_PI }, new Vec2(10f, 10f));
            env.CreateWall(new Pose { xc = 40f, yc = 10f, angle_rad = 35 * k_PI }, new Vec2(40f, 1f));
            env.CreateWall( new Pose { xc = 55f, yc = 30f, angle_rad = 100 * k_PI },new Vec2(2f, 10f));
            env.CreateWall(new Pose { xc = 65f, yc = 45f, angle_rad = 0 * k_PI }, new Vec2(15f, 15f));
            env.CreateWall(new Pose { xc = 25f, yc = 25f, angle_rad = -195 * k_PI }, new Vec2(20f, 1f));
            env.CreateWall(new Pose { xc = 50f, yc = 20f, angle_rad = 105 * k_PI }, new Vec2(2f, 7f));
            env.CreateWall(new Pose { xc = 58f, yc = 18f, angle_rad = 45 * k_PI }, new Vec2(10f, 5f));

            env.CreateWall(new Pose { xc = pictureBox1.Width/20f, yc = pictureBox1.Height/10f, angle_rad = 90 * k_PI }, new Vec2(1f, 10000f));
            env.CreateWall(new Pose { xc = pictureBox1.Width / 20f, yc = 0/10f, angle_rad = 90 * k_PI }, new Vec2(1f, 10000f));
            env.CreateWall(new Pose { xc = pictureBox1.Width / 10f, yc = pictureBox1.Height / 20f, angle_rad = 0 * k_PI }, new Vec2(1f, 10000f));
            env.CreateWall(new Pose { xc = 0/10f, yc = pictureBox1.Height / 20f, angle_rad = 0 * k_PI }, new Vec2(1f, 10000f));

            //env.CreateCircle(new Pose { xc = 25f, yc = 20f, angle_rad = -10 * k_PI }, 3, 10);
            //env.CreateFire(new Pose { xc = 0f, yc = 0f, angle_rad = -10 * k_PI },5);
        }
Exemplo n.º 7
0
		protected override void OnPaint(PaintEventArgs e) {
			GraphicsHelper helper = new GraphicsHelper(e.Graphics);

			const int r = 7;
			const int shadowHeight = 4;

			Rectangle bounds = new Rectangle(0, 0, this.Width - 1, this.Height - 1 - shadowHeight);
			Rectangle rectShadow = new Rectangle(0, 0, Width - 1, Height - 1);
			Rectangle rectText = bounds;
			Rectangle rectTextShadow = new Rectangle(1, 1, rectText.Width - 2, rectText.Height - 1);
			if (Image != null) rectText = new Rectangle(bounds.X, bounds.Y, bounds.Width + Image.Width, bounds.Height);

			helper.RoundedFill(UColor.White, bounds, r);

			if (!Hover) {
				if (Enabled) {
					//32C437: Main color
					//2AA92E: Shadow
					//0A890D: Outline
					const uint color = 0x32c437;
					const uint color_shadow = 0x2aa92e;
					const uint color_outline = 0x0a890d;
					helper.RoundedFill(UColor.Blend(255, color_shadow), rectShadow, r);
					helper.RoundedGradient(UColor.Blend(200, color), UColor.Blend(255, color), bounds, 90, r);
					helper.RoundedOutline(UColor.Blend(255, color_outline), rectShadow, r);

					helper.Text(Caption, this.Font, UColor.White, rectTextShadow);
					helper.Text(Caption, this.Font, UColor.Blend(0xdd, UColor.White), rectText);
				} else {
				}
			} else {
				if (!Pressed) {
				} else {
				}
			}

			if (Image != null) {
				e.Graphics.DrawImage(this.Image, new Point(this.Width / 4 - this.Image.Width / 2, this.Height / 2 - this.Image.Height / 2));
			}
		}
Exemplo n.º 8
0
			protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e) {
				GraphicsHelper helper = new GraphicsHelper(e.Graphics);

				Rectangle shadow = new Rectangle(
					e.TextRectangle.X + 1,
					e.TextRectangle.Y + 1,
					e.TextRectangle.Width,
					e.TextRectangle.Height);

				uint shadowColor = UColor.Blend(0x10, UColor.White);
				uint textColor = UColor.Argb(255, 0xBB, 0xBB, 0xBB);

				if (e.Item.Selected || e.Item.Pressed) {
					shadowColor = UColor.Blend(0x7a, UColor.White);
					textColor = UColor.White;
				}

				StringFormat format = new StringFormat();
				format.LineAlignment = StringAlignment.Center;
				format.Alignment = StringAlignment.Near;

				if (!e.Item.Selected) helper.Text(e.Text, e.TextFont, shadowColor, shadow, format);
				helper.Text(e.Text, e.TextFont, textColor, e.TextRectangle, format);
			}
Exemplo n.º 9
0
        public static IDisposable Create(Game game, SpriteRenderer renderer, SpriteRenderer backRenderer, PrimitiveBatchRenderer primitiveRenderer, TaskScheduler scheduler, ICommunicationManager communication)
        {
            var kinectStream = game.Services.GetService <IObservable <KinectFrame> >();
            var markerStream = game.Services.GetService <IObservable <Tuple <IplImage, MarkerFrame> > >();

            return((from magabot in Enumerable.Range(0, 1)
                    //let wheelClicks = 1400
                    let wheelClicks = 3900
                                      let wheelDistance = 0.345f
                                                          let wheelRadius = 0.045f
                                                                            let vehicle = new Vehicle()
                                                                                          let slam = new SlamController(vehicle)
                                                                                                     let environment = game.Content.Load <NavigationEnvironment>("ChampalimaudLandmarks")
                                                                                                                       let slamVisualizer = new SlamVisualizer(game, backRenderer, slam, environment)
                                                                                                                                            let kinectVisualizer = new KinectVisualizer(game)
                                                                                                                                                                   let sonarVisualizer = new SonarVisualizer()
                                                                                                                                                                                         let steeringVisualizer = new SteeringVisualizer()
                                                                                                                                                                                                                  let freeSpaceVisualizer = new FreeSpaceVisualizer()
                                                                                                                                                                                                                                            let actionPlayer = new ActionPlayer(game)
                                                                                                                                                                                                                                                               let markerText = new StringBuilder()
                                                                                                                                                                                                                                                                                let text = new StringBuilder()
                                                                                                                                                                                                                                                                                           let transform = vehicle.Transform
                                                                                                                                                                                                                                                                                                           let font = game.Content.Load <SpriteFont>("DebugFont")
                                                                                                                                                                                                                                                                                                                      let texture = game.Content.Load <Texture2D>("bot")
                                                                                                                                                                                                                                                                                                                                    let bumperLeftTexture = game.Content.Load <Texture2D>("bumpLeft")
                                                                                                                                                                                                                                                                                                                                                            let bumperRightTexture = game.Content.Load <Texture2D>("bumpRight")
                                                                                                                                                                                                                                                                                                                                                                                     let bumperLeftOptions = new TextureDrawingParameters {
                Color = Color.Transparent
            }
                    let bumperRightOptions = new TextureDrawingParameters {
                Color = Color.Transparent
            }
                    let groundSensorLeftTexture = game.Content.Load <Texture2D>("irLeft")
                                                  let groundSensorMiddleTexture = game.Content.Load <Texture2D>("irMiddle")
                                                                                  let groundSensorRightTexture = game.Content.Load <Texture2D>("irRight")
                                                                                                                 let groundSensorLeftOptions = new TextureDrawingParameters {
                Color = Color.White
            }
                    let groundSensorMiddleOptions = new TextureDrawingParameters {
                Color = Color.White
            }
                    let groundSensorRightOptions = new TextureDrawingParameters {
                Color = Color.White
            }
                    let kinectTexture = new IplImageTexture(game.GraphicsDevice, 640, 480)
                                        let bumpers = new BumperBoard(communication)
                                                      let battery = new BatteryBoard(communication)
                                                                    let ground = new GroundSensorBoard(communication)
                                                                                 let leds = new LedBoard(communication)
                                                                                            let sonars = new SonarsBoard(communication)
                                                                                                         let differentialSteering = new DifferentialSteeringBoard(communication, wheelRadius, wheelClicks)
                                                                                                                                    let odometry = new OdometryBoard(communication, wheelClicks, wheelRadius, wheelDistance)
                                                                                                                                                   let magabotState = new MagabotState(leds, differentialSteering, bumpers, battery, ground, sonars)
                                                                                                                                                                      let skype = new MainWindow(magabotState)
                                                                                                                                                                                  let kalman = new KalmanFilter
            {
                Mean = new DenseVector(3),
                Covariance = new DenseMatrix(new double[, ] {
                    { 1, 0, 0 },
                    { 0, 1, 0 },
                    { 0, 0, 1 }
                })
            }
                    //let target = new Transform2D(new Vector2(1, 0), 0, Vector2.One)
                    let target = new Transform2D()
                                 let targetTexture = TextureFactory.CreateCircleTexture(game.GraphicsDevice, 2, Color.Violet)
                                                     let path = new[] { Vector2.UnitX, Vector2.One, Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY, Vector2.Zero }
                    let playActions = scheduler.TaskUpdate.Do(actionPlayer.Update)
                                      let activateMarker = scheduler.TaskUpdate.Do(gameTime =>
            {
                var keyboard = Keyboard.GetState();
                if (keyboard.IsKeyDown(Keys.D0))
                {
                    ActivateMarker(actionPlayer, vehicle, environment, slam, 0, game.Services);
                }
                if (keyboard.IsKeyDown(Keys.D1))
                {
                    ActivateMarker(actionPlayer, vehicle, environment, slam, 1, game.Services);
                }
                if (keyboard.IsKeyDown(Keys.D2))
                {
                    ActivateMarker(actionPlayer, vehicle, environment, slam, 2, game.Services);
                }
                if (keyboard.IsKeyDown(Keys.D3))
                {
                    ActivateMarker(actionPlayer, vehicle, environment, slam, 3, game.Services);
                }
                if (keyboard.IsKeyDown(Keys.D4))
                {
                    ActivateMarker(actionPlayer, vehicle, environment, slam, 4, game.Services);
                }
                if (keyboard.IsKeyDown(Keys.D5))
                {
                    ActivateMarker(actionPlayer, vehicle, environment, slam, 5, game.Services);
                }
                if (keyboard.IsKeyDown(Keys.D6))
                {
                    ActivateMarker(actionPlayer, vehicle, environment, slam, 6, game.Services);
                }
                if (keyboard.IsKeyDown(Keys.D7))
                {
                    ActivateMarker(actionPlayer, vehicle, environment, slam, 7, game.Services);
                }
                if (keyboard.IsKeyDown(Keys.D8))
                {
                    ActivateMarker(actionPlayer, vehicle, environment, slam, 8, game.Services);
                }
                if (keyboard.IsKeyDown(Keys.D9))
                {
                    ActivateMarker(actionPlayer, vehicle, environment, slam, 9, game.Services);
                }

                const string mapFileName = "map.xml";
                if (keyboard.IsKeyDown(Keys.S))
                {
                    var state = slam.StoreControllerState();
                    var serializer = new XmlSerializer(typeof(SlamControllerState));
                    using (var writer = XmlWriter.Create(mapFileName, new XmlWriterSettings {
                        Indent = true
                    }))
                    {
                        serializer.Serialize(writer, state);
                    }
                }

                if (keyboard.IsKeyDown(Keys.R) && File.Exists(mapFileName))
                {
                    var serializer = new XmlSerializer(typeof(SlamControllerState));
                    using (var reader = XmlReader.Create(mapFileName))
                    {
                        var state = (SlamControllerState)serializer.Deserialize(reader);
                        slam.RestoreControllerState(state);
                    }
                }
            })
                                                           let obstacleCount = new Counter()
                                                                               let safetyBump = magabotState.SafetyBump.MostRecent(false).GetEnumerator()
                                                                                                let safetyGround = magabotState.SafetyGround.MostRecent(false).GetEnumerator()
                                                                                                                   let steeringBehavior = scheduler.TaskUpdate
                                                                                                                                          .Do(gameTime =>
            {
                var gamePad = GamePad.GetState(PlayerIndex.One);
                if (gamePad.IsButtonDown(Buttons.DPadUp))
                {
                    vehicle.Steering += (gamePad.IsButtonDown(Buttons.A) ? 1.5f : 1) * Vector2.UnitX.Rotate(vehicle.Transform.Rotation);
                }
                if (gamePad.IsButtonDown(Buttons.DPadDown))
                {
                    vehicle.Steering += -Vector2.UnitX.Rotate(vehicle.Transform.Rotation);
                }
                if (gamePad.IsButtonDown(Buttons.DPadLeft))
                {
                    vehicle.Steering += 0.5f * Vector2.UnitX.Rotate(vehicle.Transform.Rotation + MathHelper.PiOver2);
                }
                if (gamePad.IsButtonDown(Buttons.DPadRight))
                {
                    vehicle.Steering += 0.5f * Vector2.UnitX.Rotate(vehicle.Transform.Rotation - MathHelper.PiOver2);
                }
            })
                                                                                                                                          //.Do(Steering.PathFollow(target, path, vehicle, Steering.DefaultMinSpeed, Steering.DefaultMaxSpeed, Steering.DefaultTolerance))
                                                                                                                                          .Do(gameTime =>
            {
                obstacleCount.Value--;
                var sonarThreshold = 35;
                var sonarState = magabotState.Sonar;
                var rotation = 0f;
                if (sonarState[0] < sonarThreshold)
                {
                    rotation -= MathHelper.PiOver4;
                }
                if (sonarState[1] < sonarThreshold)
                {
                    rotation -= MathHelper.PiOver4 * 0.5f;
                }
                //if (sonarState[2] < sonarThreshold) rotation += MathHelper.PiOver4;
                if (sonarState[3] < sonarThreshold)
                {
                    rotation += MathHelper.PiOver4 * 0.5f;
                }
                if (sonarState[4] < sonarThreshold)
                {
                    rotation += MathHelper.PiOver4;
                }
                if (rotation != 0)
                {
                    obstacleCount.Value = 90;
                    obstacleCount.Rotation = rotation;
                }

                if (obstacleCount.Value > 0)
                {
                    vehicle.Steering = vehicle.Steering.Rotate(obstacleCount.Rotation);
                }
            })
                                                                                                                                          .Do(gameTime => steeringVisualizer.Steering = vehicle.Steering)
                                                                                                                                          //.Do(Steering.Arrival(target, vehicle, 1, 3, 0.3f))
                                                                                                                                          .Where(gameTime => magabotState.Stopped)
                                                                                                                                          .Where(gameTime => { safetyBump.MoveNext(); return !safetyBump.Current; })
                                                                                                                                          //.Where(gameTime => { safetyGround.MoveNext(); return !safetyGround.Current; })
                                                                                                                                          .Do(Locomotion.DifferentialSteering(vehicle, differentialSteering, wheelDistance, MathHelper.Pi / 16, 10, 100, 3))
                                                                                                                                          let visualizerLoop = scheduler.TaskUpdate
                                                                                                                                                               .Do(time => slamVisualizer.Update())
                                                                                                                                                               .Do(time => kinectTexture.Update())
                                                                                                                                                               let behavior = scheduler.TaskUpdate
                                                                                                                                                                              .Do(time => odometry.UpdateOdometryCommand())
                                                                                                                                                                              .Do(time => magabotState.DifferentialSteering.UpdateWheelVelocity(new WheelVelocity(0, 0)))
                                                                                                                                                                              .Do(time => magabotState.Leds.SetLedBoardState(255, 255, 255))
                                                                                                                                                                              .Do(time => skype.Magabot = magabotState)
                                                                                                                                                                              .Do(time => skype.Show())
                                                                                                                                                                              .Take(1)
                                                                                                                                                                              select new CompositeDisposable(
                        bumpers,
                        battery,
                        ground,
                        leds,
                        sonars,
                        odometry,
                        differentialSteering,
                        playActions.Subscribe(),
                        activateMarker.Subscribe(),
                        steeringBehavior.Subscribe(),
                        visualizerLoop.Subscribe(),
                        //backRenderer.SubscribeTexture(new Transform2D(new Vector2(-2.75f, 1.7f), 0, new Vector2(0.25f)), kinectTexture.Texture),
                        backRenderer.SubscribeTexture(new Transform2D(new Vector2(-4.25f, 2.0f), 0, new Vector2(0.75f)), kinectTexture.Texture),
                        renderer.SubscribeTexture(transform, texture),
                        renderer.SubscribeTexture(transform, new Transform2D(), bumperLeftTexture, bumperLeftOptions),
                        renderer.SubscribeTexture(transform, new Transform2D(), bumperRightTexture, bumperRightOptions),
                        renderer.SubscribeTexture(transform, new Transform2D(), groundSensorLeftTexture, groundSensorLeftOptions),
                        renderer.SubscribeTexture(transform, new Transform2D(), groundSensorMiddleTexture, groundSensorMiddleOptions),
                        renderer.SubscribeTexture(transform, new Transform2D(), groundSensorRightTexture, groundSensorRightOptions),
                        renderer.SubscribeTexture(target, targetTexture),
                        //renderer.SubscribeText(transform, font, () => text.ToString()),
                        renderer.SubscribeText(new Transform2D(-Vector2.One, 0, Vector2.One), font, () => markerText.ToString(), Color.White),
                        primitiveRenderer.SubscribePrimitive(transform, kinectVisualizer.DrawKinectDepthMap),
                        primitiveRenderer.SubscribePrimitive(transform, sonarVisualizer.DrawSonarFrame),
                        primitiveRenderer.SubscribePrimitive(transform, steeringVisualizer.DrawSteeringVector),
                        primitiveRenderer.SubscribePrimitive(new Transform2D(new Vector2(-350, 200), 0, Vector2.One), freeSpaceVisualizer.DrawFreeSpace),
                        behavior.Subscribe(),
                        magabotState.MarkerActivated.Subscribe(name => ActivateMarker(actionPlayer, vehicle, environment, slam, name, game.Services)),
                        kinectStream.Subscribe(kinectFrame =>
            {
                kinectVisualizer.Frame = kinectFrame;
                freeSpaceVisualizer.FreeSpace = KinectFreeSpace.ComputeFreeSpace(kinectFrame, 1500);
                skype.OnKinectFrame(kinectFrame);
            }),
                        markerStream.Subscribe(markerOutput =>
            {
                var inputImage = markerOutput.Item1;
                var image = new IplImage(new CvSize(kinectTexture.Texture.Width, kinectTexture.Texture.Height), inputImage.Depth, inputImage.NumChannels);
                if (inputImage.Width != kinectTexture.Texture.Width || inputImage.Height != kinectTexture.Texture.Height)
                {
                    ImgProc.cvResize(inputImage, image, SubPixelInterpolation.NearestNeighbor);
                }
                else
                {
                    Core.cvCopy(inputImage, image);
                }

                foreach (var marker in markerOutput.Item2.DetectedMarkers)
                {
                    marker.Draw(image.DangerousGetHandle(), 0, 0, 255, 2, true);
                }

                kinectTexture.SetData(image);
                slam.UpdateMeasurements(markerOutput.Item2);
            }),
                        differentialSteering.CommandChecksum.Subscribe(m => bumpers.GetBumperState()),
                        bumpers.BumpersMeasure.Subscribe(m =>
            {
                bumperLeftOptions.Color = m.BumperLeft ? Color.White : Color.Transparent;
                bumperRightOptions.Color = m.BumperRight ? Color.White : Color.Transparent;
                battery.GetBatteryState();
            }),
                        battery.BatteryMeasure.Subscribe(m =>
            {
                text.Clear();
                text.AppendLine(string.Format("Battery: {0}", m.ToString()));
                ground.GetGroundSensorState();
            }),
                        ground.GroundSensorsMeasure.Subscribe(m =>
            {
                var sensorScale = 180 / 1023f;
                groundSensorLeftOptions.Color = GraphicsHelper.HsvToRgb(new Vector3(180 - m.SensorLeft * sensorScale, 1, 1));
                groundSensorMiddleOptions.Color = GraphicsHelper.HsvToRgb(new Vector3(180 - m.SensorMiddle * sensorScale, 1, 1));
                groundSensorRightOptions.Color = GraphicsHelper.HsvToRgb(new Vector3(180 - m.SensorRight * sensorScale, 1, 1));
                text.AppendLine(string.Format("IR: {0} IR: {1} IR: {2}", m.SensorLeft, m.SensorMiddle, m.SensorRight));
                sonars.GetSonarsBoardState();
            }),
                        sonars.SonarsBoardMeasure.Subscribe(m =>
            {
                sonarVisualizer.SonarFrame = m;
                for (int count = 0; count < m.Length; count++)
                {
                    var sonar = m[count];
                    text.Append(string.Format("Sonar: {0} ", sonar));
                }
                text.AppendLine();
                leds.Actuate();
            }),
                        leds.LedBoardMeasure.Subscribe(m => odometry.UpdateOdometryCommand()),
                        odometry.Odometry.Subscribe(m =>
            {
                slam.UpdateMotion(m.LinearDisplacement, m.AngularDisplacement);
                slam.UpdateEstimate();
                differentialSteering.Actuate();
            })))
                   .First());
        }
Exemplo n.º 10
0
            public void Render(GameTime gameTime)
            {
                for (int i = 0; i < Items.Count; i++)
                {
                    Color drawColor  = Items[i].GetForeColor();
                    bool  isSelected = (SelectedItem == i);
                    //if (selectedItem == i) drawColor = selectedItemForeground;
                    if (!Items[i].Enabled)
                    {
                        drawColor = GraphicsHelper.GetColorWithAlpha(DisabledItemForeground, Items[i].Alpha);
                    }

                    GraphicsHelper.DrawShadowedString(game.SpriteBatch,
                                                      font,
                                                      (Items[i].Caption),
                                                      (Position - centerOffset) + i * ItemsOffset + (isSelected?SelectedItemOffset:Vector2.Zero),
                                                      (isSelected?SelectedItemForeground :drawColor),
                                                      (DrawShadow ? (isSelected ? Color.Black : GraphicsHelper.GetColorWithAlpha(ShadowColor, Items[i].Alpha)) : Color.Transparent)
                                                      );
                    if (isSelected)
                    {
                        game.SpriteBatch.DrawString(
                            font,
                            "| ",
                            ((Position - centerOffset) + i * ItemsOffset + (isSelected ? SelectedItemOffset : Vector2.Zero)) -
                            new Vector2(font.MeasureString("| ").X + bracketDistance, 0),
                            Color.Brown);
                        game.SpriteBatch.DrawString(
                            font,
                            " |",
                            ((Position - centerOffset) + i * ItemsOffset + (isSelected ? SelectedItemOffset : Vector2.Zero)) +
                            (new Vector2(longestItem + bracketDistance, 0)),
                            Color.Brown);
                    }
                }

                game.SpriteBatch.Draw(
                    game.GetTexture("menuFocus"),
                    itemSelector,
                    Color.White);
            }
Exemplo n.º 11
0
        protected override void OnProcess(RenderContext context)
        {
            context.ThrowIfCameraMissing();

            var graphicsDevice = GraphicsService.GraphicsDevice;

            // Set sampler state.
            // (Floating-point textures cannot use linear filtering. XNA would throw an exception.)
            if (TextureHelper.IsFloatingPointFormat(context.SourceTexture.Format))
            {
                graphicsDevice.SamplerStates[0] = SamplerState.PointClamp;
            }
            else
            {
                graphicsDevice.SamplerStates[0] = SamplerState.LinearClamp;
            }

            // Set the render target - but only if no kind of alpha blending is currently set.
            // If alpha-blending is set, then we have to assume that the render target is already
            // set - everything else does not make sense.
            if (graphicsDevice.BlendState.ColorDestinationBlend == Blend.Zero &&
                graphicsDevice.BlendState.AlphaDestinationBlend == Blend.Zero)
            {
                graphicsDevice.SetRenderTarget(context.RenderTarget);
                graphicsDevice.Viewport = context.Viewport;
            }

            _parameterViewportSize.SetValue(new Vector2(graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height));

            var cameraNode = context.CameraNode;
            var cameraPose = cameraNode.PoseWorld;

            GraphicsHelper.GetFrustumFarCorners(cameraNode.Camera.Projection, _cameraFrustumFarCorners);

            // Convert frustum far corners from view space to world space.
            for (int i = 0; i < _cameraFrustumFarCorners.Length; i++)
            {
                _cameraFrustumFarCorners[i] = (Vector3)cameraPose.ToWorldDirection((Vector3)_cameraFrustumFarCorners[i]);
            }

            _parameterFrustumCorners.SetValue(_cameraFrustumFarCorners);

            // The CIE model does not work if the sun is below the horizon. We simply project it back up
            // to the horizon. Since the sun light will be small or gone at night, the actual luminance
            // distribution does not matter.
            var sunDirection = SunDirection;

            if (sunDirection.Y < 0)
            {
                sunDirection.Y = 0;
                sunDirection.TryNormalize();
            }

            _parameterSunDirection.SetValue((Vector3)sunDirection);
            _parameterExposure.SetValue(Exposure);
            _parameterAbcd.SetValue(new Vector4(Parameters.A, Parameters.B, Parameters.C, Parameters.D));
            _parameterEAndStrength.SetValue(new Vector2(Parameters.E, Strength));
            _parameterSourceTexture.SetValue(context.SourceTexture);
            _effect.CurrentTechnique.Passes[0].Apply();

            graphicsDevice.DrawFullScreenQuad();
        }
Exemplo n.º 12
0
        protected override void AddNodeEx(SceneNode node, RenderContext context)
        {
            bool hasMaxDistance = Numeric.IsPositiveFinite(node.MaxDistance);
            var  lodGroupNode   = node as LodGroupNode;
            bool isLodGroupNode = (lodGroupNode != null);

            float distance = 0;

            if (hasMaxDistance || isLodGroupNode)
            {
                // ----- Calculate view-normalized distance.
                // The view-normalized distance is the distance between scene node and
                // camera node corrected by the camera field of view. This metric is used
                // for distance culling and LOD selection.
                var cameraNode = context.LodCameraNode;
                distance = GraphicsHelper.GetViewNormalizedDistance(node, cameraNode);

                // Apply LOD bias. (The LOD bias is a factor that can be used to increase
                // or decrease the viewing distance.)
                distance *= cameraNode.LodBias * context.LodBias;
            }

            // ----- Distance Culling: Check whether scene node is within MaxDistance.
            if (hasMaxDistance && distance >= node.MaxDistance)
            {
                return; // Ignore scene node.
            }
            // ----- Optional: Fade out scene node near MaxDistance to avoid popping.
            if (context.LodBlendingEnabled && node.SupportsInstanceAlpha())
            {
                float d     = node.MaxDistance - distance;
                float alpha = (d < context.LodHysteresis) ? d / context.LodHysteresis : 1;
                node.SetInstanceAlpha(alpha);
            }

            if (isLodGroupNode)
            {
                // ----- Evaluate LOD group.
                var lodSelection = lodGroupNode.SelectLod(context, distance);

                // ----- Optional: LOD Blending.
                if (lodSelection.Next != null &&
                    context.LodBlendingEnabled &&
                    lodSelection.Current.SupportsInstanceAlpha() &&
                    lodSelection.Next.SupportsInstanceAlpha())
                {
                    // The LOD group is currently transitioning between two LODs. Both LODs
                    // have an "InstanceAlpha" material parameter, i.e. we can create a
                    // smooth transition by blending between both LODs.
                    // --> Render both LODs using screen door transparency (stipple patterns).
                    // The current LOD (alpha = 1 - t) is faded out and the next LOD is faded
                    // in (alpha = t).
                    // The fade-in uses the regular stipple pattern and the fade-out needs to
                    // use the inverted stipple pattern. If the alpha value is negative the
                    // shader will use the inverted stipple pattern - see effect Material.fx.)
                    AddSubtree(lodSelection.Current, context);
                    lodSelection.Current.SetInstanceAlpha(-(1 - lodSelection.Transition));

                    AddSubtree(lodSelection.Next, context);
                    lodSelection.Next.SetInstanceAlpha(lodSelection.Transition);
                }
                else
                {
                    // No blending between two LODs. Just show current LOD.
                    if (lodSelection.Current.SupportsInstanceAlpha())
                    {
                        lodSelection.Current.SetInstanceAlpha(1);
                    }

                    AddSubtree(lodSelection.Current, context);
                }
            }
            else
            {
                // ----- Handle normal nodes.
                AddNode(node);
            }
        }
Exemplo n.º 13
0
 /// <summary>
 /// Recalculates the paths.
 /// </summary>
 private void RecalculatePaths()
 {
     DisposePaths();
     m_bgPath    = GraphicsHelper.GetGraphicsPath(ClientRectangle, Shape);
     m_glossPath = GraphicsHelper.Get3DShinePath(ClientRectangle, Shape);
 }
Exemplo n.º 14
0
        protected override void OnPaint(PaintEventArgs e)
        {
            //base.OnPaint(e);
            //base.OnPaintBackground(e);

            Graphics g = e.Graphics;

            g.SmoothingMode = SmoothingMode.AntiAlias;

            Color backColor;
            Color borderColor      = StyleSheet.ControlBorderColor;
            Color innerBorderColor = StyleSheet.ControlInnerBorderColor;

            if (Enabled)
            {
                switch (ControlState)
                {
                case ControlState.Hovering:
                    backColor = StyleSheet.ControlHoveringBackColor;
                    break;

                case ControlState.Pressed:
                    backColor = StyleSheet.ControlFocusedBackColor;
                    break;

                default:     //normal
                {
                    if (SensitiveType == ControlSensitiveType.Focus && Focused)
                    {
                        backColor = innerBorderColor = StyleSheet.ControlFocusedBackColor;
                    }
                    else if (SensitiveType == ControlSensitiveType.Check && Checked)
                    {
                        backColor = innerBorderColor = StyleSheet.ControlFocusedBackColor;
                    }
                    else
                    {
                        backColor = BackColor;
                        if (!HasBorder)
                        {
                            borderColor      = BackColor;
                            innerBorderColor = BackColor;
                        }
                        else
                        {
                            borderColor      = StyleSheet.ControlBorderColor;
                            innerBorderColor = StyleSheet.ControlInnerBorderColor;
                        }
                    }
                }
                break;
                }
            }
            else
            {
                backColor = StyleSheet.ControlDisabledBaseColor;
            }


            GraphicsHelper.DrawBackground(
                g,
                ClientRectangle,
                backColor,
                borderColor,
                innerBorderColor,
                _roundStyle,
                _radius,
                0,
                true,
                true,
                LinearGradientMode.Vertical);
            Rectangle textRect = new Rectangle(
                2,
                2,
                Width - 4,
                Height - 4);;

            TextRenderer.DrawText(
                g,
                Text,
                Font,
                textRect,
                ForeColor,
                GetTextFormatFlags(TextAlign, RightToLeft == RightToLeft.Yes));
        }
Exemplo n.º 15
0
        public bool UploadPictureToBlobStorage(System.Drawing.Image img, string newid, string containerName, string directoryPath, int maxWidth, int maxHeight, int maxWidthT, int maxHeightT, bool createArtifactThumbnails, bool makeSquare, long jpegquality)
        {
            // Retrieve a reference to a container
            CloudBlobContainer container = blobClient.GetContainerReference(containerName);
            CloudBlobDirectory dir       = container.GetDirectoryReference(directoryPath);

            // Create the container if it doesn't already exist
            container.CreateIfNotExist();
            container.SetPermissions(new BlobContainerPermissions {
                PublicAccess = BlobContainerPublicAccessType.Blob
            });

            System.Drawing.Image imgFull    = (System.Drawing.Image)img.Clone();
            System.Drawing.Image imgThumb   = (System.Drawing.Image)img.Clone();
            System.Drawing.Image imgThumb20 = (System.Drawing.Image)img.Clone();
            System.Drawing.Image imgThumb40 = (System.Drawing.Image)img.Clone();

            System.Drawing.Image imgFullSquare = null;
            imgFullSquare = makeItSquare(img);

            int MAX_WIDTH    = maxWidth;
            int MAX_HEIGHT   = maxHeight;
            int MAX_WIDTH_T  = maxWidthT;
            int MAX_HEIGHT_T = maxHeightT;

            try
            {
                if (maxWidthT > 0)
                {
                    if (imgThumb.Width > MAX_WIDTH_T || imgThumb.Height > MAX_HEIGHT_T)
                    {
                        imgThumb   = resizeImage(imgFullSquare, new Size(MAX_WIDTH_T, MAX_HEIGHT_T), new Point(0, 0), new Size(imgFullSquare.Width, imgFullSquare.Height), true);
                        imgThumb20 = resizeImage(imgFullSquare, new Size(20, 20), new Point(0, 0), new Size(imgFullSquare.Width, imgFullSquare.Height), true);
                        imgThumb40 = resizeImage(imgFullSquare, new Size(40, 40), new Point(0, 0), new Size(imgFullSquare.Width, imgFullSquare.Height), true);
                    }
                }

                if (makeSquare)
                {
                    imgFull = resizeImage(imgFullSquare, new Size(MAX_WIDTH, MAX_HEIGHT), new Point(0, 0), new Size(imgFullSquare.Width, imgFullSquare.Height), makeSquare);
                }
                else
                {
                    imgFull = resizeImage(imgFull, new Size(MAX_WIDTH, MAX_HEIGHT), new Point(0, 0), new Size(imgFull.Width, imgFull.Height), makeSquare);
                }


                // Retrieve reference to a blob by username
                CloudBlob blobFull = dir.GetBlobReference(newid);
                using (MemoryStream ms = new MemoryStream())
                {
                    SaveImageAsJpeg(ms, imgFull, jpegquality);
                    //imgFull.Save(ms, ImageFormat.Png);
                    blobFull.UploadByteArray(ms.ToArray());
                }

                if (maxWidthT > 0)
                {
                    CloudBlob blobThumb = dir.GetBlobReference(newid + "_t");
                    using (MemoryStream ms = new MemoryStream())
                    {
                        SaveImageAsJpeg(ms, imgThumb, jpegquality);
                        //imgThumb.Save(ms, ImageFormat.Png);
                        blobThumb.UploadByteArray(ms.ToArray());
                    }

                    if (createArtifactThumbnails)
                    {
                        CloudBlob blobThumb20 = dir.GetBlobReference(newid + "_t20");
                        using (MemoryStream ms = new MemoryStream())
                        {
                            SaveImageAsJpeg(ms, imgThumb20, jpegquality);
                            //imgThumb.Save(ms, ImageFormat.Png);
                            blobThumb20.UploadByteArray(ms.ToArray());
                        }

                        CloudBlob blobThumb40 = dir.GetBlobReference(newid + "_t40");
                        using (MemoryStream ms = new MemoryStream())
                        {
                            SaveImageAsJpeg(ms, imgThumb40, jpegquality);
                            //imgThumb.Save(ms, ImageFormat.Png);
                            blobThumb40.UploadByteArray(ms.ToArray());
                        }
                    }
                }

                if (createArtifactThumbnails)
                {
                    System.Drawing.Image imgFullBW = GraphicsHelper.MakeGrayscale3(imgFull);
                    //System.Drawing.Image imgFullR = GraphicsHelper.OvalImage(imgFull);
                    //System.Drawing.Image imgFullBWR = GraphicsHelper.OvalImage(imgFullBW);

                    System.Drawing.Image imgThumbBW  = null;
                    System.Drawing.Image imgThumbR   = null;
                    System.Drawing.Image imgThumbBWR = null;

                    if (maxWidthT > 0)
                    {
                        imgThumbBW  = GraphicsHelper.MakeGrayscale3(imgThumb);
                        imgThumbR   = GraphicsHelper.OvalImage(imgThumb);
                        imgThumbBWR = GraphicsHelper.OvalImage(imgThumbBW);
                    }

                    //CloudBlob blobFullBW = dir.GetBlobReference(newid + "_bw");
                    //using (MemoryStream ms = new MemoryStream())
                    //{
                    //    SaveImageAsJpeg(ms, imgFullBW, jpegquality);
                    //    //imgFullBW.Save(ms, ImageFormat.Png);
                    //    blobFullBW.UploadByteArray(ms.ToArray());
                    //}
                    //CloudBlob blobFullR = dir.GetBlobReference(newid + "_r");
                    //using (MemoryStream ms = new MemoryStream())
                    //{
                    //    imgFullR.Save(ms, ImageFormat.Png);
                    //    blobFullR.UploadByteArray(ms.ToArray());
                    //}
                    //CloudBlob blobFullBWR = dir.GetBlobReference(newid + "_bwr");
                    //using (MemoryStream ms = new MemoryStream())
                    //{
                    //    imgFullBWR.Save(ms, ImageFormat.Png);
                    //    blobFullBWR.UploadByteArray(ms.ToArray());
                    //}


                    if (maxWidthT > 0)
                    {
                        CloudBlob blobThumbBW = dir.GetBlobReference(newid + "_tbw");
                        using (MemoryStream ms = new MemoryStream())
                        {
                            SaveImageAsJpeg(ms, imgThumbBW, jpegquality);
                            //imgThumbBW.Save(ms, ImageFormat.Png);
                            blobThumbBW.UploadByteArray(ms.ToArray());
                        }
                        CloudBlob blobThumbR = dir.GetBlobReference(newid + "_tr");
                        using (MemoryStream ms = new MemoryStream())
                        {
                            //SaveImageAsJpeg(ms, imgThumbR, jpegquality);
                            imgThumbR.Save(ms, ImageFormat.Png);
                            blobThumbR.UploadByteArray(ms.ToArray());
                        }
                        CloudBlob blobThumbBWR = dir.GetBlobReference(newid + "_tbwr");
                        using (MemoryStream ms = new MemoryStream())
                        {
                            //SaveImageAsJpeg(ms, imgThumbBWR, jpegquality);
                            imgThumbBWR.Save(ms, ImageFormat.Png);
                            blobThumbBWR.UploadByteArray(ms.ToArray());
                        }
                    }
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Exemplo n.º 16
0
 /// <summary>
 /// Draws the line
 /// </summary>
 /// <param name="sb"></param>
 /// <param name="c"></param>
 public void Draw(SpriteBatch sb, Color c)
 {
     GraphicsHelper.DrawLine(sb, pos1, pos2, 2, c);
 }
Exemplo n.º 17
0
 public void Dispose()
 {
     GraphicsHelper.SafeDispose(ref m_d3dInteropDevice);
     GraphicsHelper.SafeDispose(ref m_dxgiAdapter);
 }
Exemplo n.º 18
0
        protected override void OnProcess(RenderContext context)
        {
            var graphicsDevice   = GraphicsService.GraphicsDevice;
            var renderTargetPool = GraphicsService.RenderTargetPool;

            var     viewport = context.Viewport;
            Vector2 size     = new Vector2(viewport.Width, viewport.Height);

            // Choose suitable technique.
            // We do not have shader for each sample count.
            int numberOfSamples = NumberOfSamples;

            SetCurrentTechnique(ref numberOfSamples);

            // Apply current scale and texture size to offsets.
            for (int i = 0; i < NumberOfSamples; i++)
            {
                _horizontalOffsets[i].X = Offsets[i].X * Scale / size.X;
                _horizontalOffsets[i].Y = Offsets[i].Y * Scale / size.Y;
            }

            // Make sure the other samples are 0 (e.g. if we want 11 samples but the
            // next best shader supports only 15 samples).
            for (int i = NumberOfSamples; i < numberOfSamples; i++)
            {
                _horizontalOffsets[i].X = 0;
                _horizontalOffsets[i].Y = 0;
                Weights[i] = 0;
            }

            // If we have a separable filter, we initialize _verticalOffsets too.
            if (IsSeparable)
            {
                if (_verticalOffsets == null)
                {
                    _verticalOffsets = new Vector2[MaxNumberOfSamples];
                }

                float aspectRatio = size.X / size.Y;
                for (int i = 0; i < NumberOfSamples; i++)
                {
                    _verticalOffsets[i].X = _horizontalOffsets[i].Y * aspectRatio;
                    _verticalOffsets[i].Y = _horizontalOffsets[i].X * aspectRatio;
                }
                for (int i = NumberOfSamples; i < numberOfSamples; i++)
                {
                    _verticalOffsets[i].X = 0;
                    _verticalOffsets[i].Y = 0;
                }
            }

            // Use hardware filtering if possible.
            if (TextureHelper.IsFloatingPointFormat(context.SourceTexture.Format))
            {
                graphicsDevice.SamplerStates[0] = SamplerState.PointClamp;
            }
            else
            {
                graphicsDevice.SamplerStates[0] = SamplerState.LinearClamp;
            }

            bool isAnisotropic = IsAnisotropic;
            bool isBilateral   = IsBilateral;

            if (FilterInLogSpace)
            {
                // Anisotropic and bilateral filtering in log-space is not implemented.
                isAnisotropic = false;
                isBilateral   = false;
            }
            else
            {
                if (isAnisotropic || isBilateral)
                {
                    context.ThrowIfCameraMissing();

                    var   cameraNode = context.CameraNode;
                    var   projection = cameraNode.Camera.Projection;
                    float far        = projection.Far;

                    GraphicsHelper.GetFrustumFarCorners(cameraNode.Camera.Projection, _frustumFarCorners);
                    _parameterFrustumCorners.SetValue(_frustumFarCorners);

                    _parameterBlurParameters0.SetValue(new Vector4(
                                                           far,
                                                           viewport.AspectRatio,
                                                           1.0f / (EdgeSoftness + 0.001f) * far,
                                                           DepthScaling));

                    context.ThrowIfGBuffer0Missing();
                    Texture2D depthBuffer = context.GBuffer0;
                    if (viewport.Width < depthBuffer.Width && viewport.Height < depthBuffer.Height)
                    {
                        // Use half-resolution depth buffer.
                        object obj;
                        if (context.Data.TryGetValue(RenderContextKeys.DepthBufferHalf, out obj))
                        {
                            var depthBufferHalf = obj as Texture2D;
                            if (depthBufferHalf != null)
                            {
                                depthBuffer = depthBufferHalf;
                            }
                        }
                    }

                    _parameterGBuffer0.SetValue(depthBuffer);
                }
            }

            _parameterViewportSize.SetValue(size);
            _parameterWeights.SetValue(Weights);

            int effectiveNumberOfPasses = IsSeparable ? NumberOfPasses * 2 : NumberOfPasses;

            // We use up to two temporary render targets for ping-ponging.
            var tempFormat  = new RenderTargetFormat((int)size.X, (int)size.Y, false, context.SourceTexture.Format, DepthFormat.None);
            var tempTarget0 = (effectiveNumberOfPasses > 1)
                        ? renderTargetPool.Obtain2D(tempFormat)
                        : null;
            var tempTarget1 = (effectiveNumberOfPasses > 2)
                        ? renderTargetPool.Obtain2D(tempFormat)
                        : null;

            for (int i = 0; i < effectiveNumberOfPasses; i++)
            {
                if (i == effectiveNumberOfPasses - 1)
                {
                    graphicsDevice.SetRenderTarget(context.RenderTarget);
                    graphicsDevice.Viewport = viewport;
                }
                else if (i % 2 == 0)
                {
                    graphicsDevice.SetRenderTarget(tempTarget0);
                }
                else
                {
                    graphicsDevice.SetRenderTarget(tempTarget1);
                }

                if (i == 0)
                {
                    _parameterSourceTexture.SetValue(context.SourceTexture);
                }
                else if (i % 2 == 0)
                {
                    _parameterSourceTexture.SetValue(tempTarget1);
                }
                else
                {
                    _parameterSourceTexture.SetValue(tempTarget0);
                }

                Vector2[] offsets;
                if (IsSeparable && i % 2 != 0 &&
                    !isAnisotropic) // The anisotropic filter only reads Offsets[i].x
                {
                    offsets = _verticalOffsets;
                }
                else
                {
                    offsets = _horizontalOffsets;
                }

                _parameterOffsets.SetValue(offsets);

                int passIndex = 0;
                if (isAnisotropic)
                {
                    passIndex = i % 2;
                }

                _effect.CurrentTechnique.Passes[passIndex].Apply();
                graphicsDevice.DrawFullScreenQuad();
            }

            _parameterSourceTexture.SetValue((Texture2D)null);

            renderTargetPool.Recycle(tempTarget0);
            renderTargetPool.Recycle(tempTarget1);
        }
        public override void Render(IList <SceneNode> nodes, RenderContext context, RenderOrder order)
        {
            if (nodes == null)
            {
                throw new ArgumentNullException("nodes");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            int numberOfNodes = nodes.Count;

            if (numberOfNodes == 0)
            {
                return;
            }

            context.Validate(_effect);
            context.ThrowIfCameraMissing();

            var graphicsDevice   = _effect.GraphicsDevice;
            var savedRenderState = new RenderStateSnapshot(graphicsDevice);

            graphicsDevice.DepthStencilState = DepthStencilState.None;
            graphicsDevice.RasterizerState   = RasterizerState.CullNone;
            graphicsDevice.BlendState        = GraphicsHelper.BlendStateAdd;

            var viewport = graphicsDevice.Viewport;

            _parameterViewportSize.SetValue(new Vector2(viewport.Width, viewport.Height));
            _parameterGBuffer0.SetValue(context.GBuffer0);
            _parameterGBuffer1.SetValue(context.GBuffer1);

            var    cameraNode     = context.CameraNode;
            Matrix viewProjection = (Matrix)cameraNode.View * cameraNode.Camera.Projection;

            var cameraPose = cameraNode.PoseWorld;

            GraphicsHelper.GetFrustumFarCorners(cameraNode.Camera.Projection, _cameraFrustumFarCorners);

            // Convert frustum far corners from view space to world space.
            for (int i = 0; i < _cameraFrustumFarCorners.Length; i++)
            {
                _cameraFrustumFarCorners[i] = (Vector3)cameraPose.ToWorldDirection((Vector3)_cameraFrustumFarCorners[i]);
            }

            _parameterFrustumCorners.SetValue(_cameraFrustumFarCorners);

            // Update SceneNode.LastFrame for all visible nodes.
            int frame = context.Frame;

            cameraNode.LastFrame = frame;

            var isHdrEnabled = context.IsHdrEnabled();

            for (int i = 0; i < numberOfNodes; i++)
            {
                var lightNode = nodes[i] as LightNode;
                if (lightNode == null)
                {
                    continue;
                }

                var light = lightNode.Light as DirectionalLight;
                if (light == null)
                {
                    continue;
                }

                // LightNode is visible in current frame.
                lightNode.LastFrame = frame;

                float hdrScale = isHdrEnabled ? light.HdrScale : 1;
                _parameterDiffuseColor.SetValue((Vector3)light.Color * light.DiffuseIntensity * hdrScale);
                _parameterSpecularColor.SetValue((Vector3)light.Color * light.SpecularIntensity * hdrScale);

                Pose    lightPose           = lightNode.PoseWorld;
                Vector3 lightDirectionWorld = lightPose.ToWorldDirection(Vector3.Forward);
                _parameterLightDirection.SetValue((Vector3)lightDirectionWorld);

                bool hasShadow = (lightNode.Shadow != null && lightNode.Shadow.ShadowMask != null);
                if (hasShadow)
                {
                    switch (lightNode.Shadow.ShadowMaskChannel)
                    {
                    case 0:  _parameterShadowMaskChannel.SetValue(new Vector4(1, 0, 0, 0)); break;

                    case 1:  _parameterShadowMaskChannel.SetValue(new Vector4(0, 1, 0, 0)); break;

                    case 2:  _parameterShadowMaskChannel.SetValue(new Vector4(0, 0, 1, 0)); break;

                    default: _parameterShadowMaskChannel.SetValue(new Vector4(0, 0, 0, 1)); break;
                    }

                    _parameterShadowMask.SetValue(lightNode.Shadow.ShadowMask);
                }

                bool hasTexture = (light.Texture != null);
                if (hasTexture)
                {
                    var textureProjection = Matrix.CreateOrthographicOffCenter(
                        -light.TextureOffset.X,
                        -light.TextureOffset.X + Math.Abs(light.TextureScale.X),
                        light.TextureOffset.Y,
                        light.TextureOffset.Y + Math.Abs(light.TextureScale.Y),
                        1,  // Not relevant
                        2); // Not relevant.
                    var scale = Matrix.CreateScale(Math.Sign(light.TextureScale.X), Math.Sign(light.TextureScale.Y), 1);

                    _parameterTextureMatrix.SetValue((Matrix)(GraphicsHelper.ProjectorBiasMatrix * scale * textureProjection * lightPose.Inverse));

                    _parameterTexture.SetValue(light.Texture);
                }

                if (lightNode.Clip != null)
                {
                    var data = lightNode.RenderData as LightRenderData;
                    if (data == null)
                    {
                        data = new LightRenderData();
                        lightNode.RenderData = data;
                    }

                    data.UpdateClipSubmesh(context.GraphicsService, lightNode);

                    graphicsDevice.DepthStencilState = GraphicsHelper.DepthStencilStateOnePassStencilFail;
                    graphicsDevice.BlendState        = GraphicsHelper.BlendStateNoColorWrite;

                    _parameterWorldViewProjection.SetValue((Matrix)data.ClipMatrix * viewProjection);
                    _passClip.Apply();
                    data.ClipSubmesh.Draw();

                    graphicsDevice.DepthStencilState = lightNode.InvertClip
            ? GraphicsHelper.DepthStencilStateStencilEqual0
            : GraphicsHelper.DepthStencilStateStencilNotEqual0;
                    graphicsDevice.BlendState = GraphicsHelper.BlendStateAdd;
                }
                else
                {
                    graphicsDevice.DepthStencilState = DepthStencilState.None;
                }

                if (hasShadow)
                {
                    if (hasTexture)
                    {
                        if (light.Texture.Format == SurfaceFormat.Alpha8)
                        {
                            _passShadowedTexturedAlpha.Apply();
                        }
                        else
                        {
                            _passShadowedTexturedRgb.Apply();
                        }
                    }
                    else
                    {
                        _passShadowed.Apply();
                    }
                }
                else
                {
                    if (hasTexture)
                    {
                        if (light.Texture.Format == SurfaceFormat.Alpha8)
                        {
                            _passTexturedAlpha.Apply();
                        }
                        else
                        {
                            _passTexturedRgb.Apply();
                        }
                    }
                    else
                    {
                        _passDefault.Apply();
                    }
                }

                graphicsDevice.DrawFullScreenQuad();
            }

            savedRenderState.Restore();
        }
Exemplo n.º 20
0
 public void Draw(GraphicsHelper gh)
 {
     var pos = body.GetPosition();
     float k = Helper.angle_to_rad;
     var a1 = body.GetAngle() / k;
     var a2 = bodyFW1.GetAngle() / k;
     var th = Helper.GetRelAngle(a1, a2, 360 * k);
     gh.DrawCar(pos.X, pos.Y, p.w, p.h, a1, p.h_base, p.w_base, th);
     if (lidar != null) lidar.Draw(gh);
 }
Exemplo n.º 21
0
        public bool ResizeAndSave(string id, string newid, string containerName, string directoryPath, int maxWidth, int maxHeight, int maxWidthT, int maxHeightT, int xoffset, int yoffset, int rwidth, int rheight, long jpegquality)
        {
            // Retrieve a reference to a container
            CloudBlobContainer container = blobClient.GetContainerReference(containerName);
            CloudBlobDirectory dir       = container.GetDirectoryReference(directoryPath);

            // Retrieve reference to the stored preview blob
            CloudBlob blobStored = dir.GetBlobReference(id);

            System.Drawing.Image imgStored;
            using (MemoryStream ms = new MemoryStream())
            {
                blobStored.DownloadToStream(ms);
                imgStored = System.Drawing.Image.FromStream(ms);
            }

            System.Drawing.Image imgFull    = null;
            System.Drawing.Image imgThumb   = null;
            System.Drawing.Image imgThumb20 = null;
            System.Drawing.Image imgThumb40 = null;

            int MAX_WIDTH    = maxWidth;
            int MAX_HEIGHT   = maxHeight;
            int MAX_WIDTH_T  = maxWidthT;
            int MAX_HEIGHT_T = maxHeightT;

            try
            {
                imgFull = resizeImage(imgStored, new Size(MAX_WIDTH, MAX_HEIGHT), new Point(xoffset, yoffset), new Size(rwidth, rheight), true);

                if (maxWidthT > 0)
                {
                    if (imgStored.Width > MAX_WIDTH_T || imgStored.Height > MAX_HEIGHT_T)
                    {
                        imgThumb   = resizeImage(imgFull, new Size(MAX_WIDTH_T, MAX_HEIGHT_T), new Point(0, 0), new Size(imgFull.Width, imgFull.Height), true);
                        imgThumb20 = resizeImage(imgFull, new Size(20, 20), new Point(0, 0), new Size(imgFull.Width, imgFull.Height), true);
                        imgThumb40 = resizeImage(imgFull, new Size(40, 40), new Point(0, 0), new Size(imgFull.Width, imgFull.Height), true);
                    }
                }

                System.Drawing.Image imgFullBW = GraphicsHelper.MakeGrayscale3(imgFull);

                System.Drawing.Image imgThumbBW  = null;
                System.Drawing.Image imgThumbR   = null;
                System.Drawing.Image imgThumbBWR = null;

                if (maxWidthT > 0)
                {
                    imgThumbBW  = GraphicsHelper.MakeGrayscale3(imgThumb);
                    imgThumbR   = GraphicsHelper.OvalImage(imgThumb);
                    imgThumbBWR = GraphicsHelper.OvalImage(imgThumbBW);
                }

                // Retrieve reference to a blob by username
                CloudBlob blobFull = dir.GetBlobReference(newid);
                using (MemoryStream ms = new MemoryStream())
                {
                    SaveImageAsJpeg(ms, imgFull, jpegquality);
                    //imgFull.Save(ms, ImageFormat.Png);
                    blobFull.UploadByteArray(ms.ToArray());
                }
                //CloudBlob blobFullBW = dir.GetBlobReference(newid + "_bw");
                //using (MemoryStream ms = new MemoryStream())
                //{
                //    imgFullBW.Save(ms, ImageFormat.Png);
                //    blobFullBW.UploadByteArray(ms.ToArray());
                //}
                //CloudBlob blobFullR = dir.GetBlobReference(newid + "_r");
                //using (MemoryStream ms = new MemoryStream())
                //{
                //    imgFullR.Save(ms, ImageFormat.Png);
                //    blobFullR.UploadByteArray(ms.ToArray());
                //}
                //CloudBlob blobFullBWR = dir.GetBlobReference(newid + "_bwr");
                //using (MemoryStream ms = new MemoryStream())
                //{
                //    imgFullBWR.Save(ms, ImageFormat.Png);
                //    blobFullBWR.UploadByteArray(ms.ToArray());
                //}


                if (maxWidthT > 0)
                {
                    CloudBlob blobThumb = dir.GetBlobReference(newid + "_t");
                    using (MemoryStream ms = new MemoryStream())
                    {
                        SaveImageAsJpeg(ms, imgThumb, jpegquality);
                        //imgThumb.Save(ms, ImageFormat.Png);
                        blobThumb.UploadByteArray(ms.ToArray());
                    }

                    CloudBlob blobThumb20 = dir.GetBlobReference(newid + "_t20");
                    using (MemoryStream ms = new MemoryStream())
                    {
                        SaveImageAsJpeg(ms, imgThumb20, jpegquality);
                        //imgThumb.Save(ms, ImageFormat.Png);
                        blobThumb20.UploadByteArray(ms.ToArray());
                    }

                    CloudBlob blobThumb40 = dir.GetBlobReference(newid + "_t40");
                    using (MemoryStream ms = new MemoryStream())
                    {
                        SaveImageAsJpeg(ms, imgThumb40, jpegquality);
                        //imgThumb.Save(ms, ImageFormat.Png);
                        blobThumb40.UploadByteArray(ms.ToArray());
                    }


                    CloudBlob blobThumbBW = dir.GetBlobReference(newid + "_tbw");
                    using (MemoryStream ms = new MemoryStream())
                    {
                        SaveImageAsJpeg(ms, imgThumbBW, jpegquality);
                        //imgThumbBW.Save(ms, ImageFormat.Png);
                        blobThumbBW.UploadByteArray(ms.ToArray());
                    }
                    CloudBlob blobThumbR = dir.GetBlobReference(newid + "_tr");
                    using (MemoryStream ms = new MemoryStream())
                    {
                        //SaveImageAsJpeg(ms, imgThumbR, jpegquality);
                        imgThumbR.Save(ms, ImageFormat.Png);
                        blobThumbR.UploadByteArray(ms.ToArray());
                    }
                    CloudBlob blobThumbBWR = dir.GetBlobReference(newid + "_tbwr");
                    using (MemoryStream ms = new MemoryStream())
                    {
                        //SaveImageAsJpeg(ms, imgThumbBWR, jpegquality);
                        imgThumbBWR.Save(ms, ImageFormat.Png);
                        blobThumbBWR.UploadByteArray(ms.ToArray());
                    }
                }

                blobStored.DeleteIfExists();

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Computes the intersection of <see cref="MeshNode"/>s.
        /// </summary>
        /// <param name="meshNodePairs">
        /// A collection of <see cref="MeshNode"/> pairs.The renderer computes the intersection volume
        /// of each pair.
        /// </param>
        /// <param name="color">The diffuse color used for the intersection.</param>
        /// <param name="alpha">The opacity of the intersection.</param>
        /// <param name="maxConvexity">
        /// The maximum convexity of the submeshes. A convex mesh has a convexity of 1. A concave mesh
        /// has a convexity greater than 1. Convexity is the number of layers required for depth peeling
        /// (= the number of front face layers when looking at the object).
        /// </param>
        /// <param name="context">The render context.</param>
        /// <remarks>
        /// <para>
        /// This method renders an off-screen image (color and depth) of the intersection volume. This
        /// operation destroys the currently set render target and depth/stencil buffer.
        /// </para>
        /// </remarks>
        /// <exception cref="ObjectDisposedException">
        /// The <see cref="IntersectionRenderer"/> has already been disposed.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="meshNodePairs"/> or <see cref="context"/> is
        /// <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// The convexity must be greater than 0.
        /// </exception>
        /// <exception cref="GraphicsException">
        /// Invalid render context: Graphics service is not set.
        /// </exception>
        /// <exception cref="GraphicsException">
        /// Invalid render context: Wrong graphics device.
        /// </exception>
        /// <exception cref="GraphicsException">
        /// Invalid render context: Scene is not set.
        /// </exception>
        /// <exception cref="GraphicsException">
        /// Invalid render context: Camera node needs to be set in render context.
        /// </exception>
        public void ComputeIntersection(IEnumerable <Pair <MeshNode> > meshNodePairs,
                                        Vector3 color, float alpha, float maxConvexity, RenderContext context)
        {
            if (_isDisposed)
            {
                throw new ObjectDisposedException("IntersectionRenderer has already been disposed.");
            }
            if (meshNodePairs == null)
            {
                throw new ArgumentNullException("meshNodePairs");
            }
            if (maxConvexity < 1)
            {
                throw new ArgumentOutOfRangeException("maxConvexity", "The max convexity must be greater than 0.");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (context.GraphicsService == null)
            {
                throw new GraphicsException("Invalid render context: Graphics service is not set.");
            }
            if (_graphicsService != context.GraphicsService)
            {
                throw new GraphicsException("Invalid render context: Wrong graphics service.");
            }
            if (context.CameraNode == null)
            {
                throw new GraphicsException("Camera node needs to be set in render context.");
            }
            if (context.Scene == null)
            {
                throw new GraphicsException("A scene needs to be set in the render context.");
            }

            // Create 2 ordered pairs for each unordered pair.
            _pairs.Clear();
            foreach (var pair in meshNodePairs)
            {
                if (pair.First == null || pair.Second == null)
                {
                    continue;
                }

                // Frustum culling.
                if (!context.Scene.HaveContact(pair.First, context.CameraNode))
                {
                    continue;
                }
                if (!context.Scene.HaveContact(pair.Second, context.CameraNode))
                {
                    continue;
                }

                _pairs.Add(new Pair <MeshNode, MeshNode>(pair.First, pair.Second));
                _pairs.Add(new Pair <MeshNode, MeshNode>(pair.Second, pair.First));
            }

            var renderTargetPool = _graphicsService.RenderTargetPool;

            if (_pairs.Count == 0)
            {
                renderTargetPool.Recycle(_intersectionImage);
                _intersectionImage = null;
                return;
            }

            // Color and alpha are applied in RenderIntersection().
            _color = color;
            _alpha = alpha;

            var graphicsDevice = _graphicsService.GraphicsDevice;

            // Save original render states.
            var originalBlendState        = graphicsDevice.BlendState;
            var originalDepthStencilState = graphicsDevice.DepthStencilState;
            var originalRasterizerState   = graphicsDevice.RasterizerState;
            var originalScissorRectangle  = graphicsDevice.ScissorRectangle;

            // Get offscreen render targets.
            var viewport = context.Viewport;

            viewport.X      = 0;
            viewport.Y      = 0;
            viewport.Width  = (int)(viewport.Width / DownsampleFactor);
            viewport.Height = (int)(viewport.Height / DownsampleFactor);
            var renderTargetFormat = new RenderTargetFormat(viewport.Width, viewport.Height, false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8);

            // Try to reuse any existing render targets.
            // (Usually they are recycled in RenderIntersection()).
            var currentScene = _intersectionImage;

            if (currentScene == null || !renderTargetFormat.IsCompatibleWith(currentScene))
            {
                currentScene.SafeDispose();
                currentScene = renderTargetPool.Obtain2D(renderTargetFormat);
            }
            var lastScene = renderTargetPool.Obtain2D(renderTargetFormat);

            // Set shared effect parameters.
            var cameraNode = context.CameraNode;
            var view       = (Matrix)cameraNode.View;
            var projection = cameraNode.Camera.Projection;
            var near       = projection.Near;
            var far        = projection.Far;

            _parameterViewportSize.SetValue(new Vector2(viewport.Width, viewport.Height));

            // The DepthEpsilon has to be tuned if depth peeling does not work because
            // of numerical problems equality z comparisons.
            _parameterCameraParameters.SetValue(new Vector3(near, far - near, 0.0000001f));
            _parameterView.SetValue(view);
            _parameterProjection.SetValue((Matrix)projection);

            var defaultTexture = _graphicsService.GetDefaultTexture2DBlack();

            // Handle all pairs.
            bool isFirstPass = true;

            while (true)
            {
                // Find a mesh node A and all mesh nodes to which it needs to be clipped.
                MeshNode meshNodeA = null;
                _partners.Clear();
                for (int i = 0; i < _pairs.Count; i++)
                {
                    var pair = _pairs[i];

                    if (pair.First == null)
                    {
                        continue;
                    }

                    if (meshNodeA == null)
                    {
                        meshNodeA = pair.First;
                    }

                    if (pair.First == meshNodeA)
                    {
                        _partners.Add(pair.Second);

                        //  Remove this pair.
                        _pairs[i] = new Pair <MeshNode, MeshNode>();
                    }
                }

                // Abort if we have handled all pairs.
                if (meshNodeA == null)
                {
                    break;
                }

                var worldTransformA = (Matrix)(meshNodeA.PoseWorld * Matrix.CreateScale(meshNodeA.ScaleWorld));

                if (EnableScissorTest)
                {
                    // Scissor rectangle of A.
                    var scissorA = GraphicsHelper.GetScissorRectangle(context.CameraNode, viewport, meshNodeA);

                    // Union of scissor rectangles of partners.
                    Rectangle partnerRectangle = GraphicsHelper.GetScissorRectangle(context.CameraNode, viewport, _partners[0]);
                    for (int i = 1; i < _partners.Count; i++)
                    {
                        var a = GraphicsHelper.GetScissorRectangle(context.CameraNode, viewport, _partners[i]);
                        partnerRectangle = Rectangle.Union(partnerRectangle, a);
                    }

                    // Use intersection of A and partners.
                    graphicsDevice.ScissorRectangle = Rectangle.Intersect(scissorA, partnerRectangle);

                    // We store the union of all scissor rectangles for use in RenderIntersection().
                    if (isFirstPass)
                    {
                        _totalScissorRectangle = graphicsDevice.ScissorRectangle;
                    }
                    else
                    {
                        _totalScissorRectangle = Rectangle.Union(_totalScissorRectangle, graphicsDevice.ScissorRectangle);
                    }
                }

                // Depth peeling of A.
                for (int layer = 0; layer < maxConvexity; layer++)
                {
                    // Set and clear render target.
                    graphicsDevice.SetRenderTarget(currentScene);
                    graphicsDevice.Clear(new Color(1, 1, 1, 0)); // RGB = "a large depth", A = "empty area"

                    // Render a depth layer of A.
                    graphicsDevice.DepthStencilState = DepthStencilStateWriteLess;
                    graphicsDevice.BlendState        = BlendState.Opaque;
                    graphicsDevice.RasterizerState   = EnableScissorTest ? CullCounterClockwiseScissor : RasterizerState.CullCounterClockwise;
                    _parameterWorld.SetValue(worldTransformA);
                    _parameterTexture.SetValue((layer == 0) ? defaultTexture : lastScene);
                    _passPeel.Apply();
                    foreach (var submesh in meshNodeA.Mesh.Submeshes)
                    {
                        submesh.Draw();
                    }

                    // Render partners to set stencil.
                    graphicsDevice.DepthStencilState = DepthStencilStateOnePassStencilFail;
                    graphicsDevice.BlendState        = BlendStateNoWrite;
                    graphicsDevice.RasterizerState   = EnableScissorTest ? CullNoneScissor : RasterizerState.CullNone;
                    foreach (var partner in _partners)
                    {
                        _parameterWorld.SetValue((Matrix)(partner.PoseWorld * Matrix.CreateScale(partner.ScaleWorld)));
                        _passMark.Apply();
                        foreach (var submesh in partner.Mesh.Submeshes)
                        {
                            submesh.Draw();
                        }
                    }

                    // Clear depth buffer. Leave stencil buffer unchanged.
                    graphicsDevice.Clear(ClearOptions.DepthBuffer, new Color(0, 1, 0), 1, 0);

                    // Render A to compute lighting.
                    graphicsDevice.DepthStencilState = DepthStencilStateStencilNotEqual0;
                    graphicsDevice.BlendState        = BlendState.Opaque;
                    graphicsDevice.RasterizerState   = EnableScissorTest ? CullCounterClockwiseScissor :  RasterizerState.CullCounterClockwise;
                    _parameterWorld.SetValue(worldTransformA);
                    _passDraw.Apply();
                    foreach (var submesh in meshNodeA.Mesh.Submeshes)
                    {
                        submesh.Draw();
                    }

                    // Combine last intersection image with current.
                    if (!isFirstPass)
                    {
                        graphicsDevice.DepthStencilState = DepthStencilState.DepthRead;
                        graphicsDevice.BlendState        = BlendState.Opaque;
                        graphicsDevice.RasterizerState   = EnableScissorTest ? CullNoneScissor : RasterizerState.CullNone;
                        _parameterTexture.SetValue(lastScene);
                        _passCombine.Apply();
                        graphicsDevice.DrawFullScreenQuad();
                    }

                    isFirstPass = false;

                    // ----- Swap render targets.
                    MathHelper.Swap(ref lastScene, ref currentScene);
                }
            }

            // Store final images for RenderIntersection.
            _intersectionImage = lastScene;

            // Scale scissor rectangle back to full-screen resolution.
            if (DownsampleFactor > 1)
            {
                _totalScissorRectangle.X      = (int)(_totalScissorRectangle.X * DownsampleFactor);
                _totalScissorRectangle.Y      = (int)(_totalScissorRectangle.Y * DownsampleFactor);
                _totalScissorRectangle.Width  = (int)(_totalScissorRectangle.Width * DownsampleFactor);
                _totalScissorRectangle.Height = (int)(_totalScissorRectangle.Height * DownsampleFactor);
            }


            // Restore original render state.
            graphicsDevice.BlendState        = originalBlendState ?? BlendState.Opaque;
            graphicsDevice.DepthStencilState = originalDepthStencilState ?? DepthStencilState.Default;
            graphicsDevice.RasterizerState   = originalRasterizerState ?? RasterizerState.CullCounterClockwise;
            graphicsDevice.ScissorRectangle  = originalScissorRectangle;

            renderTargetPool.Recycle(currentScene);
            _partners.Clear();
            _pairs.Clear();
        }
Exemplo n.º 23
0
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="factory">
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class containing
        /// the image to process.
        /// </param>
        /// <returns>
        /// The processed image from the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public Image ProcessImage(ImageFactory factory)
        {
            Bitmap newImage = null;
            Image  image    = factory.Image;

            try
            {
                int        sourceWidth  = image.Width;
                int        sourceHeight = image.Height;
                RectangleF rectangleF;
                CropLayer  cropLayer = this.DynamicParameter;

                if (cropLayer.CropMode == CropMode.Percentage)
                {
                    // Fix for whole numbers.
                    float percentageLeft   = cropLayer.Left > 1 ? cropLayer.Left / 100 : cropLayer.Left;
                    float percentageRight  = cropLayer.Right > 1 ? cropLayer.Right / 100 : cropLayer.Right;
                    float percentageTop    = cropLayer.Top > 1 ? cropLayer.Top / 100 : cropLayer.Top;
                    float percentageBottom = cropLayer.Bottom > 1 ? cropLayer.Bottom / 100 : cropLayer.Bottom;

                    // Work out the percentages.
                    float left   = percentageLeft * sourceWidth;
                    float top    = percentageTop * sourceHeight;
                    float width  = percentageRight < 1 ? (1 - percentageLeft - percentageRight) * sourceWidth : sourceWidth;
                    float height = percentageBottom < 1 ? (1 - percentageTop - percentageBottom) * sourceHeight : sourceHeight;

                    rectangleF = new RectangleF(left, top, width, height);
                }
                else
                {
                    rectangleF = new RectangleF(cropLayer.Left, cropLayer.Top, cropLayer.Right, cropLayer.Bottom);
                }

                Rectangle rectangle = Rectangle.Round(rectangleF);

                if (rectangle.X < sourceWidth && rectangle.Y < sourceHeight)
                {
                    if (rectangle.Width > (sourceWidth - rectangle.X))
                    {
                        rectangle.Width = sourceWidth - rectangle.X;
                    }

                    if (rectangle.Height > (sourceHeight - rectangle.Y))
                    {
                        rectangle.Height = sourceHeight - rectangle.Y;
                    }

                    newImage = new Bitmap(rectangle.Width, rectangle.Height, PixelFormat.Format32bppPArgb);
                    newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

                    int       rotationValue = 0;
                    const int orientation   = (int)ExifPropertyTag.Orientation;
                    bool      rotate        = factory.PreserveExifData && factory.ExifPropertyItems.ContainsKey(orientation);
                    if (rotate)
                    {
                        rotationValue = factory.ExifPropertyItems[orientation].Value[0];
                        this.ForwardRotateFlip(rotationValue, ref image);
                    }

                    using (Graphics graphics = Graphics.FromImage(newImage))
                    {
                        GraphicsHelper.SetGraphicsOptions(graphics);

                        // An unwanted border appears when using InterpolationMode.HighQualityBicubic to resize the image
                        // as the algorithm appears to be pulling averaging detail from surrounding pixels beyond the edge
                        // of the image. Using the ImageAttributes class to specify that the pixels beyond are simply mirror
                        // images of the pixels within solves this problem.
                        using (ImageAttributes wrapMode = new ImageAttributes())
                        {
                            wrapMode.SetWrapMode(WrapMode.TileFlipXY);

                            graphics.DrawImage(
                                image,
                                new Rectangle(0, 0, rectangle.Width, rectangle.Height),
                                rectangle.X,
                                rectangle.Y,
                                rectangle.Width,
                                rectangle.Height,
                                GraphicsUnit.Pixel,
                                wrapMode);
                        }
                    }

                    // Reassign the image.
                    image.Dispose();
                    image = newImage;

                    if (rotate)
                    {
                        this.ReverseRotateFlip(rotationValue, ref image);
                    }

                    if (factory.PreserveExifData && factory.ExifPropertyItems.Any())
                    {
                        // Set the width EXIF data.
                        factory.SetPropertyItem(ExifPropertyTag.ImageWidth, (ushort)image.Width);

                        // Set the height EXIF data.
                        factory.SetPropertyItem(ExifPropertyTag.ImageHeight, (ushort)image.Height);
                    }
                }
            }
            catch (Exception ex)
            {
                newImage?.Dispose();

                throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex);
            }

            return(image);
        }
        public override void Render(IList <SceneNode> nodes, RenderContext context, RenderOrder order)
        {
            if (nodes == null)
            {
                throw new ArgumentNullException("nodes");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            int numberOfNodes = nodes.Count;

            if (numberOfNodes == 0)
            {
                return;
            }

            context.Validate(_effect);
            context.ThrowIfCameraMissing();

            var graphicsDevice   = _effect.GraphicsDevice;
            var savedRenderState = new RenderStateSnapshot(graphicsDevice);

            graphicsDevice.DepthStencilState = DepthStencilState.None;
            graphicsDevice.RasterizerState   = RasterizerState.CullNone;

            // Set camera properties.
            var    cameraNode  = context.CameraNode;
            var    cameraPose  = cameraNode.PoseWorld;
            Matrix viewInverse = cameraPose;

            _parameterViewInverse.SetValue(viewInverse);
            _parameterGBuffer0.SetValue(context.GBuffer0);

            Viewport viewport = context.Viewport;

            _parameterParameters0.SetValue(new Vector2(viewport.Width, viewport.Height));

            // Set jitter map.
            if (_jitterMap == null)
            {
                _jitterMap = NoiseHelper.GetGrainTexture(context.GraphicsService, NoiseHelper.DefaultJitterMapWidth);
            }

            _parameterJitterMap.SetValue(_jitterMap);

            float cameraFar = context.CameraNode.Camera.Projection.Far;

            for (int i = 0; i < numberOfNodes; i++)
            {
                var lightNode = nodes[i] as LightNode;
                if (lightNode == null)
                {
                    continue;
                }

                var shadow = lightNode.Shadow as CascadedShadow;
                if (shadow == null)
                {
                    continue;
                }

                if (shadow.ShadowMap == null || shadow.ShadowMask == null)
                {
                    continue;
                }

                // The effect must only render in a specific channel.
                // Do not change blend state if the correct write channels is already set, e.g. if this
                // shadow is part of a CompositeShadow, the correct blend state is already set.
                if ((int)graphicsDevice.BlendState.ColorWriteChannels != (1 << shadow.ShadowMaskChannel))
                {
                    graphicsDevice.BlendState = GraphicsHelper.BlendStateWriteSingleChannel[shadow.ShadowMaskChannel];
                }

                _parameterParameters1.SetValue(new Vector4(
                                                   shadow.FadeOutRange,
                                                   shadow.Distances[shadow.NumberOfCascades - 1],
                                                   shadow.VisualizeCascades ? 1 : 0,
                                                   shadow.ShadowFog));

                float filterRadius = shadow.FilterRadius;

                // If we use a subset of the Poisson kernel, we have to normalize the scale.
                int numberOfSamples = Math.Min(shadow.NumberOfSamples, StandardShadowMaskRenderer.PoissonKernel.Length);

                // Not all shader passes support cascade visualization. Use a similar pass instead.
                if (shadow.VisualizeCascades)
                {
                    if (numberOfSamples < 0)
                    {
                        numberOfSamples = 4;
                    }
                    else if (numberOfSamples == 0)
                    {
                        numberOfSamples = 1;
                        filterRadius    = 0;
                    }
                }

                // The best dithered CSM supports max 22 samples.
                if (shadow.CascadeSelection == ShadowCascadeSelection.BestDithered && numberOfSamples > 22)
                {
                    numberOfSamples = 22;
                }

                if (numberOfSamples > 0)
                {
                    filterRadius /= StandardShadowMaskRenderer.PoissonKernel[numberOfSamples - 1].Length();
                }

                _parameterParameters2.SetValue(new Vector4(
                                                   shadow.ShadowMap.Width,
                                                   shadow.ShadowMap.Height,
                                                   filterRadius,
                                                   // The StandardShadow.JitterResolution is the number of texels per world unit.
                                                   // In the shader the parameter JitterResolution contains the division by the jitter map size.
                                                   shadow.JitterResolution / _jitterMap.Width));

                // Split distances.
                if (_parameterDistances != null)
                {
                    // Set not used entries to large values.
                    Vector4 distances = shadow.Distances;
                    for (int j = shadow.NumberOfCascades; j < 4; j++)
                    {
                        distances[j] = 10 * cameraFar;
                    }

                    _parameterDistances.SetValue((Vector4)distances);
                }

                Debug.Assert(shadow.ViewProjections.Length == 4);
                for (int j = 0; j < _matrices.Length; j++)
                {
                    _matrices[j] = viewInverse * shadow.ViewProjections[j];
                }

                _parameterShadowMatrices.SetValue(_matrices);

                _parameterDepthBias.SetValue((Vector4)shadow.EffectiveDepthBias);
                _parameterNormalOffset.SetValue((Vector4)shadow.EffectiveNormalOffset);

                Vector3 lightBackwardWorld = lightNode.PoseWorld.Orientation.GetColumn(2);
                _parameterLightDirection.SetValue((Vector3)cameraPose.ToLocalDirection(lightBackwardWorld));
                _parameterNumberOfCascades.SetValue(shadow.NumberOfCascades);
                _parameterShadowMap.SetValue(shadow.ShadowMap);

                var      rectangle           = GraphicsHelper.GetViewportRectangle(cameraNode, viewport, lightNode);
                Vector2F texCoordTopLeft     = new Vector2F(rectangle.Left / (float)viewport.Width, rectangle.Top / (float)viewport.Height);
                Vector2F texCoordBottomRight = new Vector2F(rectangle.Right / (float)viewport.Width, rectangle.Bottom / (float)viewport.Height);
                GraphicsHelper.GetFrustumFarCorners(cameraNode.Camera.Projection, texCoordTopLeft, texCoordBottomRight, _frustumFarCorners);
                _parameterFrustumCorners.SetValue(_frustumFarCorners);

                var pass = GetPass(numberOfSamples, shadow.CascadeSelection, shadow.VisualizeCascades);

                if (numberOfSamples > 0)
                {
                    if (_lastNumberOfSamples != numberOfSamples)
                    {
                        // Create an array with the first n samples and the rest set to 0.
                        _lastNumberOfSamples = numberOfSamples;
                        for (int j = 0; j < numberOfSamples; j++)
                        {
                            _samples[j].Y = StandardShadowMaskRenderer.PoissonKernel[j].Y;
                            _samples[j].X = StandardShadowMaskRenderer.PoissonKernel[j].X;
                            _samples[j].Z = 1.0f / numberOfSamples;
                        }

                        // Set the rest to zero.
                        for (int j = numberOfSamples; j < _samples.Length; j++)
                        {
                            _samples[j] = Vector3.Zero;
                        }

                        _parameterSamples.SetValue(_samples);
                    }
                    else if (i == 0)
                    {
                        // Apply offsets in the first loop.
                        _parameterSamples.SetValue(_samples);
                    }
                }

                pass.Apply();

                graphicsDevice.DrawQuad(rectangle);
            }

            _parameterGBuffer0.SetValue((Texture2D)null);
            _parameterJitterMap.SetValue((Texture2D)null);
            _parameterShadowMap.SetValue((Texture2D)null);
            savedRenderState.Restore();
        }
Exemplo n.º 25
0
        private void Draw(ref EffectPassBinding passBinding, RenderContext context, int index, int count, RenderOrder order)
        {
            var jobs       = _jobs.Array;
            var cameraNode = context.CameraNode;
            var cameraPose = cameraNode.PoseWorld;

            var graphicsDevice = context.GraphicsService.GraphicsDevice;

            // Flag: true if the box vertex/index buffers are not set in the graphics device.
            bool setBoxBuffers = true;

            foreach (var pass in passBinding)
            {
                for (int i = index; i < index + count; i++)
                {
                    var materialInstanceBinding = jobs[i].MaterialInstanceBinding;
                    var decalNode = jobs[i].DecalNode;
                    var decalPose = decalNode.PoseWorld;

                    // Update and apply local, per-instance and per-pass bindings.
                    foreach (var binding in materialInstanceBinding.ParameterBindings)
                    {
                        if (binding.Description.Hint == EffectParameterHint.PerPass)
                        {
                            binding.Update(context);
                        }

                        binding.Apply(context);
                    }

                    pass.Apply();

                    bool drawWithQuad = false;
                    if (!ClipAtNearPlane)
                    {
                        // ----- Check if near plane intersects the decal box.

                        // First make a simple AABB check in world space.
                        if (GeometryHelper.HaveContact(_cameraNearPlaneAabbWorld, decalNode.Aabb))
                        {
                            // Make exact check of decal box against camera near plane AABB in camera space.
                            var decalBoxExtent = new Vector3F(1, 1, 1);
                            decalBoxExtent *= decalNode.ScaleLocal;
                            var decalBoxCenter = new Vector3F(0, 0, -decalNode.ScaleLocal.Z / 2);

                            // Get pose of decal box in view space.
                            var decalBoxPose = new Pose(
                                cameraPose.ToLocalPosition(decalPose.Position + decalPose.Orientation * decalBoxCenter),
                                cameraPose.Orientation.Transposed * decalPose.Orientation);

                            // Aabb of camera near plane in view space.
                            var projection          = cameraNode.Camera.Projection;
                            var cameraNearPlaneAabb = new Aabb(
                                new Vector3F(projection.Left, projection.Bottom, -projection.Near),
                                new Vector3F(projection.Right, projection.Top, -projection.Near));

                            drawWithQuad = GeometryHelper.HaveContact(cameraNearPlaneAabb, decalBoxExtent, decalBoxPose, true);
                        }
                    }

                    if (!drawWithQuad)
                    {
                        // Draw a box primitive.

                        if (setBoxBuffers)
                        {
                            graphicsDevice.SetVertexBuffer(_vertexBuffer);
                            graphicsDevice.Indices = _indexBuffer;
                            setBoxBuffers          = false;
                        }

#if MONOGAME
                        graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, NumberOfPrimitives);
#else
                        graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, NumberOfVertices, 0, NumberOfPrimitives);
#endif
                    }
                    else
                    {
                        // Draw a quad at the near plane because the camera is inside the box.
                        // The quad vertices must be given decal space!

                        var      projection        = cameraNode.Camera.Projection;
                        Vector3F scale             = decalNode.ScaleWorld;
                        Pose     cameraToDecalPose = decalPose.Inverse * cameraPose;

                        Vector4F scissor = GraphicsHelper.GetBounds(cameraNode, decalNode);
                        // Use a bias to avoid that this quad is clipped by the near plane.
                        const float bias   = 1.0001f;
                        float       left   = InterpolationHelper.Lerp(projection.Left, projection.Right, scissor.X) * bias;
                        float       top    = InterpolationHelper.Lerp(projection.Top, projection.Bottom, scissor.Y) * bias;
                        float       right  = InterpolationHelper.Lerp(projection.Left, projection.Right, scissor.Z) * bias;
                        float       bottom = InterpolationHelper.Lerp(projection.Top, projection.Bottom, scissor.W) * bias;
                        float       z      = -projection.Near * bias;
                        _quadVertices[0]    = cameraToDecalPose.ToWorldPosition(new Vector3F(left, top, z));
                        _quadVertices[0].X /= scale.X;
                        _quadVertices[0].Y /= scale.Y;
                        _quadVertices[0].Z /= scale.Z;
                        _quadVertices[1]    = cameraToDecalPose.ToWorldPosition(new Vector3F(right, top, z));
                        _quadVertices[1].X /= scale.X;
                        _quadVertices[1].Y /= scale.Y;
                        _quadVertices[1].Z /= scale.Z;
                        _quadVertices[2]    = cameraToDecalPose.ToWorldPosition(new Vector3F(left, bottom, z));
                        _quadVertices[2].X /= scale.X;
                        _quadVertices[2].Y /= scale.Y;
                        _quadVertices[2].Z /= scale.Z;
                        _quadVertices[3]    = cameraToDecalPose.ToWorldPosition(new Vector3F(right, bottom, z));
                        _quadVertices[3].X /= scale.X;
                        _quadVertices[3].Y /= scale.Y;
                        _quadVertices[3].Z /= scale.Z;

                        graphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleStrip, _quadVertices, 0, 2, VertexPosition.VertexDeclaration);

                        // Remember that the device vertex/index buffers are not set anymore.
                        setBoxBuffers = true;
                    }
                }
            }
        }
Exemplo n.º 26
0
        public override void Render(IList <SceneNode> nodes, RenderContext context, RenderOrder order)
        {
            if (nodes == null)
            {
                throw new ArgumentNullException("nodes");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            int numberOfNodes = nodes.Count;

            if (numberOfNodes == 0)
            {
                return;
            }

            context.Validate(_effect);
            context.ThrowIfCameraMissing();

            var graphicsDevice   = _effect.GraphicsDevice;
            var savedRenderState = new RenderStateSnapshot(graphicsDevice);

            graphicsDevice.DepthStencilState = DepthStencilState.None;
            graphicsDevice.RasterizerState   = RasterizerState.CullNone;
            graphicsDevice.BlendState        = GraphicsHelper.BlendStateAdd;

            var viewport = graphicsDevice.Viewport;

            _parameterViewportSize.SetValue(new Vector2(viewport.Width, viewport.Height));
            _parameterGBuffer0.SetValue(context.GBuffer0);
            _parameterGBuffer1.SetValue(context.GBuffer1);

            var    cameraNode     = context.CameraNode;
            Pose   cameraPose     = cameraNode.PoseWorld;
            Matrix viewProjection = (Matrix)cameraNode.View * cameraNode.Camera.Projection;

            // Update SceneNode.LastFrame for all visible nodes.
            int frame = context.Frame;

            context.CameraNode.LastFrame = frame;

            bool isHdrEnabled = context.IsHdrEnabled();

            // Copy nodes to list and sort them by persistent IDs. This is necessary to avoid popping when
            // light probes overlap.
            _jobs.Clear();
            for (int i = 0; i < numberOfNodes; i++)
            {
                var lightNode = nodes[i] as LightNode;
                if (lightNode == null)
                {
                    continue;
                }

                var light = lightNode.Light as ImageBasedLight;
                if (light == null || light.Texture == null)
                {
                    continue;
                }

                // Build sort-ID - high values for lights which should be rendered last.
                ulong sortId = 0;

                // Render infinite lights first and others later.
                if (!(light.Shape is InfiniteShape))
                {
                    sortId += ((ulong)1 << 32); // Set high value above 32-bit range.
                }
                // Sort by priority. Lights with higher priority should be rendered last
                // (= over the other lights).
                // Shift priority (signed int) to positive range and add it.
                sortId += (ulong)((long)lightNode.Priority + int.MaxValue + 1);

                // Shift sortId and add light.Id in least significant bits.
                sortId = (sortId << 16) | (ushort)light.Id;

                // Add to list for sorting.
                _jobs.Add(new Job
                {
                    SortId    = sortId,
                    LightNode = lightNode,
                });
            }

            // Sort by ascending sort-ID value.
            _jobs.Sort(Comparer.Instance);

            numberOfNodes = _jobs.Count;
            for (int i = 0; i < numberOfNodes; i++)
            {
                var lightNode = _jobs[i].LightNode;
                var light     = (ImageBasedLight)lightNode.Light;

                // LightNode is visible in current frame.
                lightNode.LastFrame = frame;

                // ReSharper disable CompareOfFloatsByEqualityOperator
                bool enableDiffuse = !(Numeric.IsNaN(light.DiffuseIntensity) || (light.DiffuseIntensity == 0.0f && light.BlendMode == 0.0f));
                // ReSharper restore CompareOfFloatsByEqualityOperator

                bool enableSpecular = !Numeric.IsNaN(light.SpecularIntensity);
                if (!enableDiffuse && !enableSpecular)
                {
                    continue;
                }

                float hdrScale = isHdrEnabled ? light.HdrScale : 1;

                // We use 1x1 mipmap level for diffuse.
                // (2x2 is still okay, 4x4 already looks a bit like a specular reflection.)
                float diffuseIntensity = enableDiffuse ? light.DiffuseIntensity : 0.0f;
                _parameterParameters0.SetValue(new Vector4(
                                                   (Vector3)light.Color * diffuseIntensity * hdrScale, // DiffuseColor
                                                   Math.Max(0, light.Texture.LevelCount - 1)));        // Diffuse mip level.

                // Shader supports only RGBM.
                float rgbmMax;
                if (light.Encoding is RgbmEncoding)
                {
                    rgbmMax = GraphicsHelper.ToGamma(((RgbmEncoding)light.Encoding).Max);
                }
                else if (light.Encoding is SRgbEncoding)
                {
                    // Decoding RGBM with MaxValue 1 is equal to encoding sRGB, i.e. only
                    // gamma-to-linear is performed (assuming that the cube map alpha channel is 1).
                    rgbmMax = 1;
                }
                else
                {
                    throw new NotSupportedException(
                              "ImageBasedLight must use sRGB or RGBM encoding. Other encodings are not yet supported.");
                }

                _parameterParameters1.SetValue(new Vector4(
                                                   (Vector3)light.Color * light.SpecularIntensity * hdrScale, // SpecularColor
                                                   rgbmMax));

                // Bounding box can be a box shape or an infinite shape.
                var boundingBoxShape = lightNode.Shape as BoxShape;

                // Get extent of bounding box. For infinite shapes we simply set a large value.
                var boundingBoxExtent = boundingBoxShape != null
                              ? boundingBoxShape.Extent * lightNode.ScaleWorld
                              : new Vector3F(1e20f);

                // Falloff can only be used for box shapes but not for infinite shapes.
                float falloffRange = (boundingBoxShape != null) ? light.FalloffRange : 0;

                // AABB for localization in local space.
                // Use invalid min and max (min > max) to disable localization.
                Aabb projectionAabb = new Aabb(new Vector3F(1), new Vector3F(-1));
                if (light.EnableLocalizedReflection)
                {
                    if (light.LocalizedReflectionBox.HasValue)
                    {
                        // User defined AABB.
                        projectionAabb          = light.LocalizedReflectionBox.Value;
                        projectionAabb.Minimum *= lightNode.ScaleWorld;
                        projectionAabb.Maximum *= lightNode.ScaleWorld;
                    }
                    else if (boundingBoxShape != null)
                    {
                        // AABB is equal to the bounding box.
                        projectionAabb = new Aabb(-boundingBoxExtent / 2, boundingBoxExtent / 2);
                    }
                }

                _parameterParameters2.SetValue(new Vector4(
                                                   boundingBoxExtent.X / 2,
                                                   boundingBoxExtent.Y / 2,
                                                   boundingBoxExtent.Z / 2,
                                                   falloffRange));

                _parameterParameters3.SetValue(new Vector4(
                                                   projectionAabb.Minimum.X,
                                                   projectionAabb.Minimum.Y,
                                                   projectionAabb.Minimum.Z,
                                                   light.Texture.Size));

                _parameterParameters4.SetValue(new Vector4(
                                                   projectionAabb.Maximum.X,
                                                   projectionAabb.Maximum.Y,
                                                   projectionAabb.Maximum.Z,
                                                   light.BlendMode));

                // Precomputed value for specular reflection lookup.
                const float sqrt3 = 1.7320508075688772935274463415059f;
                _parameterPrecomputedTerm.SetValue((float)Math.Log(light.Texture.Size * sqrt3, 2.0));

                _parameterEnvironmentMap.SetValue(light.Texture);

                // Compute screen space rectangle and FrustumFarCorners.
                var rectangle           = GraphicsHelper.GetViewportRectangle(cameraNode, viewport, lightNode);
                var texCoordTopLeft     = new Vector2F(rectangle.Left / (float)viewport.Width, rectangle.Top / (float)viewport.Height);
                var texCoordBottomRight = new Vector2F(rectangle.Right / (float)viewport.Width, rectangle.Bottom / (float)viewport.Height);
                GraphicsHelper.GetFrustumFarCorners(cameraNode.Camera.Projection, texCoordTopLeft, texCoordBottomRight, _frustumFarCorners);

                // Convert frustum far corners from view space to world space.
                for (int j = 0; j < _frustumFarCorners.Length; j++)
                {
                    _frustumFarCorners[j] = (Vector3)cameraPose.ToWorldDirection((Vector3F)_frustumFarCorners[j]);
                }

                _parameterFrustumCorners.SetValue(_frustumFarCorners);

                EffectPass passLight = null;
                if (enableDiffuse && enableSpecular)
                {
                    passLight = _passDiffuseAndSpecularLight;
                }
                else if (enableDiffuse)
                {
                    // TODO: Can we disable writes to LightBuffer1?
                    passLight = _passDiffuseLight;
                }
                else
                {
                    // TODO: Can we disable writes to LightBuffer0?
                    passLight = _passSpecularLight;
                }

                // Simply render fullscreen quad if we do not have a clip shape or a bounding box.
                if (lightNode.Clip == null && boundingBoxShape == null)
                {
                    graphicsDevice.BlendState = BlendState.AlphaBlend;

                    // Transform matrix transforms from world space with camera as origin to
                    // local space. The lightNode.Scale is already in the other parameters and not
                    // used in Transform.
                    var pose = lightNode.PoseWorld;
                    pose.Position -= cameraPose.Position;
                    _parameterTransform.SetValue(pose.Inverse);

                    passLight.Apply();
                    graphicsDevice.DrawFullScreenQuad();
                    continue;
                }

                // ----- Render clip mesh.
                graphicsDevice.DepthStencilState = GraphicsHelper.DepthStencilStateOnePassStencilFail;
                graphicsDevice.BlendState        = GraphicsHelper.BlendStateNoColorWrite;
                if (lightNode.Clip != null)
                {
                    // Using user-defined clip shape.
                    var data = lightNode.RenderData as LightRenderData;
                    if (data == null)
                    {
                        data = new LightRenderData();
                        lightNode.RenderData = data;
                    }

                    data.UpdateClipSubmesh(context.GraphicsService, lightNode);
                    _parameterTransform.SetValue((Matrix)data.ClipMatrix * viewProjection);
                    _passClip.Apply();
                    data.ClipSubmesh.Draw();

                    graphicsDevice.DepthStencilState = lightNode.InvertClip
            ? GraphicsHelper.DepthStencilStateStencilEqual0
            : GraphicsHelper.DepthStencilStateStencilNotEqual0;
                }
                else
                {
                    Debug.Assert(boundingBoxShape != null);

                    // Use box submesh.
                    if (_boxSubmesh == null)
                    {
                        _boxSubmesh = MeshHelper.GetBox(context.GraphicsService);
                    }

                    Matrix44F world = lightNode.PoseWorld
                                      * Matrix44F.CreateScale(lightNode.ScaleLocal * boundingBoxShape.Extent);
                    _parameterTransform.SetValue((Matrix)world * viewProjection);

                    _passClip.Apply();
                    _boxSubmesh.Draw();

                    graphicsDevice.DepthStencilState = GraphicsHelper.DepthStencilStateStencilNotEqual0;
                }

                graphicsDevice.BlendState = BlendState.AlphaBlend;

                {
                    // Transform matrix transforms from world space with camera as origin to
                    // local space. The lightNode.Scale is already in the other parameters and not
                    // used in Transform.
                    var pose = lightNode.PoseWorld;
                    pose.Position -= cameraPose.Position;
                    _parameterTransform.SetValue(pose.Inverse);
                }

                // ----- Render full screen quad.
                passLight.Apply();
                graphicsDevice.DrawQuad(rectangle);
            }

            savedRenderState.Restore();
            _jobs.Clear();
        }
Exemplo n.º 27
0
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="factory">
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class containing
        /// the image to process.
        /// </param>
        /// <returns>
        /// The processed image from the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public Image ProcessImage(ImageFactory factory)
        {
            Bitmap newImage       = null;
            Bitmap mask           = null;
            Bitmap maskCropped    = null;
            Bitmap maskPositioned = null;
            Image  image          = factory.Image;

            try
            {
                int        width      = image.Width;
                int        height     = image.Height;
                ImageLayer parameters = this.DynamicParameter;
                mask = new Bitmap(parameters.Image);
                mask.SetResolution(image.HorizontalResolution, image.VerticalResolution);
                Point?position = parameters.Position;

                if (mask.Size != image.Size)
                {
                    Rectangle parent = new Rectangle(0, 0, width, height);
                    Rectangle child  = ImageMaths.GetFilteredBoundingRectangle(mask, 0, RgbaComponent.A);
                    maskCropped = new Bitmap(child.Width, child.Height, PixelFormat.Format32bppPArgb);
                    maskCropped.SetResolution(image.HorizontalResolution, image.VerticalResolution);

                    // First crop any bounding transparency.
                    using (Graphics graphics = Graphics.FromImage(maskCropped))
                    {
                        GraphicsHelper.SetGraphicsOptions(graphics);

                        graphics.Clear(Color.Transparent);
                        graphics.DrawImage(
                            mask,
                            new Rectangle(0, 0, child.Width, child.Height),
                            child.X,
                            child.Y,
                            child.Width,
                            child.Height,
                            GraphicsUnit.Pixel);
                    }

                    // Now position the mask in an image of the same dimensions as the original.
                    maskPositioned = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
                    maskPositioned.SetResolution(image.HorizontalResolution, image.VerticalResolution);
                    using (Graphics graphics = Graphics.FromImage(maskPositioned))
                    {
                        GraphicsHelper.SetGraphicsOptions(graphics, true);
                        graphics.Clear(Color.Transparent);

                        if (position != null)
                        {
                            // Apply the mask at the given position.
                            graphics.DrawImage(maskCropped, position.Value);
                        }
                        else
                        {
                            // Center it instead
                            RectangleF centered = ImageMaths.CenteredRectangle(parent, child);
                            graphics.DrawImage(maskCropped, new PointF(centered.X, centered.Y));
                        }
                    }

                    newImage = Effects.ApplyMask(image, maskPositioned);
                    maskCropped.Dispose();
                    maskPositioned.Dispose();
                }
                else
                {
                    newImage = Effects.ApplyMask(image, mask);
                    mask.Dispose();
                }

                image.Dispose();
                image = newImage;
            }
            catch (Exception ex)
            {
                mask?.Dispose();

                maskCropped?.Dispose();

                maskPositioned?.Dispose();

                newImage?.Dispose();

                throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex);
            }

            return(image);
        }
Exemplo n.º 28
0
        // draws the camera rectangle and crosshairs
        private void DrawCameraRect(SpriteBatch sb)
        {
            if (form != null && form.Visible)
            {
                // get the camera's world position
                Vector2 camTranslation = camera.Translation - new Vector2(GraphicsManager.Instance.Device.Viewport.Width / 2 / camera.Zoom.X, GraphicsManager.Instance.Viewport.Height / 2 / camera.Zoom.Y);
                // convert it from world to map coords
                Rectangle camRect = new Rectangle(
                    (int)(camTranslation.X / boardRenderer.Bounds.Width * form.Size.Width + form.AbsoluteLocation.X),
                    (int)(camTranslation.Y / boardRenderer.Bounds.Height * form.Size.Height + form.AbsoluteLocation.Y),
                    (int)((1920.0f / boardRenderer.Bounds.Width) * (float)form.Size.Width / camera.Zoom.X),
                    (int)((1080.0f / boardRenderer.Bounds.Height) * (float)form.Size.Height / camera.Zoom.Y));

                // calculate the vert and hori lines for the camera crosshairs
                Vector2 vertA = new Vector2(camRect.X + camRect.Width / 2, form.AbsoluteLocation.Y);
                Vector2 vertB = new Vector2(vertA.X, form.AbsoluteLocation.Y + form.AbsoluteBounds.Height);
                Vector2 horiA = new Vector2(form.AbsoluteLocation.X, camRect.Y + camRect.Height / 2);
                Vector2 horiB = new Vector2(form.AbsoluteLocation.X + form.AbsoluteBounds.Width, horiA.Y);

                // clamp cam rect to the form bounds
                if (camRect.X < form.AbsoluteLocation.X)
                {
                    camRect.Width -= form.AbsoluteLocation.X - camRect.X;
                    camRect.X      = form.AbsoluteLocation.X;
                }
                if (camRect.Y < form.AbsoluteLocation.Y)
                {
                    camRect.Height -= form.AbsoluteLocation.Y - camRect.Y;
                    camRect.Y       = form.AbsoluteLocation.Y;
                }
                if (camRect.X + camRect.Width > form.AbsoluteLocation.X + form.Size.Width)
                {
                    camRect.Width = form.AbsoluteLocation.X + form.Size.Width - camRect.X;
                }
                if (camRect.Y + camRect.Height > form.AbsoluteLocation.Y + form.Size.Height)
                {
                    camRect.Height = form.AbsoluteLocation.Y + form.Size.Height - camRect.Y;
                }

                // clamp crosshair to form bounds
                if (vertA.X < form.AbsoluteLocation.X)
                {
                    vertA.X = form.AbsoluteLocation.X;
                    vertB.X = vertA.X;
                }
                if (vertA.X > form.AbsoluteLocation.X + form.Size.Width)
                {
                    vertA.X = form.AbsoluteLocation.X + form.Size.Width;
                    vertB.X = vertA.X;
                }
                if (horiA.Y < form.AbsoluteLocation.Y)
                {
                    horiA.Y = form.AbsoluteLocation.Y;
                    horiB.Y = horiA.Y;
                }
                if (horiA.Y > form.AbsoluteLocation.Y + form.Size.Height)
                {
                    horiA.Y = form.AbsoluteLocation.Y + form.Size.Height;
                    horiB.Y = horiA.Y;
                }

                // draw the crosshairs
                GraphicsHelper.DrawLine(sb, vertA, vertB, 2, color);
                GraphicsHelper.DrawLine(sb, horiA, horiB, 2, color);

                // don't draw the cam rect if it does not have positive width or height
                if (camRect.Height < 0 || camRect.Width < 0)
                {
                    return;
                }
                // draw the cam rect
                GraphicsHelper.DrawRect(sb, camRect, 2, color);
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="factory">
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class containing
        /// the image to process.
        /// </param>
        /// <returns>
        /// The processed image from the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public Image ProcessImage(ImageFactory factory)
        {
            Image image = factory.Image;

            Bitmap overlay = null;

            try
            {
                ImageLayer imageLayer = this.DynamicParameter;
                overlay = new Bitmap(imageLayer.Image);

                // Set the resolution of the overlay and the image to match.
                overlay.SetResolution(image.HorizontalResolution, image.VerticalResolution);

                Size size          = imageLayer.Size;
                int  width         = image.Width;
                int  height        = image.Height;
                int  overlayWidth  = size != Size.Empty ? Math.Min(width, size.Width) : Math.Min(width, overlay.Width);
                int  overlayHeight = size != Size.Empty ? Math.Min(height, size.Height) : Math.Min(height, overlay.Height);

                Point?position = imageLayer.Position;
                int   opacity  = imageLayer.Opacity;

                if (image.Size != overlay.Size || image.Size != new Size(overlayWidth, overlayHeight))
                {
                    // Find the maximum possible dimensions and resize the image.
                    ResizeLayer layer   = new ResizeLayer(new Size(overlayWidth, overlayHeight), ResizeMode.Max);
                    Resizer     resizer = new Resizer(layer)
                    {
                        AnimationProcessMode = factory.AnimationProcessMode
                    };
                    overlay       = resizer.ResizeImage(overlay, factory.FixGamma);
                    overlayWidth  = overlay.Width;
                    overlayHeight = overlay.Height;
                }

                // Figure out bounds.
                Rectangle parent = new Rectangle(0, 0, width, height);
                Rectangle child  = new Rectangle(0, 0, overlayWidth, overlayHeight);

                // Apply opacity.
                if (opacity < 100)
                {
                    overlay = Adjustments.Alpha(overlay, opacity);
                }

                using (Graphics graphics = Graphics.FromImage(image))
                {
                    GraphicsHelper.SetGraphicsOptions(graphics, true);

                    if (position != null)
                    {
                        // Draw the image in position catering for overflow.
                        graphics.DrawImage(overlay, new Point(Math.Min(position.Value.X, width - overlayWidth), Math.Min(position.Value.Y, height - overlayHeight)));
                    }
                    else
                    {
                        RectangleF centered = ImageMaths.CenteredRectangle(parent, child);
                        graphics.DrawImage(overlay, new PointF(centered.X, centered.Y));
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex);
            }
            finally
            {
                overlay?.Dispose();
            }

            return(image);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Rotates the inside of an image to the given angle at the given position.
        /// </summary>
        /// <param name="image">
        /// The image to rotate
        /// </param>
        /// <param name="angleInDegrees">
        /// The angle in degrees.
        /// </param>
        /// <param name="keepSize">
        /// Whether to keep the image dimensions.
        /// <para>
        /// If set to true, the image is zoomed to fit the bounding area.
        /// </para>
        /// <para>
        /// If set to false, the area is cropped to fit the rotated image.
        /// </para>
        /// </param>
        /// <remarks>
        /// Based on the Rotate effect
        /// </remarks>
        /// <returns>
        /// The image rotated to the given angle at the given position.
        /// </returns>
        private Bitmap RotateImage(Image image, float angleInDegrees, bool keepSize)
        {
            var newSize = new Size(image.Width, image.Height);

            float zoom = ImageMaths.ZoomAfterRotation(image.Width, image.Height, angleInDegrees);

            // if we don't keep the image dimensions, calculate the new ones
            if (!keepSize)
            {
                newSize.Width  = Math.Max(1, (int)Math.Floor(newSize.Width / zoom));
                newSize.Height = Math.Max(1, (int)Math.Floor(newSize.Height / zoom));
            }

            // Center of the image
            float rotateAtX = Math.Abs(image.Width / 2);
            float rotateAtY = Math.Abs(image.Height / 2);

            // Create a new empty bitmap to hold rotated image
            var newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppPArgb);

            newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            // Make a graphics object from the empty bitmap
            using (var graphics = Graphics.FromImage(newImage))
            {
                GraphicsHelper.SetGraphicsOptions(graphics);

                if (keepSize)
                {
                    // Put the rotation point in the "center" of the image
                    graphics.TranslateTransform(rotateAtX, rotateAtY);

                    // Rotate the image
                    graphics.RotateTransform(angleInDegrees);

                    // Zooms the image to fit the area
                    graphics.ScaleTransform(zoom, zoom);

                    // Move the image back
                    graphics.TranslateTransform(-rotateAtX, -rotateAtY);

                    // Draw passed in image onto graphics object
                    graphics.DrawImage(image, new PointF(0, 0));
                }
                else
                {
                    float previousX = rotateAtX;
                    float previousY = rotateAtY;

                    // Calculate the difference between the center of the original image
                    // and the center of the new image.
                    rotateAtX = Math.Abs(newImage.Width / 2);
                    rotateAtY = Math.Abs(newImage.Height / 2);

                    // Put the rotation point in the "center" of the image
                    graphics.TranslateTransform(rotateAtX, rotateAtY);

                    // Rotate the image
                    graphics.RotateTransform(angleInDegrees);

                    // Draw passed in image onto graphics object
                    graphics.DrawImage(image, new PointF(-previousX, -previousY));
                }
            }

            image.Dispose();
            return(newImage);
        }
        public override void Render(IList <SceneNode> nodes, RenderContext context, RenderOrder order)
        {
            if (nodes == null)
            {
                throw new ArgumentNullException("nodes");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            int numberOfNodes = nodes.Count;

            if (numberOfNodes == 0)
            {
                return;
            }

            context.Validate(_effect);
            context.ThrowIfCameraMissing();

            var graphicsDevice   = _effect.GraphicsDevice;
            var savedRenderState = new RenderStateSnapshot(graphicsDevice);

            graphicsDevice.DepthStencilState = DepthStencilState.None;
            graphicsDevice.RasterizerState   = RasterizerState.CullNone;

            var cameraNode = context.CameraNode;

            _parameterViewInverse.SetValue(cameraNode.PoseWorld);
            _parameterGBuffer0.SetValue(context.GBuffer0);

            Viewport viewport = context.Viewport;

            _parameterParameters0.SetValue(new Vector2(viewport.Width, viewport.Height));

            if (_jitterMap == null)
            {
                _jitterMap = NoiseHelper.GetGrainTexture(context.GraphicsService, NoiseHelper.DefaultJitterMapWidth);
            }

            _parameterJitterMap.SetValue(_jitterMap);

            for (int i = 0; i < numberOfNodes; i++)
            {
                var lightNode = nodes[i] as LightNode;
                if (lightNode == null)
                {
                    continue;
                }

                var shadow = lightNode.Shadow as StandardShadow;
                if (shadow == null)
                {
                    continue;
                }

                if (shadow.ShadowMap == null || shadow.ShadowMask == null)
                {
                    continue;
                }

                // The effect must only render in a specific channel.
                // Do not change blend state if the correct write channels is already set, e.g. if this
                // shadow is part of a CompositeShadow, the correct blend state is already set.
                if ((int)graphicsDevice.BlendState.ColorWriteChannels != (1 << shadow.ShadowMaskChannel))
                {
                    graphicsDevice.BlendState = GraphicsHelper.BlendStateWriteSingleChannel[shadow.ShadowMaskChannel];
                }

                _parameterParameters1.SetValue(new Vector4(
                                                   shadow.Near,
                                                   shadow.Far,
                                                   shadow.EffectiveDepthBias,
                                                   shadow.EffectiveNormalOffset));

                // If we use a subset of the Poisson kernel, we have to normalize the scale.
                int   numberOfSamples = Math.Min(shadow.NumberOfSamples, PoissonKernel.Length);
                float filterRadius    = shadow.FilterRadius;
                if (numberOfSamples > 0)
                {
                    filterRadius /= PoissonKernel[numberOfSamples - 1].Length();
                }

                _parameterParameters2.SetValue(new Vector3(
                                                   shadow.ShadowMap.Width,
                                                   filterRadius,
                                                   // The StandardShadow.JitterResolution is the number of texels per world unit.
                                                   // In the shader the parameter JitterResolution contains the division by the jitter map size.
                                                   shadow.JitterResolution / _jitterMap.Width));

                _parameterLightPosition.SetValue((Vector3)cameraNode.PoseWorld.ToLocalPosition(lightNode.PoseWorld.Position));

                Matrix cameraViewToShadowView = cameraNode.PoseWorld * shadow.View;
                _parameterShadowView.SetValue(cameraViewToShadowView);
                _parameterShadowMatrix.SetValue(cameraViewToShadowView * shadow.Projection);
                _parameterShadowMap.SetValue(shadow.ShadowMap);

                var      rectangle           = GraphicsHelper.GetViewportRectangle(cameraNode, viewport, lightNode);
                Vector2F texCoordTopLeft     = new Vector2F(rectangle.Left / (float)viewport.Width, rectangle.Top / (float)viewport.Height);
                Vector2F texCoordBottomRight = new Vector2F(rectangle.Right / (float)viewport.Width, rectangle.Bottom / (float)viewport.Height);
                GraphicsHelper.GetFrustumFarCorners(cameraNode.Camera.Projection, texCoordTopLeft, texCoordBottomRight, _frustumFarCorners);
                _parameterFrustumCorners.SetValue(_frustumFarCorners);

                var pass = GetPass(numberOfSamples);

                if (numberOfSamples > 0)
                {
                    if (_lastNumberOfSamples != numberOfSamples)
                    {
                        // Create an array with the first n samples and the rest set to 0.
                        _lastNumberOfSamples = numberOfSamples;
                        for (int j = 0; j < numberOfSamples; j++)
                        {
                            _samples[j].X = PoissonKernel[j].X;
                            _samples[j].Y = PoissonKernel[j].Y;
                            _samples[j].Z = 1.0f / numberOfSamples;

                            // Note [HelmutG]: I have tried weights decreasing with distance but that did not
                            // look better.
                        }

                        // Set the rest to zero.
                        for (int j = numberOfSamples; j < _samples.Length; j++)
                        {
                            _samples[j] = Vector3.Zero;
                        }

                        _parameterSamples.SetValue(_samples);
                    }
                    else if (i == 0)
                    {
                        // Apply offsets in the first loop.
                        _parameterSamples.SetValue(_samples);
                    }
                }

                pass.Apply();

                graphicsDevice.DrawQuad(rectangle);
            }

            _parameterGBuffer0.SetValue((Texture2D)null);
            _parameterJitterMap.SetValue((Texture2D)null);
            _parameterShadowMap.SetValue((Texture2D)null);
            savedRenderState.Restore();
        }
 /// <summary>
 /// Detaches the specified manipulator.
 /// </summary>
 /// <param name="manipulator">The manipulator.</param>
 /// <param name="correspondingView">The corresponding view.</param>
 /// <param name="context">The context.</param>
 protected override void Detach(SceneManipulator manipulator, ViewInformation correspondingView, PerSceneContext context)
 {
     manipulator.Remove(context.BackgroundPainter);
     manipulator.RemoveResource(context.BackgroundTextureKey);
     GraphicsHelper.SafeDispose(ref context.BrushResource);
 }
Exemplo n.º 33
0
        public void initArena()
        {
            //инциализируем отрисовку и физику

            gh = new GraphicsHelper(pictureBox1);
            ghover = new GraphicsHelper(pictureBoxOverlay);
            ph = new Physics();
            pictureBox2.Image = new Bitmap(pictureBox2.Width, pictureBox2.Height);
            env = new Environment(ph, this);//

            env.draw(gh);
            pictureBoxOverlay.Image = (Image)pictureBox1.Image.Clone();
            foreach (LicsDataWindow dataWnd in dataWnds) dataWnd.Close();
            dataWnds = new List<LicsDataWindow>();
            while (robotListBox.Items.Count != 0)
                robotListBox.Items.RemoveAt(0);
            agents = new Dictionary<string, Agent>();//dispose previous agents
        }
Exemplo n.º 34
0
 protected Color GetColorWithAlpha(Color col, float alpha)
 {
     return(GraphicsHelper.GetColorWithAlpha(col, alpha));
 }
Exemplo n.º 35
0
        /// <summary>
        /// Calculates this controls shape and size that will be used
        /// when it is drawn
        /// </summary>
        /// <param name="container">The allowed space for the control</param>
        public void CalculatePaths(RectangleF container)
        {
            DisposePaths();

            m_needlePath = new GraphicsPath();
            m_hubPath    = new GraphicsPath();
            m_shadowPath = new GraphicsPath(FillMode.Winding);

            float      hubDeltaX  = ((container.Width * (1 - HubSizePercent)) / 2f);
            float      hubDeltaY  = ((container.Height * (1 - HubSizePercent)) / 2f);
            RectangleF centerRect = container;

            centerRect.Inflate(-hubDeltaX, -hubDeltaY);

            float      deltaX     = ((container.Width * (1 - RadiusPercent)) / 2f);
            float      deltaY     = ((container.Height * (1 - RadiusPercent)) / 2f);
            RectangleF needleRect = container;

            needleRect.Inflate(-deltaX, -deltaY);

            float      baseDeltaX     = ((container.Width * (1 - BaseSizePercent)) / 2f);
            float      baseDeltaY     = ((container.Height * (1 - BaseSizePercent)) / 2f);
            RectangleF baseNeedleRect = container;

            baseNeedleRect.Inflate(-baseDeltaX, -baseDeltaY);

            float      tipDeltaX     = ((container.Width * TipExtensionPercent) / 2f);
            float      tipDeltaY     = ((container.Height * TipExtensionPercent) / 2f);
            RectangleF tipNeedleRect = needleRect;

            tipNeedleRect.Inflate(tipDeltaX, tipDeltaY);

            PointF tip     = GraphicsHelper.GetPointInArc(tipNeedleRect, Orientation, 0);
            PointF tipMore = GraphicsHelper.GetPointInArc(needleRect, Orientation + (TipWidthDegrees / 2f), 0);
            PointF tipLess = GraphicsHelper.GetPointInArc(needleRect, Orientation - (TipWidthDegrees / 2f), 0);

            PointF baseMore = GraphicsHelper.GetPointInArc(baseNeedleRect, Orientation + 90, 0);
            PointF baseLess = GraphicsHelper.GetPointInArc(baseNeedleRect, Orientation - 90, 0);
            PointF baseExt  = GraphicsHelper.GetPointInArc(baseNeedleRect, Orientation + 180, 0);

            m_needlePath.AddCurve(new PointF[] { baseLess, baseExt, baseMore });
            m_needlePath.AddLine(baseMore, tipMore);
            m_needlePath.AddCurve(new PointF[] { tipMore, tip, tipLess });
            m_needlePath.CloseFigure();

            m_hubPath.AddEllipse(centerRect);

            centerRect.Width  += (container.Width * DROP_SHADOW_X);
            centerRect.Height += (container.Height * DROP_SHADOW_Y);

            m_shadowPath.AddEllipse(centerRect);
            using (GraphicsPath tempPath = m_needlePath.Clone() as GraphicsPath)
                using (Matrix trans = new Matrix())
                {
                    trans.Translate(container.Width * DROP_SHADOW_X,
                                    container.Height * DROP_SHADOW_Y);
                    tempPath.Transform(trans);
                    m_shadowPath.AddPath(tempPath, true);
                }

            //these areas need to be redrawn now
            m_redrawRegion.Union(m_shadowPath);
            m_redrawRegion.Union(m_needlePath);
            m_redrawRegion.Union(m_hubPath);
        }
Exemplo n.º 36
0
        public void Draw(GraphicsHelper gh)
        {
            var world = parent_car.body.GetWorld();
            var s = new Box2DX.Collision.Segment();
            var pen = new Pen(System.Drawing.Color.Gray, 1 / gh.Scale);
            for (int i = 0; i < p.num_rays; i++)
            {
                GetSegment(i, ref s);

                float lambda = data[i] / p.dist;

                float b0 = 0.3f, b = System.Math.Max(b0, 1 - lambda);
                byte b1 = (byte)((1 - b) * 255);
                Vec2 p1 = s.P1, p2 = (1 - lambda) * s.P1 + lambda * s.P2;

                pen.Color = System.Drawing.Color.FromArgb(b1, b1, b1);
                gh.G.DrawLine(pen, p1.X, p1.Y, p2.X, p2.Y);
            }
        }
        public override void Update(GameTime gameTime)
        {
            InputEnabled = GraphicsHelper.RectangleContains(ScreenRectangle, MouseManager.CurrentState.Position);

            base.Update(gameTime);
        }
Exemplo n.º 38
0
 /// <inheritdoc />
 /// <summary>
 /// </summary>
 /// <param name="gameTime"></param>
 public override void Update(GameTime gameTime)
 {
     InputEnabled = GraphicsHelper.RectangleContains(ScreenRectangle, MouseManager.CurrentState.Position) && DialogManager.Dialogs.Count == 0;
     HandleLoadingWheelAnimations();
     base.Update(gameTime);
 }
Exemplo n.º 39
0
 public override void Start()
 {
     m_BorderTexture = GraphicsHelper.CreateTexture(Color.Black, 1, 1);
 }
        public Bitmap CreateBackCard(DrivingLicense obj)
        {
            var canvasWidthInPixel  = (int)Math.Round(GraphicsHelper.Dpi * GraphicsHelper.CanvasWidth);
            var canvasHeightInPixel = (int)Math.Round(GraphicsHelper.Dpi * GraphicsHelper.CanvasHeight);
            var cardBitmap          = new Bitmap(canvasWidthInPixel, canvasHeightInPixel, PixelFormat.Format32bppArgb);

            cardBitmap.SetResolution(GraphicsHelper.Dpi, GraphicsHelper.Dpi);

            //var background = BackSideBackground;
            using (var gr = Graphics.FromImage(cardBitmap))
            {
                gr.SmoothingMode      = SmoothingMode.HighQuality;
                gr.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                gr.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                gr.TextRenderingHint  = TextRenderingHint.ClearTypeGridFit;
                gr.PageUnit           = GraphicsUnit.Pixel;
                gr.CompositingQuality = CompositingQuality.HighQuality;

                gr.Clear(Color.Transparent);
                //gr.DrawImage(background, 0, 0, canvasWidthInPixel, canvasHeightInPixel);

                const int textMarginX = 593;
                const int diffMarginX = 55;
                foreach (var c in obj.CategoryList)
                {
                    var textMarginY = 116;
                    switch (c.Name)
                    {
                    case "B":
                        textMarginY = textMarginY + diffMarginX;
                        break;

                    case "C":
                        textMarginY = textMarginY + diffMarginX * 2;
                        break;

                    case "D":
                        textMarginY = textMarginY + diffMarginX * 3 + 5;
                        break;

                    case "BE":
                        textMarginY = textMarginY + diffMarginX * 4 + 5;
                        break;

                    case "CE":
                        textMarginY = textMarginY + diffMarginX * 5 + 5;
                        break;

                    case "DE":
                        textMarginY = textMarginY + diffMarginX * 6 + 5;
                        break;
                    }

                    if (c.DateOfIssue.HasValue && c.DateOfIssue.Value != DateTime.MinValue)
                    {
                        GraphicsHelper.DrawText(gr, c.DateOfIssue.Value.ToShortDateString(), textMarginX, textMarginY, 115, 50);
                    }
                    if (c.DateOfExpiry.HasValue && c.DateOfExpiry.Value != DateTime.MinValue)
                    {
                        GraphicsHelper.DrawText(gr, c.DateOfExpiry.Value.ToShortDateString(), textMarginX + 120, textMarginY, 115, 50);
                    }
                }
            }

            return(cardBitmap);
        }
Exemplo n.º 41
0
        public override void Update(GameTime gameTime)
        {
            // Reflect velocity if objects collide:
            // The collision domain contains a ContactSet for each pair of touching objects.
            foreach (var contactSet in _domain.ContactSets)
            {
                // Get the touching objects.
                var objectA = (MovingGeometricObject)contactSet.ObjectA.GeometricObject;
                var objectB = (MovingGeometricObject)contactSet.ObjectB.GeometricObject;

                // In rare cases, the collision detection cannot compute a contact because of
                // numerical problems. Ignore this case, we usually get a contact in the next frame.
                if (contactSet.Count == 0)
                {
                    continue;
                }

                // Get the contact normal of the first collision point.
                var      contact = contactSet[0];
                Vector3F normal  = contact.Normal;

                // Check if the objects move towards or away from each other in the direction of the normal.
                if (Vector3F.Dot(objectB.LinearVelocity - objectA.LinearVelocity, normal) <= 0)
                {
                    // Objects move towards each other. --> Reflect their velocities.
                    objectA.LinearVelocity -= 2 * Vector3F.ProjectTo(objectA.LinearVelocity, normal);
                    objectB.LinearVelocity -= 2 * Vector3F.ProjectTo(objectB.LinearVelocity, normal);
                    objectA.AngularVelocity = -objectA.AngularVelocity;
                    objectB.AngularVelocity = -objectB.AngularVelocity;
                }
            }

            // Get the size of the current time step.
            float timeStep = (float)gameTime.ElapsedGameTime.TotalSeconds;

            // Move objects.
            var objects = _domain.CollisionObjects.Select(co => co.GeometricObject).OfType <MovingGeometricObject>();

            foreach (var obj in objects)
            {
                // Update position.
                Vector3F position = obj.Pose.Position + obj.LinearVelocity * timeStep;

                // Update rotation.
                Vector3F  rotationAxis = obj.AngularVelocity;
                float     angularSpeed = obj.AngularVelocity.Length;
                Matrix33F rotation     = (Numeric.IsZero(angularSpeed))
          ? Matrix33F.Identity
          : Matrix33F.CreateRotation(rotationAxis, angularSpeed * timeStep);
                var orientation = rotation * obj.Pose.Orientation;

                // Incrementally updating the rotation matrix will eventually create a
                // matrix which is not a rotation matrix anymore because of numerical
                // problems. Re-othogonalization make sure that the matrix represents a
                // rotation.
                orientation.Orthogonalize();

                obj.Pose = new Pose(position, orientation);
            }

            // Update collision domain. This computes new contact information.
            _domain.Update(timeStep);

            // Record some statistics.
            int numberOfObjects = _domain.CollisionObjects.Count;

            Profiler.AddValue("NumObjects", numberOfObjects);

            // If there are n objects, we can have max. n * (n - 1) / 2 collisions.
            Profiler.AddValue("NumObjectPairs", numberOfObjects * (numberOfObjects - 1f) / 2f);

            // The first part of the collision detection is the "broad-phase" which
            // filters out objects that cannot collide (e.g. using a fast bounding box test).
            Profiler.AddValue("BroadPhasePairs", _domain.NumberOfBroadPhaseOverlaps);

            // Finally, the collision detection computes the exact contact information and creates
            // a ContactSet with the Contacts for each pair of colliding objects.
            Profiler.AddValue("ContactSetCount", _domain.ContactSets.Count);

            // Draw objects using the DebugRenderer of the graphics screen.
            var debugRenderer = GraphicsScreen.DebugRenderer;

            debugRenderer.Clear();
            foreach (var collisionObject in _domain.CollisionObjects)
            {
                debugRenderer.DrawObject(collisionObject.GeometricObject, GraphicsHelper.GetUniqueColor(collisionObject), false, false);
            }
        }
Exemplo n.º 42
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "Старт")
            {
                if (env.robotsDict.Count == 0)
                {
                    MessageBox.Show("add at least 1 robot");
                    return;
                }
                button1.Text = "Стоп";
                t = 0;

                foreach (string agentname in agents.Keys)
                {
                    robotListBox.Items.Add(agentname);
                }

                saveToFile("last");

                //agent init

                //update targets and positions(positions - not to cause first pathGone unit at initial position)
                foreach (var pair in env.targetsDict)
                    (pair.Key as dreamerAgent).target = pair.Value;
                foreach (var pair in env.robotsDict)
                    (pair.Key as dreamerAgent).initial = pair.Value.pos;

                //init group leaders
                Dictionary<string, List<EvoForestUnitAgent>> groupsDict = new Dictionary<string, List<EvoForestUnitAgent>>();
                foreach (Agent agent in agents.Values)
                {
                    if (typeOfAgent(agent) == "LICS forest car agent with transfer")
                    {
                        EvoForestUnitAgent unitAgent = agent as EvoForestUnitAgent;
                        if (unitAgent.groupID == "") continue;
                        if (!groupsDict.ContainsKey(unitAgent.groupID))
                            groupsDict[unitAgent.groupID] = new List<EvoForestUnitAgent>();
                        groupsDict[unitAgent.groupID].Add(unitAgent);
                    }
                }
                foreach (var pair in groupsDict)
                    agents.Add("coordinator " + pair.Key, new EvoForestTransferAgent(pair.Value));

                //initialise data windows
                foreach (var wnd in dataWnds)
                {
                    wnd.InitializeComponent();
                }
                //initialise agents
                foreach (Agent agent in agents.Values)
                    agent.initAgent();//why: init is safe only after all preparations are done
                //agent init end

                /*
                //создание объектов среды
                //ВАЖНО!!! -- в каком порядке объекты создаются, в таком они и отрисовываются, поэтому в первую очередь создаются объекты заднего плана.
                //занятно...-- НЕсамообучающийся по картинке агент ооочень туго переваривает динамические препятствия. Хотя, всё же, переваривает.

                env.CreateRectZone(new Pose { xc = 32f, yc = 25f, angle_rad = 45 * k_PI }, new Vec2(15f, 25f), 10f);

                env.CreateWall(new Pose { xc = 25f, yc = 17f, angle_rad = 20 * k_PI }, new Vec2(2f, 10f));

                env.CreateColumn(new Pose { xc = 55f, yc = 35f, angle_rad = 100 * k_PI }, 5);
                env.CreateCircle(new Pose { xc = 25f, yc = 20f, angle_rad = -10 * k_PI }, 3, 10);
                */
                env.CreateWall(new Pose { xc = pictureBox1.Width / 60f, yc = pictureBox1.Height / 10f, angle_rad = 90 * k_PI }, new Vec2(2f, 10000f), new Box2DX.Dynamics.Color(0, 0, 0));
                env.CreateWall(new Pose { xc = pictureBox1.Width / 60f, yc = 0 / 10f, angle_rad = 90 * k_PI }, new Vec2(1f, 10000f), new Box2DX.Dynamics.Color(0, 0, 0));
                env.CreateWall(new Pose { xc = pictureBox1.Width / 10f, yc = pictureBox1.Height / 60f, angle_rad = 0 * k_PI }, new Vec2(2f, 10000f), new Box2DX.Dynamics.Color(0, 0, 0));
                env.CreateWall(new Pose { xc = 0 / 10f, yc = pictureBox1.Height / 60f, angle_rad = 0 * k_PI }, new Vec2(1f, 10000f), new Box2DX.Dynamics.Color(0, 0, 0));

                started = true;
                activeBuilder.Close();

                f = this;
                gh_static = gh;

            }
            else
            {
                button1.Text = "Старт";
                //инциализируем отрисовку и физику

                initArena();

                started = false;
                //deinit

                //end of deinit
                loadFromFile("last");

            }
        }
Exemplo n.º 43
0
		protected override void OnPaint(PaintEventArgs e) {
			GraphicsHelper helper = new GraphicsHelper(e.Graphics);

			helper.Gradient(UColor.Blend(0x30, UColor.Black), UColor.Transparent, new Rectangle(0, 0, this.Width, this.Height / 2), 90);
			helper.Line(UColor.Blend(0x60, UColor.Black), 0, 0, this.Width, 0);
		}