コード例 #1
0
ファイル: SpriteWidget.cs プロジェクト: Roger-luo/OpenRA
		public override void Draw()
		{
			var sprite = GetSprite();
			var palette = GetPalette();
			var scale = GetScale();

			if (sprite == null || palette == null)
				return;

			if (sprite != cachedSprite)
			{
				offset = 0.5f * (new float2(RenderBounds.Size) - sprite.Size);
				cachedSprite = sprite;
			}

			if (palette != cachedPalette)
			{
				pr = WorldRenderer.Palette(palette);
				cachedPalette = palette;
			}

			if (scale != cachedScale)
			{
				offset *= scale;
				cachedScale = scale;
			}

			var size = new float2(sprite.Size.X * scale, sprite.Size.Y * scale);
			Game.Renderer.SpriteRenderer.DrawSprite(sprite, RenderOrigin + offset, pr, size);
		}
コード例 #2
0
ファイル: SpriteFont.cs プロジェクト: comradpara/OpenRA
        public void DrawText(SpriteRenderer r, string text, float2 location, Color c)
        {
            location.Y += size;	// baseline vs top

            var p = location;
            foreach (var s in text)
            {
                if (s == '\n')
                {
                    location.Y += size;
                    p = location;
                    continue;
                }

                var g = glyphs[s];
                r.DrawSprite(g.Sprite,
                    new float2(
                        (int)Math.Round(p.X + g.Offset.X, 0),
                        p.Y + g.Offset.Y),
                    "chrome");
                p.X += g.Advance;
            }

            r.Flush();
        }
コード例 #3
0
        public override void DrawInner()
        {
            if( world == null || world.LocalPlayer == null ) return;

            var o = new float2(mapRect.Location.X, mapRect.Location.Y + world.Map.Bounds.Height * previewScale * (1 - radarMinimapHeight)/2);
            var s = new float2(mapRect.Size.Width, mapRect.Size.Height*radarMinimapHeight);
            Game.Renderer.RgbaSpriteRenderer.DrawSprite(terrainSprite, o, s);
            Game.Renderer.RgbaSpriteRenderer.DrawSprite(customTerrainSprite, o, s);
            Game.Renderer.RgbaSpriteRenderer.DrawSprite(actorSprite, o, s);
            Game.Renderer.RgbaSpriteRenderer.DrawSprite(shroudSprite, o, s);

            // Draw viewport rect
            if (hasRadar && !Animating)
            {
                var tl = CellToMinimapPixel(new int2((int)(Game.viewport.Location.X/Game.CellSize), (int)(Game.viewport.Location.Y/Game.CellSize)));
                var br = CellToMinimapPixel(new int2((int)((Game.viewport.Location.X + Game.viewport.Width)/Game.CellSize), (int)((Game.viewport.Location.Y + Game.viewport.Height)/Game.CellSize)));
                var tr = new int2(br.X, tl.Y);
                var bl = new int2(tl.X, br.Y);
                Game.Renderer.EnableScissor((int)mapRect.Left, (int)mapRect.Top, (int)mapRect.Width, (int)mapRect.Height);
                Game.Renderer.LineRenderer.DrawLine(Game.viewport.Location + tl, Game.viewport.Location + tr, Color.White, Color.White);
                Game.Renderer.LineRenderer.DrawLine(Game.viewport.Location + tr, Game.viewport.Location + br, Color.White, Color.White);
                Game.Renderer.LineRenderer.DrawLine(Game.viewport.Location + br, Game.viewport.Location + bl, Color.White, Color.White);
                Game.Renderer.LineRenderer.DrawLine(Game.viewport.Location + bl, Game.viewport.Location + tl, Color.White, Color.White);
                Game.Renderer.DisableScissor();
            }
        }
コード例 #4
0
ファイル: BuildPaletteWidget.cs プロジェクト: Berzeger/OpenRA
		public override void Initialize(WidgetArgs args)
		{
			paletteOpenOrigin = new float2(Game.Renderer.Resolution.Width - Columns*IconWidth - 23, 280);
			paletteClosedOrigin = new float2(Game.Renderer.Resolution.Width - 16, 280);
			paletteOrigin = paletteClosedOrigin;
			base.Initialize(args);
		}
コード例 #5
0
ファイル: Selectable.cs プロジェクト: JackKucan/OpenRA
		void DrawSelectionBar(WorldRenderer wr, float2 xy, float2 Xy, float value, Color barColor)
		{
			if (!self.IsInWorld)
				return;

			var health = self.TraitOrDefault<Health>();
			if (health == null || health.IsDead) return;

			var c = Color.FromArgb(128, 30, 30, 30);
			var c2 = Color.FromArgb(128, 10, 10, 10);
			var p = new float2(0, -4 / wr.Viewport.Zoom);
			var q = new float2(0, -3 / wr.Viewport.Zoom);
			var r = new float2(0, -2 / wr.Viewport.Zoom);

			var barColor2 = Color.FromArgb(255, barColor.R / 2, barColor.G / 2, barColor.B / 2);

			var z = float2.Lerp(xy, Xy, value);
			var wlr = Game.Renderer.WorldLineRenderer;
			wlr.DrawLine(xy + p, Xy + p, c, c);
			wlr.DrawLine(xy + q, Xy + q, c2, c2);
			wlr.DrawLine(xy + r, Xy + r, c, c);

			wlr.DrawLine(xy + p, z + p, barColor2, barColor2);
			wlr.DrawLine(xy + q, z + q, barColor, barColor);
			wlr.DrawLine(xy + r, z + r, barColor2, barColor2);
		}
コード例 #6
0
ファイル: RgbaColorRenderer.cs プロジェクト: CH4Code/OpenRA
        public void DrawLine(float2 start, float2 end, float width, Color startColor, Color endColor)
        {
            renderer.CurrentBatchRenderer = this;

            if (nv + 6 > renderer.TempBufferSize)
                Flush();

            var delta = (end - start) / (end - start).Length;
            var corner = width / 2 * new float2(-delta.Y, delta.X);

            startColor = Util.PremultiplyAlpha(startColor);
            var sr = startColor.R / 255.0f;
            var sg = startColor.G / 255.0f;
            var sb = startColor.B / 255.0f;
            var sa = startColor.A / 255.0f;

            endColor = Util.PremultiplyAlpha(endColor);
            var er = endColor.R / 255.0f;
            var eg = endColor.G / 255.0f;
            var eb = endColor.B / 255.0f;
            var ea = endColor.A / 255.0f;

            vertices[nv++] = new Vertex(start - corner + Offset, sr, sg, sb, sa);
            vertices[nv++] = new Vertex(start + corner + Offset, sr, sg, sb, sa);
            vertices[nv++] = new Vertex(end + corner + Offset, er, eg, eb, ea);
            vertices[nv++] = new Vertex(end + corner + Offset, er, eg, eb, ea);
            vertices[nv++] = new Vertex(end - corner + Offset, er, eg, eb, ea);
            vertices[nv++] = new Vertex(start - corner + Offset, sr, sg, sb, sa);
        }
コード例 #7
0
 /// <summary>
 /// Lerp Function for Float2.
 /// </summary>
 public static float2 Float2Lerp(float2 val1, float2 val2, float time1, float time2)
 {
     float2 values = new float2();
     values.x = val1.x + ((val2.x - val1.x)/time1)*time2;
     values.y = val1.y + ((val2.y - val1.y) / time1) * time2;
     return values;
 }
コード例 #8
0
        public override void Draw()
        {
            float powerScaleBy = 100;
            var maxPower = Math.Max(pm.PowerProvided, pm.PowerDrained);
            while (maxPower >= powerScaleBy) powerScaleBy *= 2;

            // Current power supply
            var providedFrac = pm.PowerProvided / powerScaleBy;
            lastProvidedFrac = providedFrac = float2.Lerp(lastProvidedFrac.GetValueOrDefault(providedFrac), providedFrac, .3f);

            var color = Color.LimeGreen;
            if (pm.PowerState == PowerState.Low)
                color = Color.Orange;
            if (pm.PowerState == PowerState.Critical)
                color = Color.Red;

            var b = RenderBounds;
            var rect = new RectangleF(b.X,
                                      b.Y + (1-providedFrac)*b.Height,
                                      (float)b.Width,
                                      providedFrac*b.Height);
            Game.Renderer.LineRenderer.FillRect(rect, color);

            var indicator = ChromeProvider.GetImage("sidebar-bits", "left-indicator");

            var drainedFrac = pm.PowerDrained / powerScaleBy;
            lastDrainedFrac = drainedFrac = float2.Lerp(lastDrainedFrac.GetValueOrDefault(drainedFrac), drainedFrac, .3f);

            float2 pos = new float2(b.X + b.Width - indicator.size.X,
                                    b.Y + (1-drainedFrac)*b.Height - indicator.size.Y / 2);

            Game.Renderer.RgbaSpriteRenderer.DrawSprite(indicator, pos);
        }
コード例 #9
0
ファイル: BrickShader.cs プロジェクト: Wiladams/NewTOAPIA
        public BrickShader(GraphicsInterface gi)
            : base(gi)
        {
            //Console.WriteLine("BrickShader Link Log: \n{0}", InfoLog);
            GLSLVertexShader vShader = new GLSLVertexShader(gi, Brick_VertexSource);
            AttachShader(vShader);


            GLSLFragmentShader fShader = new GLSLFragmentShader(gi, Brick_FragmentSource);
            AttachShader(fShader);

            Link();

            // Do an initial selection so that all the variables can be located
            Bind();

            BrickColor_Pos = GetUniformLocation("BrickColor");
            MortarColor_Pos = GetUniformLocation("MortarColor");
            BrickSize_Pos = GetUniformLocation("BrickSize");
            BrickPct_Pos = GetUniformLocation("BrickPct");
            
            // From the Vertex Shader
            LightPosition_Pos = GetUniformLocation("LightPosition");

            // Set some initial values
            BrickColor = new ColorRGBA(1.0f, 0.3f, 0.2f);
            MortarColor = new ColorRGBA(0.85f, 0.86f, 0.84f);
            BrickSize = new float2(0.30f, 0.15f);
            BrickPct = new float2(0.90f, 0.85f);
            LightPosition = new Vector3f(0.0f, 0.0f, 4.0f);

            // Unselect so we start in an unselected state
            Unbind();
        }
コード例 #10
0
ファイル: SatelliteLaunch.cs プロジェクト: Iran/ClassicRA
        public SatelliteLaunch(Actor a)
        {
            doors.PlayThen("active",
                () => a.World.AddFrameEndTask(w => w.Remove(this)));

            pos = a.CenterLocation.ToFloat2() - .5f * doors.Image.size + doorOffset;
        }
