internal WorldSelection(ControlBase parent, IWorldProvider worldProvider, Context context) : base( parent, context) { this.worldProvider = worldProvider; CreateContent(); }
public WrappedCachedWorldProvider(OpenApi api, IWorldProvider worldProvider) : base(api, worldProvider) { if (worldProvider is ICachingWorldProvider) { CachingWorldProvider = (ICachingWorldProvider)worldProvider; } }
public static List <Tile> BezierPath(Point[] points, IWorldProvider world) { var result = new List <Tile>(); HashSet <Point> foundPoints = new HashSet <Point>(); for (int i = 0; i < points.Length - 3; i++) { for (int j = 0; j < 100; j++) { float t = j / 100f; var p = GetPointOnBezierCurve(points[i].ToVector2(), points[i + 1].ToVector2(), points[i + 2].ToVector2(), points[i + 3].ToVector2(), t); foundPoints.Add(p); } } var foundPointslist = foundPoints.ToList(); for (int i = 0; i < foundPointslist.Count - 1; i++) { result.AddRange(PlotLineAA(foundPointslist[i], foundPointslist[i + 1], world)); } return(result); }
private void FillcharacterBuffersWithWorld(Screen screen, ConsoleCamera camera, GameSettings settings, IWorldProvider world) { int camX = camera.getPosition().X; int camY = camera.getPosition().Y; if (angle > 360) { angle = 0; } angle += step; for (int x = camX; x < settings.GetWidthZoomed() + camX; x++) { for (int y = camY; y < settings.GetHeightZoomed() + camY; y++) { Point screenPoint = camera.PointToScreen(x, y); if (screen.ScreenBuffer[screenPoint.Y, screenPoint.X].isVisible) { Tile tileToDraw = world.GetTile(x, y); GetTerrainTile(screen, TerrainLibrary.Terrains[tileToDraw.Terrain], screenPoint); } else { screen.ScreenBuffer[screenPoint.Y, screenPoint.X].Char = ' '; screen.ScreenBuffer[screenPoint.Y, screenPoint.X].BackGroundColor = new Color(); } } } }
public void Close() { _levelTicker.Change(Timeout.Infinite, Timeout.Infinite); WaitHandle waitHandle = new AutoResetEvent(false); _levelTicker.Dispose(waitHandle); WaitHandle.WaitAll(new[] { waitHandle }, TimeSpan.FromMinutes(2)); _levelTicker = null; foreach (var entity in Entities.Values.ToArray()) { entity.DespawnEntity(); } Entities.Clear(); foreach (Player player in Players.Values.ToArray()) { player.Disconnect("Unexpected player lingering on close of level: " + player.Username); } Players.Clear(); BlockEntities.Clear(); BlockWithTicks.Clear(); BlockWithTicks = null; BlockEntities = null; Players = null; Entities = null; _worldProvider = null; Log.Info("Closed level: " + LevelId); }
public OpenLevel(OpenApi openApi, OpenLevelManager levelManager, string levelId, IWorldProvider worldProvider, EntityManager entityManager, GameMode gameMode = GameMode.Survival, Difficulty difficulty = Difficulty.Normal, int viewDistance = 11) : base(levelManager, levelId, (worldProvider is ICachingWorldProvider) ? new WrappedCachedWorldProvider(openApi, worldProvider) : new WrappedWorldProvider(openApi, worldProvider), entityManager, gameMode, difficulty, viewDistance) { OpenAPI = openApi; CancelationToken = new CancellationTokenSource(); TickScheduler = new TickScheduler(); EventDispatcher = new EventDispatcher(openApi, OpenAPI.EventDispatcher); if (WorldProvider is WrappedWorldProvider wrapped) { wrapped.Level = this; } }
//public List<Gadget> Gadgets = new List<Gadget>(); //public ChestInfo Chest { get; set; } public xCoreLevelLobby(string levelId, IWorldProvider worldProvider, EntityManager entitymanager, xCoreGames core) : base(null, levelId, worldProvider, entitymanager) { Core = core; AllowBreak = false; AllowBuild = false; CurrentWorldTime = 6000; IsWorldTimeStarted = false; }
public IWorld AddWorld(IWorldProvider provider) { var id = GetFreeID(); IWorld world = null; world.SetID(id); worlds[id] = world; return(world); }
public override void Update(long gameTime, NamelessGame namelessGame) { IEntity worldEntity = namelessGame.TimelineEntity; IWorldProvider worldProvider = null; if (worldEntity != null) { worldProvider = worldEntity.GetComponentOfType <TimeLine>().CurrentTimelineLayer.Chunks; while (namelessGame.Commander.DequeueCommand(out DropItemCommand dropCommand)) { var tile = worldProvider.GetTile(dropCommand.WhereToDrop.X, dropCommand.WhereToDrop.Y); foreach (var dropCommandItem in dropCommand.Items) { tile.AddEntity((Entity)dropCommandItem); dropCommand.Holder.Items.Remove(dropCommandItem); dropCommandItem.GetComponentOfType <Drawable>().Visible = true; var position = dropCommandItem.GetComponentOfType <Position>(); position.Point = new Point(dropCommand.WhereToDrop.X, dropCommand.WhereToDrop.Y); } } while (namelessGame.Commander.DequeueCommand(out PickUpItemCommand pickupCommand)) { if (pickupCommand != null) { foreach (var pickupCommandItem in pickupCommand.Items) { var tile = worldProvider.GetTile(pickupCommand.WhereToPickUp.X, pickupCommand.WhereToPickUp.Y); tile.RemoveEntity((Entity)pickupCommandItem); pickupCommandItem.GetComponentOfType <Drawable>().Visible = false; var ammo = pickupCommandItem.GetComponentOfType <Ammo>(); if (ammo != null) { var itemsEntities = pickupCommand.Holder.Items; var itemsWithAmmo = itemsEntities.Select(x => x).Where(i => i.GetComponentOfType <Ammo>() != null); var sameTypeItem = itemsWithAmmo.FirstOrDefault(x => x.GetComponentOfType <Ammo>().Type.Name == ammo.Type.Name); if (sameTypeItem != null) { sameTypeItem.GetComponentOfType <Item>().Amount += pickupCommandItem.GetComponentOfType <Item>().Amount; namelessGame.RemoveEntity(pickupCommandItem); } else { pickupCommand.Holder.Items.Add(pickupCommandItem); } } else { pickupCommand.Holder.Items.Add(pickupCommandItem); } } } } } }
/// <summary> /// Creates a new start user interface. /// </summary> /// <param name="window">The game window.</param> /// <param name="inputListener">The input listener.</param> /// <param name="worldProvider">The world provider.</param> /// <param name="settingsProviders">The settings provider.</param> /// <param name="drawBackground">Whether to draw the ui background.</param> public StartUserInterface(GameWindow window, InputListener inputListener, IWorldProvider worldProvider, List <ISettingsProvider> settingsProviders, bool drawBackground) : base( window, inputListener, drawBackground) { this.worldProvider = worldProvider; this.settingsProviders = settingsProviders; }
public override void Update(long gameTime, NamelessGame namelessGame) { var playerEntity = namelessGame.PlayerEntity; var ap = playerEntity.GetComponentOfType <ActionPoints>(); if (ap.Points >= 100) { return; } IEntity worldEntity = namelessGame.TimelineEntity; IWorldProvider worldProvider = null; if (worldEntity != null) { worldProvider = worldEntity.GetComponentOfType <TimeLine>().CurrentTimelineLayer.Chunks; } if (worldProvider != null) { foreach (IEntity entity in this.RegisteredEntities) { AIControlled ac = entity.GetComponentOfType <AIControlled>(); Dead dead = entity.GetComponentOfType <Dead>(); var actionPoints = entity.GetComponentOfType <ActionPoints>(); if (dead == null && actionPoints.Points >= 100) { BasicAi basicAi = entity.GetComponentOfType <BasicAi>(); Position playerPosition = namelessGame.PlayerEntity .GetComponentOfType <Position>(); switch (basicAi.State) { case BasicAiStates.Idle: case BasicAiStates.Moving: var pPos = playerPosition.Point.ToVector2(); MoveTo(entity, namelessGame, playerPosition.Point, true); var route = basicAi.Route; if (route.Count == 0) { basicAi.State = (BasicAiStates.Idle); } break; case BasicAiStates.Attacking: break; default: break; } } } } }
public void Initialize(IWorldProvider worldProvider) { Process blocker; { // Block port! var startInfo = new ProcessStartInfo("MiNET.Console.exe", "listener"); startInfo.CreateNoWindow = false; startInfo.WindowStyle = ProcessWindowStyle.Normal; startInfo.UseShellExecute = false; blocker = Process.Start(startInfo); } { var startInfo = new ProcessStartInfo(Path.Combine(Config.GetProperty("BDSPath", null), Config.GetProperty("BDSExe", null))); startInfo.WorkingDirectory = Config.GetProperty("BDSPath", null); startInfo.CreateNoWindow = false; startInfo.WindowStyle = ProcessWindowStyle.Normal; startInfo.UseShellExecute = false; startInfo.RedirectStandardInput = true; _bedrock = Process.Start(startInfo); _client = new MiNetClient(new IPEndPoint(IPAddress.Parse("192.168.10.178"), 19162), "TheGrey", new DedicatedThreadPool(new DedicatedThreadPoolSettings(Environment.ProcessorCount))); _client.MessageHandler = new ChunkGeneratorHandler(_client, worldProvider); //_client.UseBlobCache = true; _client.StartClient(); if (_client.ServerEndPoint != null) { while (!_client.FoundServer) { _client.SendUnconnectedPing(); Thread.Sleep(100); } } } Log.Info("Found server, waiting for spawn"); Task.Run(BotHelpers.DoWaitForSpawn(_client)).Wait(); Log.Info("Spawned on bedrock server"); blocker?.Kill(); // no need to block further once we have spawned our bot. // Shutdown hook. Must use to flush in memory log of LevelDB. AppDomain.CurrentDomain.ProcessExit += (sender, args) => { Log.Warn("Closing bedrock dedicated server (BDS)"); _bedrock.StandardInput.WriteLine("stop"); _bedrock.WaitForExit(1000); _bedrock.Kill(); }; }
public static List <Tile> PlotLineAA(Point point0, Point point1, IWorldProvider world) { var result = new List <Tile>(); int dx = Math.Abs(point1.X - point0.X), sx = point0.X < point1.X ? 1 : -1; int dy = Math.Abs(point1.Y - point0.Y), sy = point0.Y < point1.Y ? 1 : -1; int err = dx - dy, e2, x2; /* error value e_xy */ int ed = (int)(dx + dy == 0 ? 1 : Math.Sqrt((float)dx * dx + (float)dy * dy)); for (;;) { /* pixel loop */ //setPixelAA(point0.X, point0.Y, 255 * abs(err - dx + dy) / ed); result.Add(world.GetTile(point0.X, point0.Y)); e2 = err; x2 = point0.X; if (2 * e2 >= -dx) { /* x step */ if (point0.X == point1.X) { break; } if (e2 + dy < ed) { result.Add(world.GetTile(point0.X, point0.Y + sy)); // setPixelAA(point0.X, point0.Y + sy, 255 * (e2 + dy) / ed); } err -= dy; point0.X += sx; } if (2 * e2 <= dy) { /* y step */ if (point0.Y == point1.Y) { break; } if (dx - e2 < ed) { result.Add(world.GetTile(x2 + sx, point0.Y + sy)); // setPixelAA(x2 + sx, point0.Y, 255 * (dx - e2) / ed); } err += dx; point0.Y += sy; } } return(result); }
public MainGame( ILogger logger, ClientStartParameters clientStartParameters, IOptions <GraphicsSettings> graphicsSettings, INetworkClient networkClient, IWindowProvider windowProvider, IWorldProvider worldProvider, IWorldRenderer worldRenderer, IContext context) { _logger = logger; _clientStartParameters = clientStartParameters; _graphicsSettings = graphicsSettings; FNALoggerEXT.LogError = message => _logger.Error("FNA: {@Message}", message); FNALoggerEXT.LogInfo = message => _logger.Information("FNA: {@Message}", message); FNALoggerEXT.LogWarn = message => _logger.Warning("FNA: {@Message}", message); _networkClient = networkClient; _networkClient.Connected += NetworkClientConnected; _networkClient.Disconnected += NetworkClientDisconnected; _networkClient.ChunkReceived += NetworkClientChunkReceived; _windowProvider = windowProvider; _context = context; _windowProvider.Load(); _ftc = new FrameTimeCalculator(this); _worldProvider = worldProvider; _worldRenderer = worldRenderer; Content.RootDirectory = nameof(Content); Window.Title = "UO-Studio"; Window.AllowUserResizing = true; Activated += WindowActivated; Deactivated += WindowDeactivated; _ = new GraphicsDeviceManager(this) { PreferredBackBufferWidth = graphicsSettings.Value.ResolutionWidth, PreferredBackBufferHeight = graphicsSettings.Value.ResolutionHeight, PreferMultiSampling = graphicsSettings.Value.IsMultiSamplingEnabled, GraphicsProfile = GraphicsProfile.HiDef, SynchronizeWithVerticalRetrace = graphicsSettings.Value.IsVsyncEnabled }; _camera = new Camera(graphicsSettings.Value.ResolutionWidth, graphicsSettings.Value.ResolutionHeight) { Mode = CameraMode.Perspective }; IsMouseVisible = true; IsFixedTimeStep = false; }
public override void Update(long gameTime, NamelessGame game) { this.gameTime = gameTime; game.GraphicsDevice.BlendState = BlendState.AlphaBlend; game.GraphicsDevice.SamplerStates[0] = sampler; game.GraphicsDevice.DepthStencilState = DepthStencilState.Default; //todo move to constructor or some other place better suited for initialization if (tileAtlas == null) { InitializeTexture(game); } IEntity worldEntity = game.TimelineEntity; IWorldProvider worldProvider = null; if (worldEntity != null) { worldProvider = worldEntity.GetComponentOfType <TimeLine>().CurrentTimelineLayer.Chunks; } var entity = game.CameraEntity; ConsoleCamera camera = entity.GetComponentOfType <ConsoleCamera>(); Screen screen = entity.GetComponentOfType <Screen>(); Commander commander = game.Commander; screen = UpdateZoom(game, commander, entity, screen, out bool zoomUpdate); if (foregroundModel == null || zoomUpdate) { foregroundModel = new TileModel(screen.Height, screen.Width); } if (backgroundModel == null || zoomUpdate) { backgroundModel = new TileModel(screen.Height, screen.Width); } if (camera != null && screen != null && worldProvider != null) { MoveCamera(game, camera); FillcharacterBufferVisibility(game, screen, camera, game.GetSettings(), worldProvider); FillcharacterBuffersWithWorld(screen, camera, game.GetSettings(), worldProvider); FillcharacterBuffersWithTileObjects(screen, camera, game.GetSettings(), game, worldProvider); FillcharacterBuffersWithWorldObjects(screen, camera, game.GetSettings(), game); RenderScreen(game, screen, game.GetSettings()); } }
private void FillcharacterBufferVisibility(NamelessGame game, Screen screen, ConsoleCamera camera, GameSettings settings, IWorldProvider world) { int camX = camera.getPosition().X; int camY = camera.getPosition().Y; Position playerPosition = game.PlayerEntity.GetComponentOfType <Position>(); BoundingBox b = new BoundingBox(camera.getPosition(), new Point(settings.GetWidthZoomed() + camX, settings.GetHeightZoomed() + camY)); for (int x = 0; x < settings.GetWidthZoomed(); x++) { for (int y = 0; y < settings.GetHeightZoomed(); y++) { screen.ScreenBuffer[x, y].isVisible = false; } } //return; if (fov == null) { { fov = new PermissiveVisibility((x, y) => { return(!world.GetTile(x, y).GetBlocksVision(game)); }, (x, y) => { Stopwatch s = Stopwatch.StartNew(); var lambdaLocalScreen = game.CameraEntity.GetComponentOfType <Screen>(); s.Stop(); s.ToString(); Point screenPoint = camera.PointToScreen(x, y); if (screenPoint.X >= 0 && screenPoint.X < settings.GetWidthZoomed() && screenPoint.Y >= 0 && screenPoint.Y < settings.GetHeightZoomed()) { lambdaLocalScreen.ScreenBuffer[screenPoint.X, screenPoint.Y].isVisible = true; } }, (x, y) => { if (Math.Abs(x) > 60 || Math.Abs(y) > 60) { return(10000); } // return (int)((x*x) + (y*y)); return(Math.Abs(x) + Math.Abs(y)); } ); } } fov.Compute(playerPosition.Point, 60); }
public xCoreLevel(IWorldProvider worldProvider, EntityManager entitymanager, xCoreInterface game, MapInfo map, int id) : base(null, game.NameGame + id, worldProvider, entitymanager, GameMode.Survival, (Difficulty)2, 7) { Game = game; Id = id; Status = Status.Start; Time = xCoreGames.StartTime; Map = map; Slots = map.Slots; CurrentWorldTime = 6000; IsWorldTimeStarted = false; BlockBreak += game.BlockBreak; BlockPlace += game.BlockPlace; WorldTick += GameTimer; }
public static IEntity CreateDummyBuilding(int x, int y, int width ,int height, NamelessGame namelessGame) { IEntity worldEntity = namelessGame.TimelineEntity; IWorldProvider worldProvider = null; if (worldEntity != null) { worldProvider = worldEntity.GetComponentOfType<TimeLine>().CurrentTimelineLayer.Chunks; } IEntity building = new Entity(); building.AddComponent(new Description("","")); building.AddComponent(new Position(x,y)); Building buildingComponent = new Building(); for (int i = 0;i< width; i++) { for (int j = 0;j< height; j++) { var tile = worldProvider.GetTile(x + i, y + j); tile.Terrain = TerrainTypes.Road; tile.Biome = Biomes.None; if (i == 0 || j == 0 || i == width - 1 || j == height - 1) { if (i == width / 2) { IEntity door = CreateDoor(x + i, y + j); buildingComponent.getBuildingParts().Add(door); namelessGame.AddEntity(door); tile.AddEntity((Entity) door); } else { var wall = TerrainFurnitureFactory.WallEntity; tile.AddEntity(wall); namelessGame.AddEntity(wall); } } } } building.AddComponent(buildingComponent); return building; }
public Level(string levelId, IWorldProvider worldProvider, EntityManager entityManager, GameMode gameMode = GameMode.Survival, Difficulty difficulty = Difficulty.Normal, int viewDistance = 11) { Random = new Random(); EntityManager = entityManager; InventoryManager = new InventoryManager(this); SpawnPoint = null; Players = new ConcurrentDictionary <long, Player>(); Entities = new ConcurrentDictionary <long, Entity>(); BlockEntities = new List <BlockEntity>(); BlockWithTicks = new ConcurrentDictionary <BlockCoordinates, long>(); LevelId = levelId; GameMode = gameMode; Difficulty = difficulty; ViewDistance = viewDistance; _worldProvider = worldProvider; }
public void Close() { //_levelTicker.Change(Timeout.Infinite, Timeout.Infinite); //WaitHandle waitHandle = new AutoResetEvent(false); //_levelTicker.Dispose(waitHandle); //WaitHandle.WaitAll(new[] {waitHandle}, TimeSpan.FromMinutes(2)); //_levelTicker = null; _tickerHighPrecisionTimer.Dispose(); foreach (var entity in Entities.Values.ToArray()) { entity.DespawnEntity(); } Entities.Clear(); foreach (Player player in Players.Values.ToArray()) { player.Disconnect("Unexpected player lingering on close of level: " + player.Username); } Players.Clear(); BlockEntities.Clear(); BlockWithTicks.Clear(); BlockWithTicks = null; BlockEntities = null; Players = null; Entities = null; AnvilWorldProvider provider = _worldProvider as AnvilWorldProvider; if (provider != null) { foreach (var chunk in provider._chunkCache) { chunk.Value?.ClearCache(); } } _worldProvider = null; Log.Info("Closed level: " + LevelId); }
public virtual Level GetLevel(Player player, string name) { Level level = Levels.FirstOrDefault(l => l.LevelId.Equals(name, StringComparison.InvariantCultureIgnoreCase)); if (level == null) { GameMode gameMode = Config.GetProperty("GameMode", GameMode.Survival); Difficulty difficulty = Config.GetProperty("Difficulty", Difficulty.Peaceful); int viewDistance = Config.GetProperty("ViewDistance", 250); IWorldProvider worldProvider = null; switch (Config.GetProperty("WorldProvider", "flat").ToLower().Trim()) { case "flat": case "flatland": worldProvider = new FlatlandWorldProvider(); break; case "cool": worldProvider = new CoolWorldProvider(); break; case "experimental": worldProvider = new ExperimentalWorldProvider(); break; case "anvil": worldProvider = new AnvilWorldProvider(); break; default: worldProvider = new FlatlandWorldProvider(); break; } level = new Level(name, worldProvider, gameMode, difficulty, viewDistance); level.Initialize(); Levels.Add(level); OnLevelCreated(new LevelEventArgs(null, level)); } return(level); }
public virtual Level CreateLevel(string name, IWorldProvider provider) { GameMode gameMode = Config.GetProperty("GameMode", GameMode.Survival); Difficulty difficulty = Config.GetProperty("Difficulty", Difficulty.Peaceful); int viewDistance = Config.GetProperty("ViewDistance", 11); IWorldProvider worldProvider = null; worldProvider = provider ?? new FlatlandWorldProvider(); var level = new Level(name, worldProvider, EntityManager, gameMode, difficulty, viewDistance); level.Initialize(); OnLevelCreated(new LevelEventArgs(null, level)); return(level); }
public Level(string levelId, IWorldProvider worldProvider = null) { Random = new Random(); EntityManager = new EntityManager(); InventoryManager = new InventoryManager(this); SpawnPoint = new PlayerLocation(50, 4000, 50); Players = new ConcurrentDictionary <long, Player>(); Entities = new ConcurrentDictionary <long, Entity>(); BlockEntities = new List <BlockEntity>(); BlockWithTicks = new ConcurrentDictionary <BlockCoordinates, long>(); LevelId = levelId; GameMode = Config.GetProperty("GameMode", GameMode.Survival); Difficulty = Config.GetProperty("Difficulty", Difficulty.Peaceful); ViewDistance = Config.GetProperty("ViewDistance", 250); _worldProvider = worldProvider; if (_worldProvider == null) { switch (Config.GetProperty("WorldProvider", "flat").ToLower().Trim()) { case "flat": case "flatland": _worldProvider = new FlatlandWorldProvider(); break; case "cool": _worldProvider = new CoolWorldProvider(); break; case "experimental": _worldProvider = new ExperimentalWorldProvider(); break; case "anvil": _worldProvider = new AnvilWorldProvider(); break; default: _worldProvider = new FlatlandWorldProvider(); break; } } }
public override void Update(long gameTime, NamelessGame game) { this.gameTime = gameTime; //todo move to constructor or some other place better suited for initialization if (tileAtlas == null) { InitializeTexture(game); _spriteBatch = new SpriteBatch(game.GraphicsDevice); } Commander commander = game.Commander; var entity = game.CameraEntity; ConsoleCamera camera = entity.GetComponentOfType <ConsoleCamera>(); Screen screen = entity.GetComponentOfType <Screen>(); screen = UpdateZoom(game, commander, entity, screen); _spriteBatch.Begin(SpriteSortMode.Deferred, null, null, DepthStencilState.None); IEntity worldEntity = game.TimelineEntity; IWorldProvider worldProvider = null; if (worldEntity != null) { worldProvider = worldEntity.GetComponentOfType <TimeLine>().CurrentTimelineLayer.Chunks; } if (camera != null && screen != null && worldProvider != null) { MoveCamera(game, camera); FillcharacterBufferVisibility(game, screen, camera, game.GetSettings(), worldProvider); FillcharacterBuffersWithWorld(screen, camera, game.GetSettings(), worldProvider); FillcharacterBuffersWithTileObjects(screen, camera, game.GetSettings(), game, worldProvider); FillcharacterBuffersWithWorldObjects(screen, camera, game.GetSettings(), game); RenderScreen(game, screen, game.GetSettings()); } _spriteBatch.End(); }
public virtual Level CreateLevel(string name, IWorldProvider provider) { GameMode gameMode = Config.GetProperty("GameMode", GameMode.Survival); Difficulty difficulty = Config.GetProperty("Difficulty", Difficulty.Peaceful); int viewDistance = Config.GetProperty("ViewDistance", 11); IWorldProvider worldProvider = null; worldProvider = provider ?? new AnvilWorldProvider { MissingChunkProvider = new SuperflatGenerator(Dimension.Overworld) }; var level = new Level(this, name, worldProvider, EntityManager, gameMode, difficulty, viewDistance); level.Initialize(); OnLevelCreated(new LevelCancelEventArgs(null, level)); return(level); }
public override void Update(long gameTime, NamelessGame namelessGame) { while (namelessGame.Commander.DequeueCommand(out DeathCommand command)) { IEntity entityToKill = command.getToKill(); entityToKill.AddComponent(new Dead()); Drawable drawable = entityToKill.GetComponentOfType <Drawable>(); if (drawable != null) { drawable.Representation = '%'; } IEntity worldEntity = namelessGame.TimelineEntity; IWorldProvider worldProvider = null; if (worldEntity != null) { worldProvider = worldEntity.GetComponentOfType <TimeLine>().CurrentTimelineLayer.Chunks; } Position position = entityToKill.GetComponentOfType <Position>(); OccupiesTile occupiesTile = entityToKill.GetComponentOfType <OccupiesTile>(); if (occupiesTile != null && position != null) { Tile tile = worldProvider.GetTile(position.Point.Y, position.Point.X); tile.RemoveEntity((Entity)entityToKill); } entityToKill.RemoveComponentOfType <OccupiesTile>(); Description d = entityToKill.GetComponentOfType <Description>(); if (d != null) { // namelessGame.WriteLineToConsole(d.Name + " is dead!"); } } }
private static TimelineLayer InitialiseFirstBoard(NamelessGame game, HistoryGenerationSettings settings) { var worldBoard = new TimelineLayer(game.WorldSettings.WorldBoardWidth, game.WorldSettings.WorldBoardWidth, 0); ChunkData chunkData = new ChunkData(game.WorldSettings, worldBoard); worldBoard.Chunks = chunkData; WorldBoardGenerator.PopulateWithInitialData(worldBoard, game); WorldBoardGenerator.AnalizeLandmasses(worldBoard, game); WorldBoardGenerator.PlaceInitialCivilizations(worldBoard, game); //WorldBoardGenerator.PlaceInitialArtifacts(worldBoard, game); //WorldBoardGenerator.PlaceResources(worldBoard, game); //WorldBoardGenerator.DistributeMetaphysics(worldBoard, game); WorldTile firsTile = null; foreach (var worldBoardWorldTile in worldBoard.WorldTiles) { if (worldBoardWorldTile.Settlement != null) { IWorldProvider worldProvider = chunkData; firsTile = worldBoardWorldTile; var concreteSettlment = SettlementFactory.GenerateSettlement(game, firsTile, worldBoard, worldProvider); firsTile.Settlement.Concrete = concreteSettlment; break; } } //var concreteSettlment = SettlementFactory.GenerateSettlement(game, firsTile, worldBoard, worldProvider); //firsTile.Settlement.Concrete = concreteSettlment; return(worldBoard); }
private void FillcharacterBufferVisibility(NamelessGame game, Screen screen, ConsoleCamera camera, GameSettings settings, IWorldProvider world) { int camX = camera.getPosition().X; int camY = camera.getPosition().Y; Position playerPosition = game.PlayerEntity.GetComponentOfType <Position>(); BoundingBox b = new BoundingBox(camera.getPosition(), new Point(settings.GetWidthZoomed() + camX, settings.GetHeightZoomed() + camY)); for (int x = 0; x < settings.GetWidthZoomed(); x++) { for (int y = 0; y < settings.GetHeightZoomed(); y++) { screen.ScreenBuffer[y, x].isVisible = true; } } return; if (fov == null) { fov = new PermissiveVisibility((x, y) => { return(!world.GetTile(x, y).GetBlocksVision(game)); }, (x, y) => { Point screenPoint = camera.PointToScreen(x, y); if (screenPoint.X >= 0 && screenPoint.X < settings.GetWidth() && screenPoint.Y >= 0 && screenPoint.Y < settings.GetHeight()) { screen.ScreenBuffer[screenPoint.X, screenPoint.Y].isVisible = true; } }, (x, y) => { return(Math.Abs(x) + Math.Abs(y)); } ); } fov.Compute(playerPosition.Point, 60); }
private void FillcharacterBuffersWithTileObjects(Screen screen, ConsoleCamera camera, GameSettings settings, NamelessGame game, IWorldProvider world) { int camX = camera.getPosition().X; int camY = camera.getPosition().Y; if (angle > 360) { angle = 0; } angle += step; for (int x = camX; x < settings.GetWidthZoomed() + camX; x++) { for (int y = camY; y < settings.GetHeightZoomed() + camY; y++) { Point screenPoint = camera.PointToScreen(x, y); if (screen.ScreenBuffer[screenPoint.Y, screenPoint.X].isVisible) { Tile tileToDraw = world.GetTile(x, y); foreach (var entity in tileToDraw.GetEntities()) { var furniture = entity.GetComponentOfType <Furniture>(); var drawable = entity.GetComponentOfType <Drawable>(); if (furniture != null && drawable != null) { screen.ScreenBuffer[screenPoint.Y, screenPoint.X].Char = drawable.Representation; screen.ScreenBuffer[screenPoint.Y, screenPoint.X].CharColor = drawable.CharColor; } } } } } }
public MobHuntLevel(string levelId, IWorldProvider worldProvider = null) : base(levelId, worldProvider) { }
public SkyLightBlockAccess(IWorldProvider worldProvider, ChunkColumn chunk) { _worldProvider = worldProvider; _chunk = chunk; _coord = new ChunkCoordinates(chunk.x, chunk.z); }
public static ChunkColumn GetChunk(ChunkCoordinates coordinates, string basePath, IWorldProvider generator, int yoffset) { int width = 32; int depth = 32; int rx = coordinates.X >> 5; int rz = coordinates.Z >> 5; string filePath = Path.Combine(basePath, string.Format(@"region\r.{0}.{1}.mca", rx, rz)); if (!File.Exists(filePath)) return generator.GenerateChunkColumn(coordinates); using (var regionFile = File.OpenRead(filePath)) { byte[] buffer = new byte[8192]; regionFile.Read(buffer, 0, 8192); int xi = (coordinates.X%width); if (xi < 0) xi += 32; int zi = (coordinates.Z%depth); if (zi < 0) zi += 32; int tableOffset = (xi + zi*width)*4; regionFile.Seek(tableOffset, SeekOrigin.Begin); byte[] offsetBuffer = new byte[4]; regionFile.Read(offsetBuffer, 0, 3); Array.Reverse(offsetBuffer); int offset = BitConverter.ToInt32(offsetBuffer, 0) << 4; int length = regionFile.ReadByte(); if (offset == 0 || length == 0) { return generator.GenerateChunkColumn(coordinates); } regionFile.Seek(offset, SeekOrigin.Begin); byte[] waste = new byte[4]; regionFile.Read(waste, 0, 4); int compressionMode = regionFile.ReadByte(); var nbt = new NbtFile(); nbt.LoadFromStream(regionFile, NbtCompression.ZLib); NbtTag dataTag = nbt.RootTag["Level"]; NbtList sections = dataTag["Sections"] as NbtList; ChunkColumn chunk = new ChunkColumn { x = coordinates.X, z = coordinates.Z, biomeId = dataTag["Biomes"].ByteArrayValue }; for (int i = 0; i < chunk.biomeId.Length; i++) { if (chunk.biomeId[i] > 22) chunk.biomeId[i] = 0; } if (chunk.biomeId.Length > 256) throw new Exception(); // This will turn into a full chunk column foreach (NbtTag sectionTag in sections) { int sy = sectionTag["Y"].ByteValue*16; byte[] blocks = sectionTag["Blocks"].ByteArrayValue; byte[] data = sectionTag["Data"].ByteArrayValue; NbtTag addTag = sectionTag["Add"]; byte[] adddata = new byte[2048]; if (addTag != null) adddata = addTag.ByteArrayValue; byte[] blockLight = sectionTag["BlockLight"].ByteArrayValue; byte[] skyLight = sectionTag["SkyLight"].ByteArrayValue; for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { for (int y = 0; y < 16; y++) { int yi = sy + y - yoffset; if (yi < 0 || yi >= 128) continue; int anvilIndex = y*16*16 + z*16 + x; int blockId = blocks[anvilIndex] + (Nibble4(adddata, anvilIndex) << 8); // Anvil to PE friendly converstion if (blockId == 125) blockId = 5; else if (blockId == 126) blockId = 158; else if (blockId == 75) blockId = 50; else if (blockId == 76) blockId = 50; else if (blockId == 123) blockId = 89; else if (blockId == 124) blockId = 89; else if (blockId == 152) blockId = 73; else if (_ignore.BinarySearch(blockId) >= 0) blockId = 0; else if (_gaps.BinarySearch(blockId) >= 0) { Debug.WriteLine("Missing material: " + blockId); blockId = 133; } if (blockId > 255) blockId = 41; if (yi == 127 && blockId != 0) blockId = 30; if (yi == 0 && (blockId == 8 || blockId == 9 /*|| blockId == 0*/)) blockId = 7; //if (blockId != 0) blockId = 41; chunk.SetBlock(x, yi, z, (byte) blockId); chunk.SetMetadata(x, yi, z, Nibble4(data, anvilIndex)); chunk.SetBlocklight(x, yi, z, Nibble4(blockLight, anvilIndex)); chunk.SetSkylight(x, yi, z, Nibble4(skyLight, anvilIndex)); } } } } NbtList entities = dataTag["Entities"] as NbtList; NbtList blockEntities = dataTag["TileEntities"] as NbtList; if (blockEntities != null) { foreach (var nbtTag in blockEntities) { var blockEntityTag = (NbtCompound) nbtTag; string entityId = blockEntityTag["id"].StringValue; int x = blockEntityTag["x"].IntValue; int y = blockEntityTag["y"].IntValue - yoffset; int z = blockEntityTag["z"].IntValue; blockEntityTag["y"] = new NbtInt("y", y); BlockEntity blockEntity = BlockEntityFactory.GetBlockEntityById(entityId); if (blockEntity != null) { blockEntityTag.Name = string.Empty; chunk.SetBlockEntity(new BlockCoordinates(x, y, z), blockEntityTag); } } } NbtList tileTicks = dataTag["TileTicks"] as NbtList; chunk.isDirty = false; return chunk; } }