Exemple #1
0
        public void SetPlayerPosition(EntityPosition newPosition)
        {
            using (Profiler.CurrentProfiler.Begin("Updating Task Priorities"))
            {
                var difference = newPosition.RelativeTo(_lastPlayerPosition);
                var distance   = difference.Length();

                int tickCount = Environment.TickCount;

                if (distance > 1 && tickCount - _oldTickCount >= 1000)
                {
                    Debug.WriteLine($"Updating Task Priorities... {newPosition}");
                    lock (_tasks)
                    {
                        for (int i = 0; i < _tasks.Length; i++)
                        {
                            foreach (var task in _tasks[i])
                            {
                                task.UpdatePriority(_lastPlayerPosition);
                            }
                        }
                    }
                    _lastPlayerPosition = newPosition;
                    _oldTickCount       = tickCount;
                }
            }
        }
        public string PrintFeature(bool link = true, DwarfObject pov = null)
        {
            string eventString = "";

            eventString += "the ascention of ";
            if (HistoricalFigure != null)
            {
                eventString += HistoricalFigure.ToLink(link, pov);
            }
            else
            {
                eventString += "UNKNOWN HISTORICAL FIGURE";
            }

            eventString += " to the position of ";
            EntityPosition position = Entity.EntityPositions.FirstOrDefault(pos => pos.Name.ToLower() == Position.ToLower());

            if (position != null)
            {
                string positionName = position.GetTitleByCaste(HistoricalFigure.Caste);
                eventString += positionName;
            }
            else
            {
                eventString += Position;
            }
            eventString += " of ";
            eventString += Entity.ToLink(link, pov);
            eventString += " in ";
            eventString += Year;
            return(eventString);
        }
Exemple #3
0
        public override EntityPosition GetPosition(IDynamicEntity owner)
        {
            var pos = new EntityPosition();

            if (!owner.EntityState.IsBlockPicked)
            {
                return(pos);
            }

            // Get the chunk where the entity will be added and check if another entity is present inside this block
            var workingchunk = LandscapeManager.GetChunkFromBlock(owner.EntityState.NewBlockPosition);

            foreach (var entity in workingchunk.Entities.OfType <IBlockLocationRoot>())
            {
                if (entity.BlockLocationRoot == BlockLocationRoot)
                {
                    // IBlockLocationRoot Entity already present at this location
                    return(pos);
                }
            }

            pos.Position = new Vector3D(owner.EntityState.NewBlockPosition.X + 0.5f,
                                        owner.EntityState.NewBlockPosition.Y,
                                        owner.EntityState.NewBlockPosition.Z + 0.5f);

            pos.Rotation = Quaternion.Identity;
            pos.Valid    = true;

            return(pos);
        }
Exemple #4
0
 private void PrintPositions()
 {
     if (_historicalFigure.Positions.Count > 0)
     {
         Html.AppendLine(Bold("Positions") + LineBreak);
         StartList(ListType.Ordered);
         foreach (HistoricalFigure.Position hfposition in _historicalFigure.Positions)
         {
             Html.AppendLine("<li>");
             EntityPosition position = hfposition.Entity.EntityPositions.FirstOrDefault(pos => pos.Name.ToLower() == hfposition.Title.ToLower());
             if (position != null)
             {
                 string positionName = position.GetTitleByCaste(_historicalFigure.Caste);
                 Html.Append(positionName);
             }
             else
             {
                 Html.Append(hfposition.Title + " of " + hfposition.Entity.PrintEntity() + " (" + hfposition.Began + " - ");
             }
             string end = hfposition.Ended == -1 ? "Present" : hfposition.Ended.ToString();
             Html.Append(" of " + hfposition.Entity.PrintEntity() + " (" + hfposition.Began + " - " + end + ")");
         }
         EndList(ListType.Ordered);
     }
 }
        private void PrintCurrentLeadership()
        {
            if (_entity.EntityPositionAssignments.Any() && _entity.EntityPositionAssignments.Where(epa => epa.HistoricalFigure != null).Any())
            {
                Html.AppendLine("<b>Current Leadership</b><br />");
                Html.AppendLine("<ul>");
                foreach (EntityPositionAssignment assignment in _entity.EntityPositionAssignments)
                {
                    EntityPosition position = _entity.EntityPositions.FirstOrDefault(pos => pos.Id == assignment.PositionId);
                    if (position != null && assignment.HistoricalFigure != null)
                    {
                        string positionName = position.GetTitleByCaste(assignment.HistoricalFigure.Caste);

                        Html.AppendLine("<li>" + assignment.HistoricalFigure.ToLink() + ", " + positionName + "</li>");

                        if (!string.IsNullOrEmpty(position.Spouse))
                        {
                            HistoricalFigureLink spouseLink = assignment.HistoricalFigure.RelatedHistoricalFigures.FirstOrDefault(hfLink => hfLink.Type == HistoricalFigureLinkType.Spouse);
                            if (spouseLink != null)
                            {
                                HistoricalFigure spouse = spouseLink.HistoricalFigure;
                                if (spouse != null)
                                {
                                    string spousePositionName = position.GetTitleByCaste(spouse.Caste, true);
                                    Html.AppendLine("<li>" + spouse.ToLink() + ", " + spousePositionName + "</li>");
                                }
                            }
                        }
                    }
                }
                Html.AppendLine("</ul>");
            }
        }