コード例 #11
0
 void DrawTargetMarker(LineRenderer wlr, float2 p)
 {
     wlr.DrawLine(p + new float2(-1, -1), p + new float2(-1, 1), c, c);
     wlr.DrawLine(p + new float2(-1, 1), p + new float2(1, 1), c, c);
     wlr.DrawLine(p + new float2(1, 1), p + new float2(1, -1), c, c);
     wlr.DrawLine(p + new float2(1, -1), p + new float2(-1, -1), c, c);
 }
コード例 #12
0
ファイル: MoveFlash.cs プロジェクト: pdovy/OpenRA
 public MoveFlash( World world, float2 pos )
 {
     this.pos = pos;
     anim.PlayThen( "idle",
         () => world.AddFrameEndTask(
             w => w.Remove( this ) ) );
 }
コード例 #13
0
ファイル: Corpse.cs プロジェクト: nevelis/OpenRA
 public Corpse(World world, float2 pos, string image, string sequence, string paletteName)
 {
     this.pos = pos;
     this.paletteName = paletteName;
     anim = new Animation(image);
     anim.PlayThen(sequence, () => world.AddFrameEndTask(w => w.Remove(this)));
 }
コード例 #14
0
ファイル: CheckboxWidget.cs プロジェクト: alzeih/OpenRA
        public override void Draw()
        {
            var disabled = IsDisabled();
            var font = Game.Renderer.Fonts[Font];
            var rect = RenderBounds;
            var check = new Rectangle(rect.Location, new Size(Bounds.Height, Bounds.Height));
            var state = disabled ? "checkbox-disabled" :
                        Depressed && HasPressedState ? "checkbox-pressed" :
                        Widget.MouseOverWidget == this ? "checkbox-hover" :
                        "checkbox";

            WidgetUtils.DrawPanel(state, check);

            var textSize = font.Measure(Text);
            font.DrawText(Text,
                new float2(rect.Left + rect.Height * 1.5f, RenderOrigin.Y - BaseLine + (Bounds.Height - textSize.Y)/2), Color.White);

            if (IsChecked() || (Depressed && HasPressedState && !disabled))
            {
                var checkType = GetCheckType();
                if (HasPressedState && (Depressed || disabled))
                    checkType += "-disabled";

                var offset = new float2(rect.Left + CheckOffset, rect.Top + CheckOffset);
                WidgetUtils.DrawRGBA(ChromeProvider.GetImage("checkbox-bits", checkType), offset);
            }
        }
コード例 #15
0
ファイル: SiloBarWidget.cs プロジェクト: alzeih/OpenRA
        public override void Draw()
        {
            float scaleBy = 100;
            var max = Math.Max(pr.OreCapacity, pr.Ore);
            while (max >= scaleBy) scaleBy *= 2;

            // Current capacity
            var capacityFrac = pr.OreCapacity / scaleBy;
            lastCapacityFrac = capacityFrac = float2.Lerp(lastCapacityFrac.GetValueOrDefault(capacityFrac), capacityFrac, .3f);

            var color = GetBarColor();

            var b = RenderBounds;
            var rect = new RectangleF(b.X, float2.Lerp( b.Bottom, b.Top, capacityFrac ),
                (float)b.Width, capacityFrac*b.Height);
            Game.Renderer.LineRenderer.FillRect(rect, color);

            var indicator = ChromeProvider.GetImage("sidebar-bits", "right-indicator");

            var storedFrac = pr.Ore / scaleBy;
            lastStoredFrac = storedFrac = float2.Lerp(lastStoredFrac.GetValueOrDefault(storedFrac), storedFrac, .3f);

            float2 pos = new float2(b.X, float2.Lerp( b.Bottom, b.Top, storedFrac ) - indicator.size.Y / 2);

            Game.Renderer.RgbaSpriteRenderer.DrawSprite(indicator, pos);
        }
コード例 #16
0
ファイル: VGPaint.cs プロジェクト: Wiladams/NewTOAPIA
 public VGPaintRadialGradient(float2 center, float radius, float2 focal)
     :base(VGPaintType.VG_PAINT_TYPE_RADIAL_GRADIENT)
 {
     this.Center = center;
     this.Radius = radius;
     this.FocalPoint = focal;
 }
コード例 #17
0
ファイル: SheetBuilder.cs プロジェクト: TiriliPiitPiit/OpenRA
 public Sprite Add(byte[] src, Size size, float2 spriteOffset)
 {
     var rect = Allocate(size, spriteOffset);
     Util.FastCopyIntoChannel(rect, src);
     current.CommitData();
     return rect;
 }
コード例 #18
0
ファイル: PerfGraphWidget.cs プロジェクト: mgatland/OpenRA
        public override void DrawInner(World world)
        {
            var rect = RenderBounds;
            float2 origin = Game.viewport.Location + new float2(rect.Right, rect.Bottom);
            float2 basis = new float2(-rect.Width / 100, -rect.Height / 100);

            Game.Renderer.LineRenderer.DrawLine(origin, origin + new float2(100, 0) * basis, Color.White, Color.White);
            Game.Renderer.LineRenderer.DrawLine(origin + new float2(100, 0) * basis, origin + new float2(100, 100) * basis, Color.White, Color.White);

            foreach (var item in PerfHistory.items.Values)
            {
                int n = 0;
                item.Samples().Aggregate((a, b) =>
                {
                    Game.Renderer.LineRenderer.DrawLine(
                        origin + new float2(n, (float)a) * basis,
                        origin + new float2(n + 1, (float)b) * basis,
                        item.c, item.c);
                    ++n;
                    return b;
                });
            }

            Game.Renderer.LineRenderer.Flush();
        }
コード例 #19
0
ファイル: MoveFlash.cs プロジェクト: pdovy/OpenRA
 public MoveFlash( World world, int2 cell )
 {
     this.pos = Game.CellSize * (cell + new float2(0.5f, 0.5f));
     anim.PlayThen( "idle",
         () => world.AddFrameEndTask(
             w => w.Remove( this ) ) );
 }
コード例 #20
0
ファイル: RadarWidget.cs プロジェクト: Generalcamo/OpenRA
        public override void Draw()
        {
            if (world == null)
                return;

            var o = new float2(mapRect.Location.X, mapRect.Location.Y + world.Map.Bounds.Height * previewScale * (1 - radarMinimapHeight)/2);
            var s = new float2(mapRect.Size.Width, mapRect.Size.Height*radarMinimapHeight);

            var rsr = Game.Renderer.RgbaSpriteRenderer;
            rsr.DrawSprite(terrainSprite, o, s);
            rsr.DrawSprite(customTerrainSprite, o, s);
            rsr.DrawSprite(actorSprite, o, s);
            rsr.DrawSprite(shroudSprite, o, s);

            // Draw viewport rect
            if (hasRadar)
            {
                var tl = CellToMinimapPixel(worldRenderer.Position(worldRenderer.Viewport.TopLeft).ToCPos());
                var br = CellToMinimapPixel(worldRenderer.Position(worldRenderer.Viewport.BottomRight).ToCPos());

                Game.Renderer.EnableScissor(mapRect);
                Game.Renderer.LineRenderer.DrawRect(tl, br, Color.White);
                Game.Renderer.DisableScissor();
            }
        }
コード例 #21
0
ファイル: RadarBinWidget.cs プロジェクト: subspace/OpenRA
        public override void DrawInner(World world)
        {
            radarCollection = "radar-" + world.LocalPlayer.Country.Race;

            Game.Renderer.RgbaSpriteRenderer.DrawSprite(ChromeProvider.GetImage(radarCollection, "left"), radarOrigin);
            Game.Renderer.RgbaSpriteRenderer.DrawSprite(ChromeProvider.GetImage(radarCollection, "right"), radarOrigin + new float2(201, 0));
            Game.Renderer.RgbaSpriteRenderer.DrawSprite(ChromeProvider.GetImage(radarCollection, "bottom"), radarOrigin + new float2(0, 192));
            Game.Renderer.RgbaSpriteRenderer.DrawSprite(ChromeProvider.GetImage(radarCollection, "bg"), radarOrigin + new float2(9, 0));

            // Don't draw the radar if the tray is moving
            if (radarAnimationFrame >= radarSlideAnimationLength)
            {
                var o = new float2(mapRect.Location.X, mapRect.Location.Y + world.Map.Height * previewScale * (1 - radarMinimapHeight)/2);
                var s = new float2(mapRect.Size.Width, mapRect.Size.Height*radarMinimapHeight);
                Game.Renderer.RgbaSpriteRenderer.DrawSprite(terrainSprite, o, s);
                Game.Renderer.RgbaSpriteRenderer.DrawSprite(customTerrainSprite, o, s);
                Game.Renderer.RgbaSpriteRenderer.DrawSprite(actorSprite, o, s);
                Game.Renderer.RgbaSpriteRenderer.DrawSprite(shroudSprite, o, s);

                // Draw viewport rect
                if (radarAnimationFrame == radarSlideAnimationLength + radarActivateAnimationLength)
                {
                    var tl = CellToMinimapPixel(new int2((int)(Game.viewport.Location.X/Game.CellSize), (int)(Game.viewport.Location.Y/Game.CellSize)));
                    var br = CellToMinimapPixel(new int2((int)((Game.viewport.Location.X + Game.viewport.Width)/Game.CellSize), (int)((Game.viewport.Location.Y + Game.viewport.Height)/Game.CellSize)));
                    var tr = new int2(br.X, tl.Y);
                    var bl = new int2(tl.X, br.Y);
                    Game.Renderer.EnableScissor((int)mapRect.Left, (int)mapRect.Top, (int)mapRect.Width, (int)mapRect.Height);
                    Game.Renderer.LineRenderer.DrawLine(Game.viewport.Location + tl, Game.viewport.Location + tr, Color.White, Color.White);
                    Game.Renderer.LineRenderer.DrawLine(Game.viewport.Location + tr, Game.viewport.Location + br, Color.White, Color.White);
                    Game.Renderer.LineRenderer.DrawLine(Game.viewport.Location + br, Game.viewport.Location + bl, Color.White, Color.White);
                    Game.Renderer.LineRenderer.DrawLine(Game.viewport.Location + bl, Game.viewport.Location + tl, Color.White, Color.White);
                    Game.Renderer.DisableScissor();
                }
            }
        }