Exemple #6
0
        public override void Load(BinaryReader r, uint id)
        {
            base.Load(r, id);

            EntityName = GetStringFromInt(r.ReadUInt32());

            World = ReadNullableObject <IWorld>(r);

            Rotation = r.ReadDouble();
            var pos = new EntityPosition();

            pos.X     = r.ReadDouble();
            pos.Y     = r.ReadDouble();
            _position = pos;
            Color color = new Color();

            color.R     = r.ReadByte();
            color.G     = r.ReadByte();
            color.B     = r.ReadByte();
            color.A     = r.ReadByte();
            EntityColor = color;
            Radius      = r.ReadInt32();
            Age         = r.ReadInt32();

            IsDead = r.ReadBoolean();
        }
Exemple #7
0
        public override void Idle(Microsoft.Xna.Framework.GameTime gameTime)
        {
            base.Idle(gameTime);

            if (Simulation == null)
            {
                MenuBar.GetItem("Edit").Enabled       = false;
                MenuBar.GetItem("Simulation").Enabled = false;
                MenuBar.GetItem("Entities").Enabled   = false;
                MenuBar.GetItem("World").Enabled      = false;
            }
            else
            {
                MenuBar.GetItem("Edit").Enabled       = true;
                MenuBar.GetItem("Simulation").Enabled = true;
                MenuBar.GetItem("Entities").Enabled   = true;
                MenuBar.GetItem("World").Enabled      = true;
            }

            if (Mode == Modes.AddEntity)
            {
                if (WorldBox.IsUnderMouse && MouseInput.IsClicked(TakaGUI.Services.MouseButtons.Left))
                {
                    var entity = GetEntityFunction();

                    var pos = new EntityPosition();
                    pos.X           = (MouseInput.X - WorldBox.RealX + WorldBox.ViewCamera.LookX) / WorldBox.ViewCamera.Zoom;
                    pos.Y           = (MouseInput.Y - WorldBox.RealY + WorldBox.ViewCamera.LookY) / WorldBox.ViewCamera.Zoom;
                    entity.Position = pos;

                    WorldBox.World.AddEntity(entity);
                }
                else if (WorldBox.IsUnderMouse && MouseInput.IsClicked(TakaGUI.Services.MouseButtons.Right))
                {
                    Mode = Modes.None;
                }
            }
            else if (Mode == Modes.SetPeremiter)
            {
                if (MouseInput.IsClicked(TakaGUI.Services.MouseButtons.Left))
                {
                    var c = p1;
                    p1 = p2;
                    p2 = c;
                }
                else if (MouseInput.IsClicked(TakaGUI.Services.MouseButtons.Right))
                {
                    Mode = Modes.None;
                    var peremiter = new Rectangle();
                    peremiter.X      = Math.Min(p1.X, p2.X);
                    peremiter.Y      = Math.Min(p1.Y, p2.Y);
                    peremiter.Width  = Math.Max(p1.X, p2.X) - peremiter.X;
                    peremiter.Height = Math.Max(p1.Y, p2.Y) - peremiter.Y;

                    SendPeremiterFunction(peremiter);
                }

                p1 = new Point(MouseInput.X, MouseInput.Y);
            }
        }
        public override string Print(bool link = true, DwarfObject pov = null)
        {
            string eventString = GetYearTime();

            if (HistoricalFigure != null)
            {
                eventString += HistoricalFigure.ToLink(link, pov);
            }
            else
            {
                eventString += "UNKNOWN HISTORICAL FIGURE";
            }

            switch (LinkType)
            {
            case HfEntityLinkType.Prisoner:
                eventString += " was imprisoned by ";
                break;

            case HfEntityLinkType.Slave:
                eventString += " was enslaved by ";
                break;

            case HfEntityLinkType.Enemy:
                eventString += " became an enemy of ";
                break;

            case HfEntityLinkType.Member:
                eventString += " became a member of ";
                break;

            case HfEntityLinkType.FormerMember:
                eventString += " became a former member of ";
                break;

            case HfEntityLinkType.Squad:
            case HfEntityLinkType.Position:
                EntityPosition position = Entity.EntityPositions.FirstOrDefault(pos => pos.Name.ToLower() == Position.ToLower());
                if (position != null)
                {
                    string positionName = position.GetTitleByCaste(HistoricalFigure.Caste);
                    eventString += " became the " + positionName + " of ";
                }
                else
                {
                    eventString += " became the " + Position + " of ";
                }
                break;

            default:
                eventString += " linked to ";
                break;
            }

            eventString += Entity.ToLink(link, pov);
            eventString += PrintParentCollection(link, pov);
            eventString += ".";
            return(eventString);
        }
Exemple #9
0
 private void numZ_ValueChanged(object sender, EventArgs e)
 {
     if (!positiondirty)
     {
         EntityPosition pos = entity.Positions[positionindex];
         entity.Positions[positionindex] = new EntityPosition(pos.X, pos.Y, (short)numZ.Value);
     }
 }
Exemple #10
0
        public override void SetPosition(EntityPosition pos, IItem item, IDynamicEntity owner)
        {
            base.SetPosition(pos, item, owner);

            var cubeEntity = (BlockItem)item;

            cubeEntity.BlockLocationRoot = BlockHelper.EntityToBlock(pos.Position);
        }
Exemple #11
0
        public override string Print(bool link = true, DwarfObject pov = null)
        {
            string eventString = GetYearTime();

            if (HistoricalFigure != null)
            {
                eventString += HistoricalFigure.ToLink(link, pov, this);
            }
            else
            {
                eventString += "UNKNOWN HISTORICAL FIGURE";
            }
            switch (LinkType)
            {
            case HfEntityLinkType.Prisoner:
                eventString += " escaped from the prisons of ";
                break;

            case HfEntityLinkType.Slave:
                eventString += " fled from ";
                break;

            case HfEntityLinkType.Enemy:
                eventString += " stopped being an enemy of ";
                break;

            case HfEntityLinkType.Member:
                eventString += " left ";
                break;

            case HfEntityLinkType.Squad:
            case HfEntityLinkType.Position:
                EntityPosition position = Entity.EntityPositions.FirstOrDefault(pos => pos.Name.ToLower() == Position.ToLower() || pos.Id == PositionId);
                if (position != null)
                {
                    string positionName = position.GetTitleByCaste(HistoricalFigure?.Caste);
                    eventString += " stopped being the " + positionName + " of ";
                }
                else if (!string.IsNullOrWhiteSpace(Position))
                {
                    eventString += " stopped being the " + Position + " of ";
                }
                else
                {
                    eventString += " stopped being an unspecified position of ";
                }
                break;

            default:
                eventString += " stopped being linked to ";
                break;
            }

            eventString += Entity.ToLink(link, pov, this);
            eventString += PrintParentCollection(link, pov);
            eventString += ".";
            return(eventString);
        }
Exemple #12
0
        public void Move(double dx, double dy)
        {
            var newPos = Position;

            newPos.X += dx;
            newPos.Y += dy;

            Position = newPos;
        }
        public override string Print(bool link = true, DwarfObject pov = null)
        {
            string eventString = GetYearTime();

            eventString += Artifact.ToLink(link, pov, this);
            if ((Claim == Claim.Symbol ||
                 Claim == Claim.Heirloom && HistoricalFigure != null) && Circumstance != "from afar")
            {
                eventString += " was made a ";
                eventString += Claim.GetDescription();
                if (PositionProfileId > -1 && Entity != null)
                {
                    eventString += " of the ";
                    bool foundPosition = false;
                    foreach (EntityPositionAssignment assignment in Entity.EntityPositionAssignments)
                    {
                        EntityPosition position =
                            Entity.EntityPositions.FirstOrDefault(pos => pos.Id == assignment.PositionId);
                        if (position != null && assignment.HistoricalFigure != null)
                        {
                            string positionName = position.GetTitleByCaste(assignment.HistoricalFigure.Caste);
                            eventString  += positionName;
                            foundPosition = true;
                            break;
                        }
                    }
                    if (!foundPosition)
                    {
                        eventString += "Position Title '" + PositionProfileId + "'";
                    }
                }
            }
            else
            {
                eventString += " was claimed";
            }
            if (Entity != null)
            {
                eventString += " by ";
                eventString += Entity.ToLink(link, pov, this);
            }
            if (HistoricalFigure != null)
            {
                eventString += " by ";
                eventString += HistoricalFigure.ToLink(link, pov, this);
            }

            if (!string.IsNullOrWhiteSpace(Circumstance))
            {
                eventString += " ";
                eventString += Circumstance;
            }
            eventString += PrintParentCollection(link, pov);
            eventString += ".";
            return(eventString);
        }
        public override void SetPosition(EntityPosition pos, IItem item, IDynamicEntity owner)
        {
            base.SetPosition(pos, item, owner);

            var blockItem = item as OrientedBlockLinkedItem;

            if (blockItem != null)
            {
                blockItem.Orientation = pos.Orientation;
            }
        }