コード例 #22
0
ファイル: RadarWidget.cs プロジェクト: nevelis/OpenRA
        public override void Draw()
        {
            if (world == null) return;

            var o = new float2(mapRect.Location.X, mapRect.Location.Y + world.Map.Bounds.Height * previewScale * (1 - radarMinimapHeight)/2);
            var s = new float2(mapRect.Size.Width, mapRect.Size.Height*radarMinimapHeight);
            var rsr = Game.Renderer.RgbaSpriteRenderer;
            rsr.DrawSprite(terrainSprite, o, s);
            rsr.DrawSprite(customTerrainSprite, o, s);
            rsr.DrawSprite(actorSprite, o, s);
            rsr.DrawSprite(shroudSprite, o, s);

            // Draw viewport rect
            if (hasRadar && !animating)
            {
                var wr = Game.viewport.WorldRect;
                var wro = new CPos(wr.X, wr.Y);
                var tl = CellToMinimapPixel(wro);
                var br = CellToMinimapPixel(wro + new CVec(wr.Width, wr.Height));

                Game.Renderer.EnableScissor((int)mapRect.Left, (int)mapRect.Top, (int)mapRect.Width, (int)mapRect.Height);
                Game.Renderer.LineRenderer.DrawRect(tl, br, Color.White);
                Game.Renderer.DisableScissor();
            }
        }
コード例 #23
0
ファイル: Util.cs プロジェクト: RunCraze/OpenRA
 public static void FastCreateQuad(Vertex[] vertices, float2 o, Sprite r, int palette, int nv, float2 size)
 {
     var b = new float2(o.X + size.X, o.Y);
     var c = new float2(o.X + size.X, o.Y + size.Y);
     var d = new float2(o.X, o.Y + size.Y);
     FastCreateQuad(vertices, o, b, c, d, r, palette, nv);
 }
コード例 #24
0
ファイル: VoxelRenderer.cs プロジェクト: Berzeger/OpenRA
		public VoxelRenderProxy(Sprite sprite, Sprite shadowSprite, float2[] projectedShadowBounds, float shadowDirection)
		{
			Sprite = sprite;
			ShadowSprite = shadowSprite;
			ProjectedShadowBounds = projectedShadowBounds;
			ShadowDirection = shadowDirection;
		}
コード例 #25
0
ファイル: CncLoadScreen.cs プロジェクト: Roger-luo/OpenRA
		public override void Init(Manifest m, Dictionary<string, string> info)
		{
			loadInfo = info;

			// Avoid standard loading mechanisms so we
			// can display loadscreen as early as possible
			r = Game.Renderer;
			if (r == null) return;

			sheet = new Sheet(SheetType.BGRA, Platform.ResolvePath(loadInfo["Image"]));
			var res = r.Resolution;
			bounds = new Rectangle(0, 0, res.Width, res.Height);

			borderTop = new Sprite(sheet, new Rectangle(161, 128, 62, 33), TextureChannel.Alpha);
			borderBottom = new Sprite(sheet, new Rectangle(161, 223, 62, 33), TextureChannel.Alpha);
			borderLeft = new Sprite(sheet, new Rectangle(128, 161, 33, 62), TextureChannel.Alpha);
			borderRight = new Sprite(sheet, new Rectangle(223, 161, 33, 62), TextureChannel.Alpha);
			cornerTopLeft = new Sprite(sheet, new Rectangle(128, 128, 33, 33), TextureChannel.Alpha);
			cornerTopRight = new Sprite(sheet, new Rectangle(223, 128, 33, 33), TextureChannel.Alpha);
			cornerBottomLeft = new Sprite(sheet, new Rectangle(128, 223, 33, 33), TextureChannel.Alpha);
			cornerBottomRight = new Sprite(sheet, new Rectangle(223, 223, 33, 33), TextureChannel.Alpha);

			nodLogo = new Sprite(sheet, new Rectangle(0, 256, 256, 256), TextureChannel.Alpha);
			gdiLogo = new Sprite(sheet, new Rectangle(256, 256, 256, 256), TextureChannel.Alpha);
			evaLogo = new Sprite(sheet, new Rectangle(256, 64, 128, 64), TextureChannel.Alpha);
			nodPos = new float2(bounds.Width / 2 - 384, bounds.Height / 2 - 128);
			gdiPos = new float2(bounds.Width / 2 + 128, bounds.Height / 2 - 128);
			evaPos = new float2(bounds.Width - 43 - 128, 43);

			brightBlock = new Sprite(sheet, new Rectangle(320, 0, 16, 35), TextureChannel.Alpha);
			dimBlock = new Sprite(sheet, new Rectangle(336, 0, 16, 35), TextureChannel.Alpha);

			versionText = m.Mod.Version;
		}
コード例 #26
0
ファイル: Contrail.cs プロジェクト: katzsmile/OpenRA
        public void Tick(Actor self)
        {
            var facing = self.Trait<IFacing>();
            var altitude = new float2(0, self.Trait<IMove>().Altitude);

            var pos = self.CenterLocation - Combat.GetTurretPosition(self, facing, ContrailTurret) - altitude;
            history.Tick(pos);
        }
コード例 #27
0
ファイル: TimerWidget.cs プロジェクト: patthoyts/OpenRA
        public override void DrawInner( WorldRenderer wr )
        {
            var s = WidgetUtils.FormatTime(Game.LocalTick);
            var size = Game.Renderer.TitleFont.Measure(s);
            var pos = new float2(RenderBounds.Left - size.X / 2, RenderBounds.Top - 20);

            Game.Renderer.TitleFont.DrawTextWithContrast(s, pos, Color.White, Color.Black, 1);
        }
コード例 #28
0
ファイル: Viewport.cs プロジェクト: comradpara/OpenRA
        public Viewport(float2 screenSize, int2 mapStart, int2 mapEnd, Renderer renderer)
        {
            this.screenSize = screenSize;
            this.renderer = renderer;
            cursorRenderer = new SpriteRenderer(renderer, true);

            this.scrollPosition = Game.CellSize* mapStart;
        }
コード例 #29
0
ファイル: TargetLineRenderable.cs プロジェクト: pchote/OpenRA
 public static void DrawTargetMarker(WorldRenderer wr, Color color, float3 location)
 {
     var iz = 1 / wr.Viewport.Zoom;
     var offset = new float2(iz, iz);
     var tl = location - offset;
     var br = location + offset;
     Game.Renderer.WorldRgbaColorRenderer.FillRect(tl, br, color);
 }
コード例 #30
0
ファイル: Leap.cs プロジェクト: mgatland/OpenRA
        public Leap(Actor self, Target target)
        {
            this.target = target;
            initialLocation = self.CenterLocation;

            self.Trait<RenderInfantry>().Attacking(self);
            Sound.Play("dogg5p.aud", self.CenterLocation);
        }
コード例 #31
0
ファイル: mathx.cs プロジェクト: Kmiecis/Unity-CommonECS
 public static int2 ceil(float2 v)
 {
     return((int2)(v + 1.0f));
 }
コード例 #32
0
ファイル: mathx.cs プロジェクト: Kmiecis/Unity-CommonECS
 public static bool isequal(float2 a, float2 b)
 {
     return(iszero(b - a));
 }
コード例 #33
0
ファイル: mathx.cs プロジェクト: Kmiecis/Unity-CommonECS
 public static int2 round(float2 v)
 {
     return((int2)(v + 0.5f));
 }
コード例 #34
0
            public void Execute(int i)
            {
                float positionDelta = math.length(velocities[i]) * deltaTime;

                SplineMath.SplineGraphFollowState followState = followStates[i];
                Unity.Mathematics.Random          random      = randoms[i];

                SplineMath.AdvanceTFromDelta(
                    ref followState,
                    ref random,
                    positionDelta,
                    splineGraph.vertices.data,
                    splineGraph.vertices.count,
                    splineGraph.edgePoolChildren.data,
                    splineGraph.edgePoolParents.data,
                    splineGraph.payload.edgeParentToChildSplines.data,
                    splineGraph.payload.edgeChildToParentSplines.data
                    );

                followStates[i] = followState;
                randoms[i]      = random;

                Int16 edgeIndex = followState.DecodeEdgeIndex();

                SplineMath.Spline spline = (followState.DecodeIsReverse() == 0)
                    ? splineGraph.payload.edgeParentToChildSplines.data[edgeIndex]
                    : splineGraph.payload.edgeChildToParentSplines.data[edgeIndex];

                Int16 vertexIndexChild  = splineGraph.edgePoolChildren.data[edgeIndex].vertexIndex;
                Int16 vertexIndexParent = splineGraph.edgePoolParents.data[edgeIndex].vertexIndex;

                if (followState.DecodeIsReverse() == 1)
                {
                    Int16 vertexIndexTemp = vertexIndexChild;
                    vertexIndexChild  = vertexIndexParent;
                    vertexIndexParent = vertexIndexTemp;
                }

                quaternion rotationParent = splineGraph.payload.rotations.data[vertexIndexParent];
                quaternion rotationChild  = splineGraph.payload.rotations.data[vertexIndexChild];

                float3     positionPrevious = positions[i];
                quaternion rotationPrevious = rotations[i];

                float3 positionOnSpline = SplineMath.EvaluatePositionFromT(spline, followState.t);

                positions[i] = positionOnSpline;
                // rotations[i] = SplineMath.EvaluateRotationFromT(spline, followState.t);
                // rotations[i] = math.slerp(rotationParent, rotationChild, followState.t);
                rotations[i] = SplineMath.EvaluateRotationWithRollFromT(spline, rotationParent, rotationChild, followState.t);

                // For now, simply evaluate the current leash value by lerping between the parent and child leash values, rather than using spline interpolation.
                // This seems good enough for now (there is a bug in the spline interpolation code commented out below.)
                float2 leashParent = splineGraph.payload.leashes.data[vertexIndexParent];
                float2 leashChild  = splineGraph.payload.leashes.data[vertexIndexChild];
                float2 leashMaxOS  = math.lerp(leashParent, leashChild, followState.t);

                // SplineMath.Spline splineLeash = (followState.DecodeIsReverse() == 0)
                //     ? splineGraph.payload.edgeParentToChildSplinesLeashes.data[edgeIndex]
                //     : splineGraph.payload.edgeChildToParentSplinesLeashes.data[edgeIndex];
                // float2 leashMaxOS = SplineMath.EvaluatePositionFromT(splineLeash, followState.t).xy;

                float2 leashOS = leashMaxOS * leashes[i];
                float3 leashWS = math.mul(rotations[i], new float3(leashOS, 0.0f));

                positions[i] += leashWS;

                if (avoidanceSoftBodySphereRadius > 1e-5f)
                {
                    float3 avoidanceDirection = positions[i] - avoidanceSoftBodySphereOrigin;
                    float  avoidanceLength    = math.length(avoidanceDirection);
                    avoidanceDirection *= (avoidanceLength > 1e-5f) ? (1.0f / avoidanceLength) : 0.0f;
                    float avoidanceOffset = math.saturate((avoidanceLength / avoidanceSoftBodySphereRadius) * -0.5f + 1.0f) * avoidanceSoftBodySphereRadius;
                    if (avoidanceOffset > 0.0f)
                    {
                        float3 leashPlaneNormal = math.mul(rotations[i], new float3(0.0f, 0.0f, 1.0f));
                        float3 avoidanceDirectionLeashPlaneT = avoidanceDirection - leashPlaneNormal * math.dot(leashPlaneNormal, avoidanceDirection);
                        avoidanceDirectionLeashPlaneT = (math.lengthsq(avoidanceDirectionLeashPlaneT) > 1e-3f)
                            ? avoidanceDirectionLeashPlaneT
                            : leashWS;
                        avoidanceDirectionLeashPlaneT = (math.lengthsq(avoidanceDirectionLeashPlaneT) > 1e-3f)
                            ? avoidanceDirectionLeashPlaneT
                            : new float3(0.0f, 1.0f, 0.0f);
                        avoidanceDirectionLeashPlaneT = math.normalize(avoidanceDirectionLeashPlaneT);
                        positions[i] += avoidanceDirectionLeashPlaneT * avoidanceOffset;
                    }
                }

                positions[i] = math.lerp(positions[i], positionPrevious, dampeningPosition);
                rotations[i] = math.slerp(rotations[i], rotationPrevious, dampeningRotation);


                // {
                //     float3 acceleration = SplineMath.EvaluateAccelerationFromT(spline, followState.t);

                //     float3 directionRightWS = math.mul(rotations[i], new float3(1.0f, 0.0f, 0.0f));
                //     float accelerationRight = math.dot(directionRightWS, acceleration);

                //     float rollAngle = math.lerp(-0.25f * math.PI, 0.25f * math.PI, math.saturate((accelerationRight * rollFromAccelerationScale) * -0.5f + 0.5f));
                //     rotations[i] = math.mul(rotations[i], quaternion.AxisAngle(new float3(0.0f, 0.0f, 1.0f), rollAngle));
                // }
            }
コード例 #35
0
    protected override JobHandle OnUpdate(JobHandle lastJobHandle)
    {
        int pathOffset = m_PathVariationOffset;

        m_PathVariationOffset = (m_PathVariationOffset + 1) & 3;

        // Get component data from the GridPlane
        var cartesianGridPlane = GetSingleton <CartesianGridOnPlane>();
        var rowCount           = cartesianGridPlane.Blob.Value.RowCount;
        var colCount           = cartesianGridPlane.Blob.Value.ColCount;
        var trailingOffsets    = (float2 *)cartesianGridPlane.Blob.Value.TrailingOffsets.GetUnsafePtr();

        var targetEntities    = m_TargetQuery.ToEntityArray(Allocator.TempJob);
        var targetCoordinates = m_TargetQuery.ToComponentDataArray <CartesianGridCoordinates>(Allocator.TempJob);
        var getCartesianGridTargetDirectionFromEntity = GetBufferFromEntity <CartesianGridTargetDirection>(true);

        // Offset center to grid cell
        var cellCenterOffset = new float2(((float)colCount * 0.5f) - 0.5f, ((float)rowCount * 0.5f) - 0.5f);

        // Whenever a CartesianGridFollowTarget reaches a new grid cell, make a decision about what next direction to turn.
        lastJobHandle = Entities
                        .WithName("ChangeDirectionTowardNearestTarget")
                        .WithNativeDisableUnsafePtrRestriction(trailingOffsets)
                        .WithEntityQueryOptions(EntityQueryOptions.FilterWriteGroup)
                        .WithReadOnly(targetCoordinates)
                        .WithReadOnly(getCartesianGridTargetDirectionFromEntity)
                        .WithAll <CartesianGridFollowTarget>()
                        .ForEach((ref CartesianGridDirection gridDirection,
                                  ref CartesianGridCoordinates gridCoordinates,
                                  ref Translation translation) =>
        {
            var dir = gridDirection.Value;
            if (dir != 0xff)         // If moving, update grid based on trailing direction.
            {
                var nextGridPosition = new CartesianGridCoordinates(translation.Value.xz + trailingOffsets[dir], rowCount, colCount);
                if (gridCoordinates.Equals(nextGridPosition))
                {
                    // Don't allow translation to drift
                    translation.Value = CartesianGridMovement.SnapToGridAlongDirection(translation.Value, dir, gridCoordinates, cellCenterOffset);
                    return;         // Still in the same grid cell. No need to change direction.
                }

                gridCoordinates = nextGridPosition;
            }

            var targetEntity = FindTargetShortestManhattanDistance(gridCoordinates, rowCount, colCount, targetCoordinates, targetEntities);
            if (targetEntity == Entity.Null)
            {
                // No target for whatever reason, don't move.
                gridDirection.Value = 0xff;
                return;
            }

            // Lookup next direction along shortest path to target from table stored in CartesianGridTargetDirection
            // - When multiple shortest path available, use pathOffset to select which option.
            var targetDirections = getCartesianGridTargetDirectionFromEntity[targetEntity].Reinterpret <byte>().AsNativeArray();
            var validDirections  = CartesianGridOnPlaneShortestPath.LookupDirectionToTarget(gridCoordinates, rowCount, colCount, targetDirections);
            gridDirection.Value  = CartesianGridMovement.PathVariation[(pathOffset * 16) + validDirections];
        }).Schedule(lastJobHandle);

        lastJobHandle = targetEntities.Dispose(lastJobHandle);
        lastJobHandle = targetCoordinates.Dispose(lastJobHandle);

        return(lastJobHandle);
    }
コード例 #36
0
ファイル: ScreenShaker.cs プロジェクト: watsoncui/OpenRA
 public void AddEffect(int time, float2 position, int intensity)
 {
     shakeEffects.Add(new ShakeEffect {
         ExpiryTime = ticks + time, Position = position, Intensity = intensity
     });
 }
コード例 #37
0
 public static float2 Mul(float2 a, float2 b)
 {
     return(new float2(
                a.x * b.x - a.y * b.y,
                a.x * b.y + a.y * b.x));
 }
コード例 #38
0
        public override void Draw()
        {
            var player = GetPlayer();

            if (player == null)
            {
                return;
            }

            var queues = world.ActorsWithTrait <ProductionQueue>()
                         .Where(a => a.Actor.Owner == player)
                         .Select((a, i) => new { a.Trait, i });

            foreach (var queue in queues)
            {
                if (!clocks.ContainsKey(queue.Trait))
                {
                    clocks.Add(queue.Trait, new Animation(world, ClockAnimation));
                }
            }

            var iconSize = new float2(IconWidth, IconHeight);

            foreach (var queue in queues)
            {
                var current = queue.Trait.CurrentItem();
                if (current == null)
                {
                    continue;
                }

                var faction = queue.Trait.Actor.Owner.Faction.InternalName;
                var actor   = queue.Trait.AllItems().FirstOrDefault(a => a.Name == current.Item);
                if (actor == null)
                {
                    continue;
                }

                var rsi  = actor.TraitInfo <RenderSpritesInfo>();
                var icon = new Animation(world, rsi.GetImage(actor, world.Map.Rules.Sequences, faction));
                icon.Play(actor.TraitInfo <TooltipInfo>().Icon);
                var bi       = actor.TraitInfo <BuildableInfo>();
                var location = new float2(RenderBounds.Location) + new float2(queue.i * (IconWidth + IconSpacing), 0);
                WidgetUtils.DrawSHPCentered(icon.Image, location + 0.5f * iconSize, worldRenderer.Palette(bi.IconPalette), 0.5f);

                var pio = queue.Trait.Actor.Owner.PlayerActor.TraitsImplementing <IProductionIconOverlay>()
                          .FirstOrDefault(p => p.IsOverlayActive(actor));
                if (pio != null)
                {
                    WidgetUtils.DrawSHPCentered(pio.Sprite, location + 0.5f * iconSize + pio.Offset(0.5f * iconSize),
                                                worldRenderer.Palette(pio.Palette), 0.5f);
                }

                var clock = clocks[queue.Trait];
                clock.PlayFetchIndex(ClockSequence,
                                     () => current.TotalTime == 0 ? 0 : ((current.TotalTime - current.RemainingTime)
                                                                         * (clock.CurrentSequence.Length - 1) / current.TotalTime));
                clock.Tick();
                WidgetUtils.DrawSHPCentered(clock.Image, location + 0.5f * iconSize, worldRenderer.Palette(ClockPalette), 0.5f);

                var tiny = Game.Renderer.Fonts["Tiny"];
                var text = GetOverlayForItem(current, world.Timestep);
                tiny.DrawTextWithContrast(text,
                                          location + new float2(16, 16) - new float2(tiny.Measure(text).X / 2, 0),
                                          Color.White, Color.Black, 1);
            }
        }
コード例 #39
0
 public static bool IsPreciselyZero(this float2 value) => value.x == 0 &&
 value.y == 0;
コード例 #40
0
        // Init is called on startup.
        public override void Init()
        {
            _initWindowWidth  = Width;
            _initWindowHeight = Height;

            _initCanvasWidth  = Width / 100f;
            _initCanvasHeight = Height / 100f;

            _canvasHeight = _initCanvasHeight;
            _canvasWidth  = _initCanvasWidth;

            _aspectRatio = Width / (float)Height;

            // Initial "Zoom" value (it's rather the distance in view direction, not the camera's focal distance/opening angle)
            _zoom = 400;

            _angleRoll        = 0;
            _angleRollInit    = 0;
            _twoTouchRepeated = false;
            _offset           = float2.Zero;
            _offsetInit       = float2.Zero;

            // Set the clear color for the back buffer to white (100% intensity in all color channels R, G, B, A).
            RC.ClearColor = new float4(1, 1, 1, 1);

            // Load the standard model
            _scene = AssetStorage.Get <SceneContainer>(ModelFile);

            _gui = CreateGui();
            // Create the interaction handler
            _sih = new SceneInteractionHandler(_gui);


            // Register the input devices that are not already given.

            _spaceMouse = GetDevice <SixDOFDevice>();
            _gamePad    = GetDevice <GamePadDevice>();



            AABBCalculator aabbc = new AABBCalculator(_scene);
            var            bbox  = aabbc.GetBox();

            if (bbox != null)
            {
                // If the model origin is more than one third away from its bounding box,
                // recenter it to the bounding box. Do this check individually per dimension.
                // This way, small deviations will keep the model's original center, while big deviations
                // will make the model rotate around its geometric center.
                float3 bbCenter = bbox.Value.Center;
                float3 bbSize   = bbox.Value.Size;
                float3 center   = float3.Zero;
                if (System.Math.Abs(bbCenter.x) > bbSize.x * 0.3)
                {
                    center.x = bbCenter.x;
                }
                if (System.Math.Abs(bbCenter.y) > bbSize.y * 0.3)
                {
                    center.y = bbCenter.y;
                }
                if (System.Math.Abs(bbCenter.z) > bbSize.z * 0.3)
                {
                    center.z = bbCenter.z;
                }
                _sceneCenter = float4x4.CreateTranslation(-center);

                // Adjust the model size
                float maxScale = System.Math.Max(bbSize.x, System.Math.Max(bbSize.y, bbSize.z));
                if (maxScale != 0)
                {
                    _sceneScale = float4x4.CreateScale(200.0f / maxScale);
                }
                else
                {
                    _sceneScale = float4x4.Identity;
                }
            }

            //Add resize delegate
            var projComp = _scene.Children[0].GetComponent <ProjectionComponent>();

            AddResizeDelegate(delegate { projComp.Resize(Width, Height); });

            // Wrap a SceneRenderer around the model.
            _sceneRenderer = new SceneRenderer(_scene);
            _guiRenderer   = new SceneRenderer(_gui);
        }