Exemple #15
0
        public static bool IsColliding(this Entity entity, EntityPosition targetEntityPosition, double targetEntityCollisionDistanceX, double targetEntityCollisionDistanceY)
        {
            double bottom = entity.Position.PosY + entity.CollisionDistanceY;
            double top    = entity.Position.PosY;
            double left   = entity.Position.PosX;
            double right  = entity.Position.PosX + entity.CollisionDistanceX;

            return(!((bottom < targetEntityPosition.PosY) ||
                     (top > targetEntityPosition.PosY + targetEntityCollisionDistanceY) ||
                     (left > targetEntityPosition.PosX + targetEntityCollisionDistanceX) ||
                     (right < targetEntityPosition.PosX)));
        }
Exemple #16
0
        private void RenderEntity(Entity entity)
        {
            if (entity.Positions.Count == 1)
            {
                EntityPosition position = entity.Positions[0];
                GL.PushMatrix();
                GL.Translate(position.X, position.Y, position.Z);
                switch (entity.Type)
                {
                case 0x3:
                    if (entity.Subtype.HasValue)
                    {
                        RenderPickup(entity.Subtype.Value);
                    }
                    break;

                case 0x22:
                    if (entity.Subtype.HasValue)
                    {
                        RenderBox(entity.Subtype.Value);
                    }
                    break;

                default:
                    GL.Color3(Color.White);
                    LoadTexture(Resources.PointTexture);
                    RenderSprite();
                    break;
                }
                GL.PopMatrix();
            }
            else
            {
                GL.Color3(Color.Blue);
                GL.Begin(BeginMode.LineStrip);
                foreach (EntityPosition position in entity.Positions)
                {
                    GL.Vertex3(position.X, position.Y, position.Z);
                }
                GL.End();
                GL.Color3(Color.Red);
                foreach (EntityPosition position in entity.Positions)
                {
                    GL.Color3(Color.Red);
                    LoadTexture(Resources.PointTexture);
                    GL.PushMatrix();
                    GL.Translate(position.X, position.Y, position.Z);
                    RenderSprite();
                    GL.PopMatrix();
                }
            }
        }
Exemple #17
0
        private void PrintRelatedEntities()
        {
            if (_historicalFigure.RelatedEntities.Count > 0)
            {
                Html.AppendLine(Bold("Related Entities") + LineBreak);
                StartList(ListType.Unordered);
                foreach (EntityLink link in _historicalFigure.RelatedEntities)
                {
                    string linkString = link.Entity.PrintEntity() + " (" + link.Type.GetDescription();
                    if (link.Strength > 0)
                    {
                        linkString += " " + link.Strength + "%";
                    }

                    if (link.StartYear > -1)
                    {
                        linkString += " ";
                        var hfposition = _historicalFigure.Positions.FirstOrDefault(hfpos => hfpos.Began == link.StartYear && hfpos.Ended == link.EndYear);
                        if (hfposition != null)
                        {
                            EntityPosition position = link.Entity.EntityPositions.FirstOrDefault(pos => pos.Name == hfposition.Title);
                            if (position != null)
                            {
                                string positionName = position.GetTitleByCaste(_historicalFigure.Caste);
                                linkString += positionName;
                            }
                            else
                            {
                                linkString += hfposition.Title;
                            }
                        }
                        else
                        {
                            linkString += "Noble";
                        }
                        linkString += ", " + link.StartYear + "-";
                        if (link.EndYear > -1)
                        {
                            linkString += link.EndYear;
                        }
                        else
                        {
                            linkString += "Present";
                        }
                    }
                    linkString += ")";
                    Html.AppendLine(ListItem + linkString);
                }
                EndList(ListType.Unordered);
            }
        }