コード例 #41
0
            private void PerformSplit()
            {
                //generate random spit for every centroid
                for (int i = 0; i < Owner.m_centroidsCount; i++)
                {
                    float2 c_src = new float2(Owner.Centroids.Host[i * CENTROID_FIELDS], Owner.Centroids.Host[i * CENTROID_FIELDS + 1]);

                    float vx = Owner.Centroids.Host[i * CENTROID_FIELDS + 2];
                    float vy = Owner.Centroids.Host[i * CENTROID_FIELDS + 3];

                    double dir = random.NextDouble() * Math.PI * 2;

                    int c_n1i = Owner.m_centroidsCount + 2 * i;
                    int c_n2i = Owner.m_centroidsCount + 2 * i + 1;

                    float2 c_n1 = new float2((float)(vx * 0.5 * Math.Cos(dir)), (float)(vy * 0.5 * Math.Sin(dir)));
                    float2 c_n2 = c_n1 * -1;

                    c_n1 += c_src;
                    c_n2 += c_src;

                    Owner.Centroids.Host[c_n1i * CENTROID_FIELDS]     = c_n1.x;
                    Owner.Centroids.Host[c_n1i * CENTROID_FIELDS + 1] = c_n1.y;

                    Owner.Centroids.Host[c_n2i * CENTROID_FIELDS]     = c_n2.x;
                    Owner.Centroids.Host[c_n2i * CENTROID_FIELDS + 1] = c_n2.y;
                }

                Owner.Centroids.SafeCopyToDevice();

                //try 2-Means for generated pairs
                for (int i = 0; i < Owner.m_centroidsCount; i++)
                {
                    int c_n1i = Owner.m_centroidsCount + 2 * i;
                    int c_n2i = Owner.m_centroidsCount + 2 * i + 1;

                    //prepare 2-Means
                    m_2meansKernel.Run(Owner.AttentionMap, Owner.Centroids, c_n1i, c_n2i, i,
                                       Owner.ReductionSources, m_imageWidth, m_imageHeight);

                    //do reductions
                    for (int k = 0; k < Owner.m_sumsPerItem; k++)
                    {
                        m_reduction_kernel.Run(Owner.Statistics, Owner.ReductionSources, Owner.AttentionMap.Count,
                                               c_n1i * Owner.m_sumsPerItem + k,
                                               c_n1i * Owner.AttentionMap.Count * Owner.m_sumsPerItem + k * Owner.AttentionMap.Count, 1);

                        m_reduction_kernel.Run(Owner.Statistics, Owner.ReductionSources, Owner.AttentionMap.Count,
                                               c_n2i * Owner.m_sumsPerItem + k,
                                               c_n2i * Owner.AttentionMap.Count * Owner.m_sumsPerItem + k * Owner.AttentionMap.Count, 1);
                    }
                }

                //finalize 2-Means
                m_finalize_kernel.SetupExecution(Owner.m_centroidsCount * 2);
                m_finalize_kernel.Run(Owner.Centroids, Owner.m_centroidsCount * 2, Owner.Statistics, LearningRate, Owner.m_centroidsCount);

                Owner.Centroids.SafeCopyToHost();

                //iterate candidates for split and find the maximum gain
                int numOfSplits = 0;

                for (int i = 0; i < Owner.m_centroidsCount; i++)
                {
                    int c_n1i = Owner.m_centroidsCount + 2 * i;
                    int c_n2i = Owner.m_centroidsCount + 2 * i + 1;

                    float2 c_n1    = new float2(Owner.Centroids.Host[c_n1i * CENTROID_FIELDS], Owner.Centroids.Host[c_n1i * CENTROID_FIELDS + 1]);
                    float2 c_n2    = new float2(Owner.Centroids.Host[c_n2i * CENTROID_FIELDS], Owner.Centroids.Host[c_n2i * CENTROID_FIELDS + 1]);
                    float2 c_n12   = c_n1 - c_n2;
                    float  c_n12_l = (float)Math.Sqrt(c_n12.x * c_n12.x + c_n12.y * c_n12.y);

                    float c_n1_dbi = Owner.Centroids.Host[c_n1i * CENTROID_FIELDS + 5];
                    float c_n2_dbi = Owner.Centroids.Host[c_n2i * CENTROID_FIELDS + 5];

                    float c_src_dbi = Owner.Centroids.Host[i * CENTROID_FIELDS + 5];
                    float c_n12_dbi = 0.5f * (c_n1_dbi + c_n2_dbi) / c_n12_l;

                    if (c_n12_dbi < c_src_dbi)
                    {
                        //replace the source centroid to the first child
                        Owner.Centroids.CopyToMemoryBlock(Owner.Centroids, c_n1i * CENTROID_FIELDS, i * CENTROID_FIELDS, CENTROID_FIELDS);

                        //add the second child to the end
                        Owner.Centroids.CopyToMemoryBlock(Owner.Centroids, c_n2i * CENTROID_FIELDS,
                                                          (Owner.m_centroidsCount + numOfSplits) * CENTROID_FIELDS, CENTROID_FIELDS);

                        numOfSplits++;
                    }
                    //MyLog.DEBUG.WriteLine("Split candidates: " + i + ". = (" + c_src_dbi + " -> " + c_n12_dbi + ")");
                }

                Owner.m_centroidsCount += numOfSplits;
            }
コード例 #42
0
        public void SetShader(String baseTexturePath, String colorMapTexturePath, float4 lineColor, float2 lineWidth)
        {
            var imgData = _rc.LoadImage(baseTexturePath);

            _iTexture1 = _rc.CreateTexture(imgData);
            imgData    = _rc.LoadImage(colorMapTexturePath);
            _iTexture2 = _rc.CreateTexture(imgData);

            _shaderEffect = Shader.GetShaderEffect(_rc, _iTexture1, _iTexture2, lineColor, lineWidth);
        }
コード例 #43
0
 public static bool IsZero(this float2 value) => math.abs(value.x) < SMALL_VALUE &&
 math.abs(value.y) < SMALL_VALUE;
コード例 #44
0
ファイル: VoxelWidget.cs プロジェクト: zgrsgr/Yuris-Revenge
        public override void PrepareRenderables()
        {
            var voxel             = GetVoxel();
            var palette           = GetPalette();
            var playerPalette     = GetPlayerPalette();
            var normalsPalette    = GetNormalsPalette();
            var shadowPalette     = GetShadowPalette();
            var scale             = GetScale();
            var lightAmbientColor = GetLightAmbientColor();
            var lightDiffuseColor = GetLightDiffuseColor();
            var lightPitch        = GetLightPitch();
            var lightYaw          = GetLightYaw();

            if (voxel == null || palette == null)
            {
                return;
            }

            if (voxel != cachedVoxel)
            {
                offset      = 0.5f * (new float2(RenderBounds.Size) - new float2(voxel.Size[0], voxel.Size[1]));
                cachedVoxel = voxel;
            }

            if (palette != cachedPalette)
            {
                if (string.IsNullOrEmpty(palette) && string.IsNullOrEmpty(playerPalette))
                {
                    return;
                }
                string paletteName = string.IsNullOrEmpty(palette) ? playerPalette : palette;
                pr            = WorldRenderer.Palette(paletteName);
                cachedPalette = paletteName;
            }

            if (playerPalette != cachedPlayerPalette)
            {
                prPlayer            = WorldRenderer.Palette(playerPalette);
                cachedPlayerPalette = playerPalette;
            }

            if (normalsPalette != cachedNormalsPalette)
            {
                prNormals            = WorldRenderer.Palette(normalsPalette);
                cachedNormalsPalette = normalsPalette;
            }

            if (shadowPalette != cachedShadowPalette)
            {
                prShadow            = WorldRenderer.Palette(shadowPalette);
                cachedShadowPalette = shadowPalette;
            }

            if (scale != cachedScale)
            {
                //offset *= scale;
                cachedScale = scale;
            }

            if (lightPitch != cachedLightPitch)
            {
                cachedLightPitch = lightPitch;
            }

            if (lightYaw != cachedLightYaw)
            {
                cachedLightYaw = lightYaw;
            }

            if (cachedLightAmbientColor[0] != lightAmbientColor[0] || cachedLightAmbientColor[1] != lightAmbientColor[1] || cachedLightAmbientColor[2] != lightAmbientColor[2])
            {
                cachedLightAmbientColor = lightAmbientColor;
            }

            if (cachedLightDiffuseColor[0] != lightDiffuseColor[0] || cachedLightDiffuseColor[1] != lightDiffuseColor[1] || cachedLightDiffuseColor[2] != lightDiffuseColor[2])
            {
                cachedLightDiffuseColor = lightDiffuseColor;
            }
            if (cachedVoxel == null)
            {
                return;
            }
            var            size      = new float2(cachedVoxel.Size[0] * cachedScale, cachedVoxel.Size[1] * cachedScale);
            ModelAnimation animation = new ModelAnimation(
                cachedVoxel,
                () => WVec.Zero,
                () => new List <WRot>()
            {
                new WRot(
                    new WAngle(-45),
                    new WAngle(-30),
                    new WAngle(360)
                    )
            },
                () => false,
                () => 0,
                true);

            ModelPreview preview = new ModelPreview(
                new ModelAnimation[] { animation }, WVec.Zero, 0,
                cachedScale,
                new WAngle(cachedLightPitch),
                new WAngle(cachedLightYaw),
                cachedLightAmbientColor,
                cachedLightDiffuseColor,
                new WAngle(),
                pr,
                prNormals,
                prShadow);

            List <ModelPreview> previews = new List <ModelPreview>()
            {
                preview
            };


            // Calculate the preview bounds
            PreviewOffset    = int2.Zero;
            IdealPreviewSize = int2.Zero;

            var rs = previews.SelectMany(p => ((IActorPreview)p).ScreenBounds(WorldRenderer, WPos.Zero));

            if (rs.Any())
            {
                var b = rs.First();
                foreach (var rr in rs.Skip(1))
                {
                    b = OpenRA.Primitives.Rectangle.Union(b, rr);
                }

                IdealPreviewSize = new int2(b.Width, b.Height);
                PreviewOffset    = -new int2(b.Left, b.Top) - IdealPreviewSize / 2;
            }

            renderables = previews
                          .SelectMany(p => ((IActorPreview)p).Render(WorldRenderer, WPos.Zero))
                          .OrderBy(WorldRenderer.RenderableScreenZPositionComparisonKey)
                          .Select(r => r.PrepareRender(WorldRenderer))
                          .ToArray();
        }