Exemple #18
0
        public override EntityPosition GetPosition(IDynamicEntity owner)
        {
            var pos = new EntityPosition();

            // allow to put only on top of the entity
            if (owner.EntityState.PickPointNormal.Y != 1)
            {
                return(pos);
            }

            pos.Position = new Vector3D(owner.EntityState.PickPoint);
            pos.Valid    = true;

            return(pos);
        }
Exemple #19
0
 public static void Load()
 {
     PositionOffsetPath     = new EntityPosition(0);
     RotationOffsetPath     = new EntityRotation(0);
     NetworkableOffsetPath  = new EntityNetworkable(0);
     PlayerFlagsPath        = new EntityPlayerFlags(0);
     EntityTagPath          = new EntityTag(0);
     EntityNamePath         = new EntityName(0);
     PlayerNamePath         = new PlayerName(0);
     EntityLayerPath        = new EntityLayerPath(0);
     EntitySteamID          = new EntitySteamID(0);
     EntityLifeState        = new EntityLifeState(0);
     EntityPlayerModelFlags = new EntityPlayerModelFlags(0);
     ActiveItem             = new PlayerActiveItem(0);
     BeltList     = new PlayerBeltItemList(0);
     EntityHealth = new EntityHealth(0);
 }
        public override void SetPosition(EntityPosition pos, IItem item, IDynamicEntity owner)
        {
            base.SetPosition(pos, item, owner);

            var cubeEntity = (BlockLinkedItem)item;

            if (!owner.EntityState.IsBlockPicked)
            {
                cubeEntity.Linked = false;
            }
            else
            {
                cubeEntity.LinkedCube        = owner.EntityState.PickedBlockPosition;
                cubeEntity.BlockLocationRoot = BlockHelper.EntityToBlock(pos.Position);
                cubeEntity.Linked            = true;
            }
        }
Exemple #21
0
        protected virtual void GUI_Edit_SetValues(ColumnListBox listBox)
        {
            Dictionary <string, object> values = new Dictionary <string, object>();

            foreach (var row in listBox.Values)
            {
                values.Add((string)row.Values[0], row.Values[1]);
            }

            Position = new EntityPosition((double)values["PositionX"], (double)values["PositionY"]);
            Rotation = (double)values["Rotation"];
            var entityColor = new Color();

            entityColor.R = (byte)values["EntityColorR"];
            entityColor.G = (byte)values["EntityColorG"];
            entityColor.B = (byte)values["EntityColorB"];
            EntityColor   = entityColor;
            Radius        = (int)values["Radius"];
            Age           = (int)values["Age"];
        }
Exemple #22
0
        public Tile(Grid parent, TilePos index)
            : base(parent.Game)
        {
            Parent  = parent;
            Context = parent.GenerationContext;
            Index   = index;
            Offset  = index.ToBlockPos();

            Centroid = EntityPosition.Create(Index, RealSize * 0.5f);

            Graphics = new TileGraphics(this);

            List <ConcurrentQueue <Action> > acts = new List <ConcurrentQueue <Action> >();

            foreach (var v in Enum.GetValues(typeof(GenerationStage)))
            {
                acts.Add(new ConcurrentQueue <Action>());
            }

            _pendingActions = acts.ToArray();
        }
        public string GetLastNoblePosition()
        {
            string title = "";

            if (Positions.Any())
            {
                string         positionName = "";
                var            hfposition   = Positions.Last();
                EntityPosition position     = hfposition.Entity.EntityPositions.FirstOrDefault(pos => pos.Name.ToLower() == hfposition.Title.ToLower());
                if (position != null)
                {
                    positionName = position.GetTitleByCaste(Caste);
                }
                else
                {
                    positionName = hfposition.Title;
                }
                title += (hfposition.Ended == -1 ? "" : "Former ") + positionName + " of " + hfposition.Entity.Name;
            }
            return(title);
        }
 public void AddEntities(params Entity[] entities)
 {
     int id = _entities.Count();
     foreach (var entity in entities)
     {
         _entities.Add(entity);
         for (int i = 0; i < entity.Tokens.Length; ++i)
         {
             var position = new EntityPosition(id, i);
             var token = entity.Tokens[i];
             List<EntityPosition> matches;
             if (_tokenToEntities.TryGetValue(token, out matches))
             {
                 matches.Add(position);
             }
             else
             {
                 _tokenToEntities[token] = new List<EntityPosition> { position };
             }
         }
         ++id;
     }
 }