コード例 #45
0
ファイル: mathx.cs プロジェクト: Kmiecis/Unity-CommonECS
 public static float2 perpendicular(float2 v)
 {
     return(new float2(v.y, -v.x));
 }
コード例 #46
0
ファイル: mathx.cs プロジェクト: Kmiecis/Unity-CommonECS
 public static float2 lerp(float2 v0, float2 v1, float2 v2, float3 w)
 {
     return(v0 * w.x + v1 * w.y + v2 * w.z);
 }
コード例 #47
0
ファイル: Constant.cs プロジェクト: ZippeyKeys12/funstuff
 public override Sample <float2> Get(float2 xy)
 => (Sample <float2>)a;
コード例 #48
0
ファイル: mathx.cs プロジェクト: Kmiecis/Unity-CommonECS
 public static int2 floor(float2 v)
 {
     return((int2)v);
 }
コード例 #49
0
ファイル: BallSystem.cs プロジェクト: spicysoft/h5g-batting
        // 的との当たり判定.
        bool checkColliTarget(float3 vSt, float3 vEd, float3 center, float r, out float3 norm)
        {
            // A:線分の始点、B:線分の終点、P:円の中心、X:PからABに下ろした垂線との交点.
            float2 vAB = new float2(vEd.x - vSt.x, vEd.y - vSt.y);
            float2 vAP = new float2(center.x - vSt.x, center.y - vSt.y);
            float2 vBP = new float2(center.x - vEd.x, center.y - vEd.y);

            float2 vABnorm = math.normalize(vAB);
            // AXの距離.
            float lenAX = inner2d(vAP, vABnorm);

            // 線分ABとPの最短距離
            float shortestDistance;
            int   pattern = 0;

            if (lenAX < 0)
            {
                // AXが負なら APが円の中心までの最短距離
                shortestDistance = math.length(vAP);
                pattern          = 1;
            }
            else if (lenAX > math.length(vAB))
            {
                // AXがABよりも長い場合は、BPが円の中心までの最短距離
                shortestDistance = math.length(vBP);
                pattern          = 2;
            }
            else
            {
                // XがAB上にあるので、AXが最短距離
                // 単位ベクトルABとベクトルAPの外積で求める
                shortestDistance = math.abs(cross2d(vAP, vABnorm));
                pattern          = 3;
            }

            if (shortestDistance > r)
            {
                // はずれ.
                norm = float3.zero;
                return(false);
            }

            // Xの座標.
            float2 pX = vABnorm * lenAX + new float2(vSt.x, vSt.y);

            float2 pP      = new float2(center.x, center.y);
            float2 vPX     = pP - pX;
            float  lenPXsp = math.lengthsq(vPX);

            // 交点求める.
            // Xから交点までの距離.
            float  dist = math.sqrt(r * r - lenPXsp);
            float2 pQ   = float2.zero;

            if (pattern == 1)
            {
                pQ = vABnorm * dist + pX;
            }
            else if (pattern == 2)
            {
                pQ = -vABnorm * dist + pX;
            }
            else if (pattern == 3)
            {
                pQ = -vABnorm * dist + pX;
            }

            // 法線計算.
            float2 vPQ     = pQ - pP;
            float2 vPQnorm = math.normalize(vPQ);

            norm = new float3(vPQnorm.x, vPQnorm.y, 0);

            return(true);
        }
コード例 #50
0
 public PlungerUvBufferElement(float2 v)
 {
     Value = v;
 }
コード例 #51
0
        // RenderAFrame is called once a frame
        public override void RenderAFrame()
        {
            //_rechtsVorneTransform.Rotation = new float3(M.MinAngle(TimeSinceStart), 0, 0);

            float rechts_vorne_rotation_z = _rechtsVorneTransform.Rotation.z;

            rechts_vorne_rotation_z += 2 * -Keyboard.UpDownAxis * DeltaTime;

            float rechts_vorne_rotation_y = _rechtsVorneTransform.Rotation.y;

            rechts_vorne_rotation_y += Keyboard.LeftRightAxis * DeltaTime;

            if (rechts_vorne_rotation_y < 0.25 && rechts_vorne_rotation_y > -0.25)
            {
                _rechtsVorneTransform.Rotation = new float3(0, rechts_vorne_rotation_y, rechts_vorne_rotation_z);
            }
            else
            {
                _rechtsVorneTransform.Rotation = new float3(0, _rechtsVorneTransform.Rotation.y, rechts_vorne_rotation_z);
            }

            //Diagnostics.Log(rechts_vorne_rotation_y);

            float links_vorne_rotation_z = _linksVorneTransform.Rotation.z;

            links_vorne_rotation_z += 2 * -Keyboard.UpDownAxis * DeltaTime;

            float links_vorne_rotation_y = _linksVorneTransform.Rotation.y;

            links_vorne_rotation_y += Keyboard.LeftRightAxis * DeltaTime;

            if (links_vorne_rotation_y < 0.25 && links_vorne_rotation_y > -0.25)
            {
                _linksVorneTransform.Rotation = new float3(0, links_vorne_rotation_y, links_vorne_rotation_z);
            }
            else
            {
                _linksVorneTransform.Rotation = new float3(0, _linksVorneTransform.Rotation.y, links_vorne_rotation_z);
            }


            float links_hinten_rotation_z = _linksHintenTransform.Rotation.z;

            links_hinten_rotation_z       += 2 * -Keyboard.UpDownAxis * DeltaTime;
            _linksHintenTransform.Rotation = new float3(0, 0, links_hinten_rotation_z);

            float rechts_hinten_rotation_z = _rechtsHintenTransform.Rotation.z;

            rechts_hinten_rotation_z       += 2 * -Keyboard.UpDownAxis * DeltaTime;
            _rechtsHintenTransform.Rotation = new float3(0, 0, rechts_hinten_rotation_z);



            if (_Arm1)
            {
                float arm1_rotation_y = _Arm1Transform.Rotation.y;
                arm1_rotation_y        += 2 * Keyboard.ADAxis * DeltaTime;
                _Arm1Transform.Rotation = new float3(0, arm1_rotation_y, 0);
            }

            if (_Arm2)
            {
                float arm2_rotation_z = _Arm2Transform.Rotation.z;
                arm2_rotation_z += 2 * Keyboard.WSAxis * DeltaTime;
                if (arm2_rotation_z <= 1.5 && arm2_rotation_z >= -1.5)
                {
                    _Arm2Transform.Rotation = new float3(0, 0, arm2_rotation_z);
                }
            }

            if (_Arm3)
            {
                float arm3_rotation_z = _Arm3Transform.Rotation.z;
                arm3_rotation_z += 2 * Keyboard.WSAxis * DeltaTime;
                if (arm3_rotation_z <= 1 && arm3_rotation_z >= -1)
                {
                    _Arm3Transform.Rotation = new float3(0, 0, arm3_rotation_z);
                }
                //Diagnostics.Log(arm3_rotation_z);
            }


            // Clear the backbuffer
            RC.Clear(ClearFlags.Color | ClearFlags.Depth);

            // Setup the camera
            _camAngle += 12.0f * M.Pi / 180.0f * DeltaTime;
            RC.View    = float4x4.CreateTranslation(0, 0, 40) * float4x4.CreateRotationY(_camAngle);

            if (Mouse.LeftButton)
            {
                float2 pickPosClip = Mouse.Position * new float2(2.0f / Width, -2.0f / Height) + new float2(-1, 1);
                _scenePicker.View       = RC.View;
                _scenePicker.Projection = RC.Projection;

                List <PickResult> pickResults = _scenePicker.Pick(pickPosClip).ToList();
                PickResult        newPick     = null;
                if (pickResults.Count > 0)
                {
                    pickResults.Sort((a, b) => Sign(a.ClipPos.z - b.ClipPos.z));
                    newPick = pickResults[0];
                }

                if (newPick?.Node != _currentPick?.Node)
                {
                    if (_currentPick != null)
                    {
                        ShaderEffectComponent shaderEffectComponent = _currentPick.Node.GetComponent <ShaderEffectComponent>();
                        shaderEffectComponent.Effect.SetEffectParam("DiffuseColor", _oldColor);
                    }
                    if (newPick != null)
                    {
                        ShaderEffectComponent shaderEffectComponent = newPick.Node.GetComponent <ShaderEffectComponent>();
                        _oldColor = (float3)shaderEffectComponent.Effect.GetEffectParam("DiffuseColor");
                        shaderEffectComponent.Effect.SetEffectParam("DiffuseColor", new float3(1, 0.4f, 0.4f));

                        if (newPick.Node.Name == "Arm1")
                        {
                            _Arm1 = true;
                            _Arm2 = false;
                            _Arm3 = false;
                        }
                        else if (newPick.Node.Name == "Arm2")
                        {
                            _Arm1 = false;
                            _Arm2 = true;
                            _Arm3 = false;
                        }
                        else if (newPick.Node.Name == "Arm3")
                        {
                            _Arm1 = false;
                            _Arm2 = false;
                            _Arm3 = true;
                        }
                        else
                        {
                            _Arm1 = false;
                            _Arm2 = false;
                            _Arm3 = false;
                        }
                    }
                    _currentPick = newPick;
                }
            }

            // Render the scene on the current render context
            _sceneRenderer.Render(RC);

            // Swap buffers: Show the contents of the backbuffer (containing the currently rendered farame) on the front buffer.
            Present();
        }
コード例 #52
0
        // RenderAFrame is called once a frame
        public override void RenderAFrame()
        {
            // Clear the backbuffer
            RC.Clear(ClearFlags.Color | ClearFlags.Depth);

            // Mouse and keyboard movement
            if (Mouse.LeftButton)
            {
                _pick    = true;
                _pickPos = Mouse.Position;
            }
            else
            {
                _pick  = false;
                toggle = false;
            }

            _DistanceFactor = _DistanceFactor + Mouse.WheelVel * 0.001f;

            _LookAtPosition   = float3.Lerp(_LookAtPositionLerpTo, _LookAtPositionLerpFrom, _LerpTimer);
            _LookFromPosition = float3.Lerp(_LookFromPositionLerpTo, _LookFromPositionLerpFrom, _LerpTimer);

            var mtxCam = float4x4.LookAt(_LookFromPosition * _DistanceFactor, _LookAtPosition, _LookUpDefault);

            if (_pick && !toggle)
            {
                float2 pickPosClip = _pickPos * new float2(2.0f / Width, -2.0f / Height) + new float2(-1, 1);

                _scenePicker.View = mtxCam;

                PickResult newPick = _scenePicker.Pick(pickPosClip).ToList().OrderBy(pr => pr.ClipPos.z).FirstOrDefault();


                if (newPick != null)
                {
                    Diagnostics.Log("PositionCenter: " + GetTriagleCenter(newPick));
                    Diagnostics.Log("PositionBary: " + GetTriagleBarycentric(newPick));
                    Diagnostics.Log("NormalsCenter: " + GetNormalsCenter(newPick));
                    Diagnostics.Log("NormalBary: " + GetNormalsBarycentric(newPick));
                    _LookAtPositionLerpFrom = _LookAtPosition;
                    _LookAtPositionLerpTo   = GetTriagleBarycentric(newPick);

                    _LookFromPositionLerpFrom = _LookFromPosition;
                    _LookFromPositionLerpTo   = GetTriagleBarycentric(newPick) + GetNormalsBarycentric(newPick);

                    _LerpTimer = 1;

                    toggle = true;
                }
            }

            // Render the scene loaded in Init()
            RC.ModelView = mtxCam;
            _sceneRenderer.Render(RC);
            // Swap buffers: Show the contents of the backbuffer (containing the currently rendered frame) on the front buffer.
            Present();

            if (_LerpTimer > 0)
            {
                _LerpTimer -= (Time.DeltaTime / _LerpSpeed);
            }

            if (_LerpTimer < 0)
            {
                _LerpTimer = 0;
            }
        }
コード例 #53
0
ファイル: BallSystem.cs プロジェクト: spicysoft/h5g-batting
 // 外積.
 float cross2d(float2 v1, float2 v2)
 {
     return(v1.x * v2.y - v1.y * v2.x);
 }
コード例 #54
0
ファイル: BallSystem.cs プロジェクト: spicysoft/h5g-batting
 // 内積.
 float inner2d(float2 v1, float2 v2)
 {
     return(v1.x * v2.x + v1.y * v2.y);
 }
コード例 #55
0
        protected override void OnUpdate()
        {
            this.Entities.With(this._triggerCutsceneGroup).ForEach((Entity exitEntity, Transform levelExitTransform, ref PositionComponent exitPositionComponent) =>
            {
                var player       = GameObject.FindGameObjectWithTag("Player");
                var playerEntity = player.GetComponent <GameObjectEntity>().Entity;
                var rigidbody    = player.GetComponent <Rigidbody2D>();
                var director     = TimelinesManagerComponent.Instance.Timelines.PlayerDungeonExit;
                var levelExit    = levelExitTransform.GetChild(0).gameObject;

                var playerPosition  = new float2(player.transform.position.x, player.transform.position.y);
                var desiredPosition = exitPositionComponent.CurrentPosition;
                desiredPosition.y  -= 1f;

                if (!this.EntityManager.HasComponent <InCutsceneComponent>(playerEntity))
                {
                    this.PostUpdateCommands.AddComponent(playerEntity, new InCutsceneComponent());
                }

                var movementComponent = this.EntityManager.GetComponentData <MovementComponent>(playerEntity);
                if (math.abs(playerPosition.x - desiredPosition.x) > 0.1f ||
                    math.abs(playerPosition.y - desiredPosition.y) > 0.1f)
                {
                    movementComponent.Direction = desiredPosition - playerPosition;
                    this.PostUpdateCommands.SetComponent(playerEntity, movementComponent);
                    return;
                }
                movementComponent.Direction = float2.zero;
                this.PostUpdateCommands.SetComponent(playerEntity, movementComponent);

                if (!director.enabled)
                {
                    director.enabled = true;
                }

                void onStop(PlayableDirector aDirector)
                {
                    this.cutsceneDone     = true;
                    rigidbody.isKinematic = false;
                    director.stopped     -= onStop;
                    director.enabled      = false;
                }
                director.stopped += onStop;

                foreach (var playableAssetOutput in director.playableAsset.outputs)
                {
                    if (playableAssetOutput.streamName == "PlayerAnim")
                    {
                        director.SetGenericBinding(playableAssetOutput.sourceObject, player);
                    }
                    else if (playableAssetOutput.streamName == "PlayerMove")
                    {
                        director.SetGenericBinding(playableAssetOutput.sourceObject, player);
                    }
                    else if (playableAssetOutput.streamName == "CaveFall")
                    {
                        director.SetGenericBinding(playableAssetOutput.sourceObject, levelExit);
                    }
                }
                this.cutsceneDone     = false;
                rigidbody.isKinematic = true;
                this.PostUpdateCommands.AddComponent(playerEntity, new PlayerExitCutscenePlaying());
                director.Play();
                this.PostUpdateCommands.RemoveComponent <PlayerExitCutsceneComponent>(exitEntity);
            });

            this.Entities.With(this._playerDoneCutSceneGroup).ForEach((Entity playerEntity, Transform transform, Rigidbody2D rigidbody) =>
            {
                if (this.cutsceneDone)
                {
                    this.PostUpdateCommands.RemoveComponent <InCutsceneComponent>(playerEntity);
                    this.PostUpdateCommands.RemoveComponent <PlayerExitCutscenePlaying>(playerEntity);

                    var saveGameEntity = this.PostUpdateCommands.CreateEntity();
                    this.PostUpdateCommands.AddComponent(saveGameEntity, new SaveGameComponent());

                    var sceneLoadEntity = this.PostUpdateCommands.CreateEntity();
                    this.PostUpdateCommands.AddComponent(sceneLoadEntity, new SceneLoadComponent
                    {
                        SceneIndex = SceneUtility.GetBuildIndexByScenePath("Assets/Scenes/DungeonScene.unity")
                    });
                }
            });
        }
コード例 #56
0
        public override void Draw()
        {
            if (GetSeries == null || !GetSeries().Any() ||
                GetLabelFont == null || GetLabelFont() == null ||
                GetAxisFont == null || GetAxisFont() == null)
            {
                return;
            }

            var rect   = RenderBounds;
            var origin = new float2(rect.Left, rect.Bottom);

            var width  = rect.Width;
            var height = rect.Height;

            var tiny = Game.Renderer.Fonts[GetLabelFont()];
            var bold = Game.Renderer.Fonts[GetAxisFont()];

            var xAxisSize = GetXAxisSize();
            var yAxisSize = GetYAxisSize();

            var maxValue = GetSeries().Select(p => p.Points).SelectMany(d => d).Concat(new[] { 0f }).Max();
            var scale    = 200 / Math.Max(5000, (float)Math.Ceiling(maxValue / 1000) * 1000);

            var xStep = width / xAxisSize;
            var yStep = height / yAxisSize;

            var pointCount = GetSeries().First().Points.Count();
            var pointStart = Math.Max(0, pointCount - xAxisSize);
            var pointEnd   = Math.Max(pointCount, xAxisSize);

            var keyOffset = 0;

            foreach (var series in GetSeries())
            {
                var key    = series.Key;
                var color  = series.Color;
                var points = series.Points;
                if (points.Any())
                {
                    points = points.Reverse().Take(xAxisSize).Reverse();
                    var lastX     = 0;
                    var lastPoint = 0f;
                    Game.Renderer.LineRenderer.DrawLineStrip(
                        points.Select((point, x) =>
                    {
                        lastX     = x;
                        lastPoint = point;
                        return(origin + new float2(x * xStep, -point * scale));
                    }), color);

                    if (lastPoint != 0f)
                    {
                        tiny.DrawText(GetValueFormat().F(lastPoint), origin + new float2(lastX * xStep, -lastPoint * scale - 2), color);
                    }
                }

                tiny.DrawText(key, new float2(rect.Left, rect.Top) + new float2(5, 10 * keyOffset + 3), color);
                keyOffset++;
            }

            // TODO: make this stuff not draw outside of the RenderBounds
            for (int n = pointStart, x = 0; n <= pointEnd; n++, x += xStep)
            {
                Game.Renderer.LineRenderer.DrawLine(origin + new float2(x, 0), origin + new float2(x, -5), Color.White);
                tiny.DrawText(GetXAxisValueFormat().F(n), origin + new float2(x, 2), Color.White);
            }

            bold.DrawText(GetXAxisLabel(), origin + new float2(width / 2, 20), Color.White);

            for (var y = GetDisplayFirstYAxisValue() ? 0 : yStep; y <= height; y += yStep)
            {
                var yValue = y / scale;
                Game.Renderer.LineRenderer.DrawLine(origin + new float2(width - 5, -y), origin + new float2(width, -y), Color.White);
                tiny.DrawText(GetYAxisValueFormat().F(yValue), origin + new float2(width + 2, -y), Color.White);
            }

            bold.DrawText(GetYAxisLabel(), origin + new float2(width + 40, -(height / 2)), Color.White);

            Game.Renderer.LineRenderer.DrawLine(origin, origin + new float2(width, 0), Color.White);
            Game.Renderer.LineRenderer.DrawLine(origin, origin + new float2(0, -height), Color.White);
            Game.Renderer.LineRenderer.DrawLine(origin + new float2(width, 0), origin + new float2(width, -height), Color.White);
            Game.Renderer.LineRenderer.DrawLine(origin + new float2(0, -height), origin + new float2(width, -height), Color.White);
        }
コード例 #57
0
 /**
  * <summary>Queries the visibility between two points within a specified
  * radius.</summary>
  *
  * <returns>True if q1 and q2 are mutually visible within the radius;
  * false otherwise.</returns>
  *
  * <param name="q1">The first point between which visibility is to be
  * tested.</param>
  * <param name="q2">The second point between which visibility is to be
  * tested.</param>
  * <param name="radius">The radius within which visibility is to be
  * tested.</param>
  */
 internal bool queryVisibility(float2 q1, float2 q2, float radius)
 {
     return(queryVisibilityRecursive(q1, q2, radius, obstacleTree_));
 }