Exemple #25
0
 private double RelativeToPlayer(EntityPosition centroid)
 {
     return(_lastPlayerPosition.RelativeTo(centroid).LengthSquared());
 }
Exemple #26
0
 public bool TileExists(EntityPosition playerPosition)
 {
     return(_tileManager.GetTileIfExists(playerPosition.BasePosition, out var tile) && tile.GeneratingPhase >= GenerationStage.Unstarted);
 }
Exemple #27
0
        public void SetPlayerPosition(EntityPosition newPosition)
        {
            if (saveInitializationPhase < 1)
            {
                return;
            }

            using (Profiler.CurrentProfiler.Begin("Updating Player Visibility"))
            {
                var difference = newPosition.RelativeTo(_lastPlayerPosition);
                var distance   = difference.Length();

                var tp = newPosition.BasePosition;
                if (!TileExists(newPosition))
                {
                    bootstrap = true;
                }

                if (Environment.TickCount - before <= 1000 || (distance <= 5 && !bootstrap))
                {
                    return;
                }

                using (Profiler.CurrentProfiler.Begin("Computing Visible Tiles"))
                {
                    Debug.WriteLine("Re-computing visible tiles...");

                    before = Environment.TickCount;

                    bootstrap = false;

                    tempTiles.Clear();

                    _tileManager.AccessUnordered(unorderedTile =>
                    {
                        tempTiles.AddRange(unorderedTile.Where(tile => Distance(newPosition, tile) > UnloadRadius).Select(t => t.Index));
                    });
                }

                using (Profiler.CurrentProfiler.Begin("Discarding Inactive Tiles"))
                {
                    Debug.WriteLine($"Discarding {tempTiles.Count} tiles...");
                    _tileManager.RemoveTiles(tempTiles);
                }

                using (Profiler.CurrentProfiler.Begin("Loading Visible Tiles"))
                {
                    lock (_pendingTilesList)
                    {
                        tempTiles.Clear();
                        //_pendingTilesSet.Clear();
                        //_pendingTilesList.Clear();

                        //for (int r = 0; r < LoadRange; r++)
                        var rX = LoadRadius / Tile.RealSize.X;
                        var rY = LoadRadius / Tile.RealSize.Y;
                        var rZ = LoadRadius / Tile.RealSize.Z;
                        {
                            for (int z = -rZ; z <= rZ; z++)
                            {
                                for (int x = -rX; x <= rX; x++)
                                {
                                    for (int y = -rY; y <= rY; y++)
                                    {
                                        if (!((new Vector3D(x, y, z) * Tile.RealSize).Length() <= LoadRadius))
                                        {
                                            continue;
                                        }

                                        var tpo = tp.Offset(x, y, z);
                                        if (tempTiles.Contains(tpo))
                                        {
                                            continue;
                                        }

                                        Request(tpo, GenerationStage.Completed, "Player Nearby", (b, t) => {});
                                    }
                                }
                            }
                            //if (_pendingTiles.Count >= MaxTilesQueued)
                            //    break;
                        }

                        _lastPlayerPosition = newPosition;

                        ResortPending();
                    }
                }
            }
        }
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            var mouseDelta = (Vector2)VoxelGame.Instance.MouseDelta;

            mouseDelta /= (float)gameTime.ElapsedGameTime.TotalSeconds;

            var elapsed = MathHelper.Min(1.0f / 20, (float)gameTime.ElapsedGameTime.TotalSeconds);

            mouseDelta *= elapsed;

            Vector3 move             = Vector3.Zero;
            bool    walkingIsPressed = false;
            bool    isSpacePressed   = false;

            if (!VoxelGame.Instance.Paused)
            {
                var keyboardState = Keyboard.GetState();

                walkingIsPressed = Mouse.GetState().MiddleButton == ButtonState.Pressed;
                if (walkingIsPressed && !_walkingWasPressed)
                {
                    Walking = !Walking;
                }

                isSpacePressed = keyboardState.IsKeyDown(Keys.Space);

                if (keyboardState.IsKeyDown(Keys.A))
                {
                    move.X -= 1;
                }
                if (keyboardState.IsKeyDown(Keys.D))
                {
                    move.X += 1;
                }
                if (keyboardState.IsKeyDown(Keys.S))
                {
                    move.Z -= 1;
                }
                if (keyboardState.IsKeyDown(Keys.W))
                {
                    move.Z += 1;
                }

                PlayerOrientation = PlayerOrientation.RotateYaw(mouseDelta.X * 0.0025f);
                PlayerOrientation = PlayerOrientation.RotatePitch(mouseDelta.Y * 0.0025f);
            }

            RenderManager.Instance.CameraForward = PlayerOrientation.Forward;

            if (Walking)
            {
                if (VoxelGame.Instance.Grid.saveInitializationPhase > 0 && VoxelGame.Instance.Grid.TileExists(PlayerPosition))
                {
                    if (move.LengthSquared() > 0)
                    {
                        move.Normalize();

                        PlayerPosition += (
                            PlayerOrientation.HorizontalForward * move.Z +
                            PlayerOrientation.HorizontalRight * move.X) * elapsed * 20;
                    }

                    // Gravity
                    _playerSpeed.Y -= 9.8f * elapsed;
                    PlayerPosition += new Vector3(0, _playerSpeed.Y * elapsed, 0);

                    var p0 = (PlayerPosition - new Vector3(0.4f, 0.4F, 0.4F)).GridPosition;
                    var q0 = (PlayerPosition + new Vector3(0.4f, 0.4F, 0.4F)).GridPosition;

                    var pos = new BlockPos(p0.X, int.MinValue, p0.Z);

                    for (int rz = p0.Z; rz <= q0.Z; rz++)
                    {
                        for (int rx = p0.X; rx <= q0.X; rx++)
                        {
                            int ry = VoxelGame.Instance.Grid.FindGround(new BlockPos(rx, q0.Y, rz));
                            if (ry > pos.Y)
                            {
                                pos = new BlockPos(rx, ry, rz);
                            }
                        }
                    }

                    var block = VoxelGame.Instance.Grid.GetBlock(pos);

                    float blockHeight = block.PhysicsMaterial.IsSolid ? block.PhysicsMaterial.Height : 0;

                    PlayerPositionTarget = EntityPosition.FromGrid(pos, new Vector3(0, blockHeight, 0));

                    var approach = elapsed / 0.25f;

                    var distance = PlayerPosition.RelativeTo(PlayerPositionTarget).Y;

                    if (distance < 0)
                    {
                        _playerSpeed.Y = 0;
                        if (isSpacePressed && !_wasSpacePressed)
                        {
                            PlayerPosition += new Vector3(0, -distance, 0);
                            _playerSpeed.Y  = 8;
                        }
                    }

                    if (distance < -1)
                    {
                        PlayerPosition += new Vector3(0, -distance, 0);
                    }
                    else if (distance > approach)
                    {
                        PlayerPosition += new Vector3(0, -approach, 0);
                    }
                    else if (distance < -approach)
                    {
                        PlayerPosition += new Vector3(0, approach, 0);
                    }
                    else
                    {
                        PlayerPosition += new Vector3(0, -distance, 0);
                    }
                }
            }
            else
            {
                if (move.LengthSquared() > 0)
                {
                    move.Normalize();

                    PlayerPosition += (
                        PlayerOrientation.Forward * move.Z +
                        PlayerOrientation.HorizontalRight * move.X) * elapsed * 25;
                }

                _playerSpeed = Vector3.Zero;
            }

            VoxelGame.Instance.Grid.SetPlayerPosition(PlayerPosition);
            PriorityScheduler.Instance.SetPlayerPosition(PlayerPosition);

            _walkingWasPressed = walkingIsPressed;
            _wasSpacePressed   = isSpacePressed;
        }