コード例 #58
0
        /**
         * <summary>Recursive method for building an obstacle k-D tree.
         * </summary>
         *
         * <returns>An obstacle k-D tree node.</returns>
         *
         * <param name="obstacles">A list of obstacles.</param>
         */
        private ObstacleTreeNode buildObstacleTreeRecursive(IList <Obstacle> obstacles)
        {
            if (obstacles.Count == 0)
            {
                return(null);
            }

            ObstacleTreeNode node = new ObstacleTreeNode();

            int optimalSplit = 0;
            int minLeft      = obstacles.Count;
            int minRight     = obstacles.Count;

            for (int i = 0; i < obstacles.Count; ++i)
            {
                int leftSize  = 0;
                int rightSize = 0;

                Obstacle obstacleI1 = obstacles[i];
                Obstacle obstacleI2 = obstacleI1.next_;

                /* Compute optimal split node. */
                for (int j = 0; j < obstacles.Count; ++j)
                {
                    if (i == j)
                    {
                        continue;
                    }

                    Obstacle obstacleJ1 = obstacles[j];
                    Obstacle obstacleJ2 = obstacleJ1.next_;

                    float j1LeftOfI = RVOMath.leftOf(obstacleI1.point_, obstacleI2.point_, obstacleJ1.point_);
                    float j2LeftOfI = RVOMath.leftOf(obstacleI1.point_, obstacleI2.point_, obstacleJ2.point_);

                    if (j1LeftOfI >= -RVOMath.RVO_EPSILON && j2LeftOfI >= -RVOMath.RVO_EPSILON)
                    {
                        ++leftSize;
                    }
                    else if (j1LeftOfI <= RVOMath.RVO_EPSILON && j2LeftOfI <= RVOMath.RVO_EPSILON)
                    {
                        ++rightSize;
                    }
                    else
                    {
                        ++leftSize;
                        ++rightSize;
                    }

                    if (new FloatPair(Math.Max(leftSize, rightSize), Math.Min(leftSize, rightSize)) >= new FloatPair(Math.Max(minLeft, minRight), Math.Min(minLeft, minRight)))
                    {
                        break;
                    }
                }

                if (new FloatPair(Math.Max(leftSize, rightSize), Math.Min(leftSize, rightSize)) < new FloatPair(Math.Max(minLeft, minRight), Math.Min(minLeft, minRight)))
                {
                    minLeft      = leftSize;
                    minRight     = rightSize;
                    optimalSplit = i;
                }
            }

            {
                /* Build split node. */
                IList <Obstacle> leftObstacles = new List <Obstacle> (minLeft);

                for (int n = 0; n < minLeft; ++n)
                {
                    leftObstacles.Add(null);
                }

                IList <Obstacle> rightObstacles = new List <Obstacle> (minRight);

                for (int n = 0; n < minRight; ++n)
                {
                    rightObstacles.Add(null);
                }

                int leftCounter  = 0;
                int rightCounter = 0;
                int i            = optimalSplit;

                Obstacle obstacleI1 = obstacles[i];
                Obstacle obstacleI2 = obstacleI1.next_;

                for (int j = 0; j < obstacles.Count; ++j)
                {
                    if (i == j)
                    {
                        continue;
                    }

                    Obstacle obstacleJ1 = obstacles[j];
                    Obstacle obstacleJ2 = obstacleJ1.next_;

                    float j1LeftOfI = RVOMath.leftOf(obstacleI1.point_, obstacleI2.point_, obstacleJ1.point_);
                    float j2LeftOfI = RVOMath.leftOf(obstacleI1.point_, obstacleI2.point_, obstacleJ2.point_);

                    if (j1LeftOfI >= -RVOMath.RVO_EPSILON && j2LeftOfI >= -RVOMath.RVO_EPSILON)
                    {
                        leftObstacles[leftCounter++] = obstacles[j];
                    }
                    else if (j1LeftOfI <= RVOMath.RVO_EPSILON && j2LeftOfI <= RVOMath.RVO_EPSILON)
                    {
                        rightObstacles[rightCounter++] = obstacles[j];
                    }
                    else
                    {
                        /* Split obstacle j. */
                        float t = RVOMath.det(obstacleI2.point_ - obstacleI1.point_, obstacleJ1.point_ - obstacleI1.point_) / RVOMath.det(obstacleI2.point_ - obstacleI1.point_, obstacleJ1.point_ - obstacleJ2.point_);

                        float2 splitPoint = obstacleJ1.point_ + t * (obstacleJ2.point_ - obstacleJ1.point_);

                        Obstacle newObstacle = new Obstacle();
                        newObstacle.point_     = splitPoint;
                        newObstacle.previous_  = obstacleJ1;
                        newObstacle.next_      = obstacleJ2;
                        newObstacle.convex_    = true;
                        newObstacle.direction_ = obstacleJ1.direction_;

                        newObstacle.id_ = Simulator.Instance.obstacles_.Count;

                        Simulator.Instance.obstacles_.Add(newObstacle);

                        obstacleJ1.next_     = newObstacle;
                        obstacleJ2.previous_ = newObstacle;

                        if (j1LeftOfI > 0.0f)
                        {
                            leftObstacles[leftCounter++]   = obstacleJ1;
                            rightObstacles[rightCounter++] = newObstacle;
                        }
                        else
                        {
                            rightObstacles[rightCounter++] = obstacleJ1;
                            leftObstacles[leftCounter++]   = newObstacle;
                        }
                    }
                }

                node.obstacle_ = obstacleI1;
                node.left_     = buildObstacleTreeRecursive(leftObstacles);
                node.right_    = buildObstacleTreeRecursive(rightObstacles);

                return(node);
            }
        }
コード例 #59
0
        // RenderAFrame is called once a frame
        public override void RenderAFrame()
        {
            if (_gamePad != null)
            {
                Diagnostics.Log(_gamePad.LSX);
            }

            // Clear the backbuffer
            RC.Clear(ClearFlags.Color | ClearFlags.Depth);

            // Mouse and keyboard movement
            if (Keyboard.LeftRightAxis != 0 || Keyboard.UpDownAxis != 0)
            {
                _keys = true;
            }

            var curDamp = (float)System.Math.Exp(-Damping * DeltaTime);

            // Zoom & Roll
            if (Touch.TwoPoint)
            {
                if (!_twoTouchRepeated)
                {
                    _twoTouchRepeated = true;
                    _angleRollInit    = Touch.TwoPointAngle - _angleRoll;
                    _offsetInit       = Touch.TwoPointMidPoint - _offset;
                    _maxPinchSpeed    = 0;
                }
                _zoomVel   = Touch.TwoPointDistanceVel * -0.01f;
                _angleRoll = Touch.TwoPointAngle - _angleRollInit;
                _offset    = Touch.TwoPointMidPoint - _offsetInit;
                float pinchSpeed = Touch.TwoPointDistanceVel;
                if (pinchSpeed > _maxPinchSpeed)
                {
                    _maxPinchSpeed = pinchSpeed;                              // _maxPinchSpeed is used for debugging only.
                }
            }
            else
            {
                _twoTouchRepeated = false;
                _zoomVel          = Mouse.WheelVel * -0.5f;
                _angleRoll       *= curDamp * 0.8f;
                _offset          *= curDamp * 0.8f;
            }



            // UpDown / LeftRight rotation
            if (Mouse.LeftButton)
            {
                _keys          = false;
                _angleVelHorz += -RotationSpeed * Mouse.XVel * DeltaTime * 0.00005f;
                _angleVelVert += -RotationSpeed * Mouse.YVel * DeltaTime * 0.00005f;
            }

            else if (_spaceMouse != null)
            {
                _angleVelHorz += _spaceMouse.Rotation.y * -0.00005f * DeltaTime;
                _angleVelVert += _spaceMouse.Rotation.x * -0.00005f * DeltaTime;
            }

            else if (_gamePad != null)
            {
                _angleVelHorz -= -RotationSpeed * _gamePad.LSX * DeltaTime;
                _angleVelVert -= -RotationSpeed * _gamePad.LSY * DeltaTime;
            }

            else if (Touch.GetTouchActive(TouchPoints.Touchpoint_0) && !Touch.TwoPoint)
            {
                _keys = false;
                float2 touchVel;
                touchVel      = Touch.GetVelocity(TouchPoints.Touchpoint_0);
                _angleVelHorz = -RotationSpeed * touchVel.x * DeltaTime * 0.0005f;
                _angleVelVert = -RotationSpeed * touchVel.y * DeltaTime * 0.0005f;
            }
            else
            {
                if (_keys)
                {
                    _angleVelHorz = -RotationSpeed * Keyboard.LeftRightAxis * DeltaTime;
                    _angleVelVert = -RotationSpeed * Keyboard.UpDownAxis * DeltaTime;
                }
                else
                {
                    _angleVelHorz *= curDamp;
                    _angleVelVert *= curDamp;
                }
            }

            _zoom += _zoomVel;
            // Limit zoom
            if (_zoom < 80)
            {
                _zoom = 80;
            }
            if (_zoom > 2000)
            {
                _zoom = 2000;
            }

            _angleHorz += _angleVelHorz;
            // Wrap-around to keep _angleHorz between -PI and + PI
            _angleHorz = M.MinAngle(_angleHorz);

            _angleVert += _angleVelVert;
            // Limit pitch to the range between [-PI/2, + PI/2]
            _angleVert = M.Clamp(_angleVert, -M.PiOver2, M.PiOver2);

            // Wrap-around to keep _angleRoll between -PI and + PI
            _angleRoll = M.MinAngle(_angleRoll);

            // Create the camera matrix and set it as the current View transformation
            var mtxRot = /*float4x4.CreateRotationZ(_angleRoll) **/ float4x4.CreateRotationX(_angleVert) * float4x4.CreateRotationY(_angleHorz);
            var mtxCam = float4x4.LookAt(0, 20, -_zoom, 0, 0, 0, 0, 1, 0);

            RC.View = mtxCam * mtxRot * _sceneScale * _sceneCenter;
            var mtxOffset = float4x4.CreateTranslation(2f * _offset.x / Width, -2f * _offset.y / Height, 0);

            RC.Projection *= mtxOffset;

            // Constantly check for interactive objects.
            _sih.CheckForInteractiveObjects(Input.Mouse.Position, Width, Height);

            if (Touch.GetTouchActive(TouchPoints.Touchpoint_0) && !Touch.TwoPoint)
            {
                _sih.CheckForInteractiveObjects(Touch.GetPosition(TouchPoints.Touchpoint_0), Width, Height);
            }
            // Tick any animations and Render the scene loaded in Init()
            _sceneRenderer.Animate();

            _sceneRenderer.Render(RC);

            var projection = float4x4.CreateOrthographic(Width, Height, ZNear, ZFar);

            RC.Projection = projection;

            _sih.View = RC.View;

            _guiRenderer.Render(RC);

            projection    = float4x4.CreatePerspectiveFieldOfView(_fovy, _aspectRatio, ZNear, ZFar);
            RC.Projection = projection;

            // Swap buffers: Show the contents of the backbuffer (containing the currently rendered frame) on the front buffer.
            Present();
        }
コード例 #60
0
 public Rect(float2 topLeft, float2 bottomRight)
 {
     this.bottomLeft = topLeft;
     this.topRight   = bottomRight;
 }