Exemple #29
0
 private static float Distance(EntityPosition newPosition, Tile tile)
 {
     return((tile.Centroid.RelativeTo(newPosition)).Length());
 }
Exemple #30
0
        internal void FindSpawnPosition()
        {
            using (Profiler.CurrentProfiler.Begin("Finding Spawn Position"))
            {
                int range = 100;
                int seekLimit = 256;
                int x, y, z;

                do
                {
                    var a = Random.NextDouble() * Math.PI * 2;

                    x = (int)(range * Math.Cos(a));
                    y = GenerationContext.WaterLevel;
                    z = (int)(range * Math.Sin(a));

                    var densityProvider = GenerationContext.DensityProvider;

                    if (densityProvider.Get(new Vector3I(x, y++, z)) < 0)
                    {
                        range += 5;
                        // try again
                        continue;
                    }

                    while (seekLimit-- > 0)
                    {
                        if (densityProvider.Get(new Vector3I(x, y++, z)) >= 0)
                        {
                            continue;
                        }
                        if (densityProvider.Get(new Vector3I(x, y++, z)) >= 0)
                        {
                            continue;
                        }
                        if (densityProvider.Get(new Vector3I(x, y++, z)) >= 0)
                        {
                            continue;
                        }
                        if (densityProvider.Get(new Vector3I(x, y++, z)) < 0)
                        {
                            break;
                        }
                    }

                    if (seekLimit <= 0)
                    {
                        break;
                    }

                    range += 5;
                    // try again
                } while (true);

                if (seekLimit <= 0)
                {
                    // TODO: Build spawn platform
                }

                SpawnPosition = EntityPosition.FromGrid(new BlockPos(x, y - 3, z));
            }
        }
        public override EntityPosition GetPosition(IDynamicEntity owner)
        {
            var pos = new EntityPosition();

            if (!AllowFreeMount && !owner.EntityState.IsBlockPicked)
            {
                return(pos);
            }

            if (!MountPoint.HasFlag(BlockFace.Top) && owner.EntityState.PickPointNormal.Y == 1)
            {
                return(pos);
            }

            if (!MountPoint.HasFlag(BlockFace.Bottom) && owner.EntityState.PickPointNormal.Y == -1)
            {
                return(pos);
            }

            if (!MountPoint.HasFlag(BlockFace.Sides) && (owner.EntityState.PickPointNormal.X != 0 || owner.EntityState.PickPointNormal.Z != 0))
            {
                return(pos);
            }

            if (BlockEmptyRequired && owner.EntityState.IsBlockPicked)
            {
                //Get the chunk where the entity will be added and check if another entity is not present at the destination root block !
                var workingchunk = LandscapeManager.GetChunkFromBlock(owner.EntityState.PickedBlockPosition);

                if (workingchunk == null)
                {
                    return(pos);
                }

                foreach (var entity in workingchunk.Entities.OfType <BlockLinkedItem>().Where(x => x.Linked && x.LinkedCube == owner.EntityState.PickedBlockPosition))
                {
                    if (entity.BlockLocationRoot == owner.EntityState.NewBlockPosition && entity.LinkedCube == owner.EntityState.PickedBlockPosition)
                    {
                        //CubePlaced Entity already present at this location
                        return(pos);
                    }
                }
            }

            // locate the entity
            if (owner.EntityState.PickPointNormal.Y == 1) // = Put on TOP
            {
                if (BlockFaceCentered)
                {
                    var newBlockPos = owner.EntityState.IsBlockPicked ? owner.EntityState.NewBlockPosition : owner.EntityState.PickPoint.ToCubePosition();
                    pos.Position = new Vector3D(
                        newBlockPos + new Vector3(0.5f - (float)owner.EntityState.PickPointNormal.X / 2,
                                                  owner.EntityState.PickPoint.Y % 1,
                                                  0.5f - (float)owner.EntityState.PickPointNormal.Z / 2)
                        );
                }
                else
                {
                    pos.Position = new Vector3D(owner.EntityState.PickPoint);
                }
            }
            else if (owner.EntityState.PickPointNormal.Y == -1) //PUT on cube Bottom = (Ceiling)
            {
                pos.Position    = new Vector3D(owner.EntityState.PickPoint);
                pos.Position.Y -= DefaultSize.Y;
            }
            else //Put on a side
            {
                if (BlockFaceCentered)
                {
                    var newBlockPos = owner.EntityState.IsBlockPicked ? owner.EntityState.NewBlockPosition : owner.EntityState.PickPoint.ToCubePosition();
                    pos.Position = new Vector3D(
                        newBlockPos + new Vector3(0.5f - (float)owner.EntityState.PickPointNormal.X / 2,
                                                  0.5f,
                                                  0.5f - (float)owner.EntityState.PickPointNormal.Z / 2)
                        );
                }
                else
                {
                    pos.Position = new Vector3D(owner.EntityState.PickPoint);
                }

                pos.Position += new Vector3D(owner.EntityState.PickPointNormal.X == -1 ? -0.01 : 0,
                                             0,
                                             owner.EntityState.PickPointNormal.Z == -1 ? -0.01 : 0);


                var slope = 0d;

                if (owner.EntityState.PickPointNormal.X == -1)
                {
                    slope = -Math.PI / 2;
                }
                if (owner.EntityState.PickPointNormal.X == 1)
                {
                    slope = Math.PI / 2;                                             // ok
                }
                if (owner.EntityState.PickPointNormal.Z == -1)
                {
                    slope = Math.PI;                                             // ok
                }
                if (owner.EntityState.PickPointNormal.Z == 1)
                {
                    slope = 0;
                }

                pos.Rotation = Quaternion.RotationAxis(new Vector3(0, 1, 0), (float)slope);
            }

            pos.Valid = true;

            return(pos);
        }