Ejemplo n.º 1
0
        /// <summary>
        /// Creates an instance of a <see cref="Region"/> for the given region file.
        /// </summary>
        /// <param name="rm">The <see cref="RegionManager"/> that should be managing this region.</param>
        /// <param name="cache">A shared cache for holding chunks.</param>
        /// <param name="filename">The region file to derive the region from.</param>
        /// <remarks><para>The constructor will not actually open or parse the region file.  It will only read the file's name in order
        /// to derive the region's coordinates, based on a strict naming pattern for regions: r.x.z.mcr, given x and z are integers
        /// representing the region's coordinates.</para>
        /// <para>Regions require a <see cref="ChunkCache"/> to be provided because they do not actually store any chunks or references
        /// to chunks on their own.  This allows regions to easily pass off requests outside of their bounds, if necessary.</para></remarks>
        public Region(RegionManager rm, ChunkCache cache, string filename)
        {
            _regionMan  = rm;
            _cache      = cache;
            _regionFile = new WeakReference(null);

            ParseFileName(filename, out _rx, out _rz);

            if (!File.Exists(Path.Combine(_regionMan.GetRegionPath(), filename)))
            {
                throw new FileNotFoundException();
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Creates an instance of a <see cref="Region"/> for a given set of coordinates.
        /// </summary>
        /// <param name="rm">The <see cref="RegionManager"/> that should be managing this region.</param>
        /// <param name="cache">A shared cache for holding chunks.</param>
        /// <param name="rx">The global X-coordinate of the region.</param>
        /// <param name="rz">The global Z-coordinate of the region.</param>
        /// <remarks><para>The constructor will not actually open or parse any region files.  Given just the region coordinates, the
        /// region will be able to determien the correct region file to look for based on the naming pattern for regions:
        /// r.x.z.mcr, given x and z are integers representing the region's coordinates.</para>
        /// <para>Regions require a <see cref="ChunkCache"/> to be provided because they do not actually store any chunks or references
        /// to chunks on their own.  This allows regions to easily pass off requests outside of their bounds, if necessary.</para></remarks>
        public Region(RegionManager rm, ChunkCache cache, int rx, int rz)
        {
            _regionMan  = rm;
            _cache      = cache;
            _regionFile = new WeakReference(null);
            _rx         = rx;
            _rz         = rz;

            if (!File.Exists(GetFilePath()))
            {
                throw new FileNotFoundException();
            }
        }
Ejemplo n.º 3
0
 // Use this for
 void Start()
 {
     Cache               = new ChunkCache(this);
     Cache.Resolution    = Resolution;
     Cache.StartSeed     = Seed;
     Cache.Steepness     = Steepness;
     Cache.MaxOverhang   = MaxOverhang;
     Cache.OverhangRatio = OverhangRatio;
     Cache.Patchamount   = PatchAmount;
     Noise               = new NoiseProvider();
     //PerlinNoise = new Perlin(Frequency, Lacunarity, Persistence, Octaves, Seed, QualityMode.Medium);
     //PerlinNoise = new Perlin();
     //float a = (float)(PerlinNoise.GetValue(1, 0, 1) / 2f) + 0.5f;
     //Debug.Log("outside");
     //Debug.Log(a);
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Adds game-components.
        /// </summary>
        private void AddComponents()
        {
            this.Components.Add(new InputManager(this));

            this.Components.Add(new AssetManager(this));

            #if XNA
            this.Components.Add(new Sky(this));
            #endif

            this.Components.Add(new Fogger(this));

            var chunkStorage = new ChunkStorage(this);
            this.Components.Add(chunkStorage);

            var vertexBuilder = new VertexBuilder(this);
            this.Components.Add(vertexBuilder);

            var chunkCache = new ChunkCache(this);
            this.Components.Add(chunkCache);

            var world = new World(this, chunkStorage, chunkCache);
            this.Components.Add(world);

            this.Components.Add(new Player(this, world));

            #if XNA
            bloom = new BloomComponent(this);
            this.Components.Add(bloom);
            #endif

            this.Components.Add(new Camera(this));
            this.Components.Add(new UserInterface(this));

            this.Components.Add(new InGameDebugger(this));
            this.Components.Add(new Statistics(this));
            this.Components.Add(new GraphManager(this));

            #if XNA
            this.Components.Add(new AudioManager(this));
            #endif

            this._timeRuler         = new TimeRuler(this);
            this._timeRuler.Visible = true;
            this._timeRuler.ShowLog = true;
            this.Components.Add(this._timeRuler);
        }
Ejemplo n.º 5
0
        public void updateRenderer(Material[] materials)
        {
            if (this.needsUpdate)
            {
                this.needsUpdate = false;
                int  posX     = this.xPos;
                int  posY     = this.yPos;
                int  posZ     = this.zPos;
                int  posXPlus = posX + 16;
                int  posYPlus = posY + 16;
                int  posZPlus = posZ + 16;
                byte plus     = 1;

                ChunkCache chunkCache = new ChunkCache(this.world, posX - plus, posY - plus, posZ - plus, posXPlus + plus, posYPlus + plus, posZPlus + plus, plus);
                if (!chunkCache.isEmpty())
                {
                    this.createMeshes(materials);
                    BlockRenderer blockRenderer = new BlockRenderer(chunkCache, this.chunkMesh, this.chunkMesh_transparent);
                    for (int blockX = posX; blockX < posXPlus; blockX++)
                    {
                        for (int blockZ = posZ; blockZ < posZPlus; blockZ++)
                        {
                            for (int blockY = posY; blockY < posYPlus; blockY++)
                            {
                                int blockID = chunkCache.getBlockID(blockX, blockY, blockZ);
                                if (blockID > 0)
                                {
                                    blockRenderer.renderBlock(Block.blocks[blockID], blockX, blockY, blockZ);
                                }
                            }
                        }
                    }
                    this.chunkMesh.build();
                    this.chunkMesh_transparent.build();
                    this.visible = true;
                }
                else
                {
                    this.visible = false;
                }
            }
        }
Ejemplo n.º 6
0
            private bool TryReadByte(long byteIndex, out byte b)
            {
                b = 0;

                if (byteIndex >= Session.FileInfo.FileSize)
                {
                    return(false);
                }

                // calculate chunk index by byte number
                long chunkNumber = (byteIndex / Session.FileInfo.ChunkSize) + 1;

                if (!ChunkCache.ContainsKey(chunkNumber))
                {
                    ChunkCache.Clear();
                    ChunkCache.Add(chunkNumber, Repository.Read(Session.Id, (int)chunkNumber));
                }

                // get the i-th byte inside that chunk
                b = ChunkCache[chunkNumber][byteIndex % Session.FileInfo.ChunkSize];
                return(true);
            }
Ejemplo n.º 7
0
        internal override void OnUpdate()
        {
            float      upperLimit = 20;
            ChunkCache cache      = World.Instance.GetCachedChunks();
            float      total      = cache.ChunkColumns.Values.Count();
            float      current    = cache.ChunkColumns.Values.Where(c => c.Stage == ChunkColumn.ColumnStageEnum.Decorated).Count();

            if (total > upperLimit)
            {
                total = upperLimit;
            }
            float progress = current / total;

            if (progress > 1f)
            {
                TheGame.Instance.CloseGui();
            }
            else
            {
                labelProgress.Text   = (progress * 100).ToString() + "%";
                panelProgress.Size.X = progress * panel.Size.X;
                panelProgress.Size.Y = panel.Size.Y;
            }
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Creates a new instance of a <see cref="RegionManager"/> for the given region directory and chunk cache.
 /// </summary>
 /// <param name="regionDir">The path to a directory containing region files.</param>
 /// <param name="cache">The shared chunk cache to hold chunk data in.</param>
 public RegionManager(string regionDir, ChunkCache cache)
 {
     _regionPath = regionDir;
     _chunkCache = cache;
     _cache      = new Dictionary <RegionKey, Region>();
 }
Ejemplo n.º 9
0
 /// <summary>
 /// Creates a new <see cref="BetaChunkManager"/> instance from another.
 /// </summary>
 /// <param name="cm">A <see cref="BetaChunkManager"/> to get a <see cref="RegionManager"/> and <see cref="ChunkCache"/> from.</param>
 public BetaChunkManager(BetaChunkManager cm)
 {
     _regionMan = cm._regionMan;
     _cache     = cm._cache;
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Creates a new <see cref="BetaChunkManager"/> instance given a backing <see cref="RegionManager"/> and <see cref="ChunkCache"/>.
 /// </summary>
 /// <param name="rm">A <see cref="RegionManager"/> exposing access to regions.</param>
 /// <param name="cache">A shared cache for storing chunks read in.</param>
 public BetaChunkManager(RegionManager rm, ChunkCache cache)
 {
     _regionMan = rm;
     _cache     = cache;
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Creates a new <see cref="RegionChunkManager"/> instance from another.
 /// </summary>
 /// <param name="cm">A <see cref="RegionChunkManager"/> to get a <see cref="RegionManager"/> and <see cref="ChunkCache"/> from.</param>
 public RegionChunkManager(RegionChunkManager cm)
 {
     _regionMan = cm._regionMan;
     _cache     = cm._cache;
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Creates a new <see cref="RegionChunkManager"/> instance given a backing <see cref="RegionManager"/> and <see cref="ChunkCache"/>.
 /// </summary>
 /// <param name="rm">A <see cref="RegionManager"/> exposing access to regions.</param>
 /// <param name="cache">A shared cache for storing chunks read in.</param>
 public RegionChunkManager(IRegionManager rm, ChunkCache cache)
 {
     _regionMan = rm;
     _cache     = cache;
 }
Ejemplo n.º 13
0
        private IPlanet loadPlanet(int index)
        {
            IUniverse universe = GetUniverse(0);

            var cache = new ChunkCache(idx => loadChunk(index, idx), (_, chunk) => saveChunk(index, chunk));
            _managers[index] = new PlanetResourceManager(cache);

            return mapGenerator.GeneratePlanet(universe.Id, index);
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            try
            {
                try
                {
                    try
                    {
                        x1 = short.Parse(args[0]);
                        y1 = short.Parse(args[1]);
                        x2 = short.Parse(args[2]);
                        y2 = short.Parse(args[3]);
                        if (x1 > x2 || y1 > y2)
                        {
                            throw new Exception();
                        }
                        try
                        {
                            File.Open(args[5], FileMode.Append, FileAccess.Write).Dispose();
                            logFilePath = args[5];
                        }
                        catch
                        { }
                    }
                    catch (OverflowException)
                    {
                        throw new Exception("Entire watched zone should be inside the map");
                    }
                    catch
                    {
                        throw new Exception("Parameters: <leftX> <topY> <rightX> <bottomY> [logFilePath] ; all in range -32768..32767");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    finishCTS.Cancel();
                    return;
                }
                logger = new Logger(finishCTS.Token, logFilePath);
                string fingerprint = Guid.NewGuid().ToString("N");
                cache = new ChunkCache(x1, y1, x2, y2, logger.LogLine);
                bool initialMapStateSaved = false;
                saveThread.Start();
                filename = string.Format("pixels_({0};{1})-({2};{3})_{4:yyyy.MM.dd_HH-mm}.bin", x1, y1, x2, y2, DateTime.Now);
                do
                {
                    try
                    {
                        using (InteractionWrapper wrapper = new InteractionWrapper(fingerprint, logger.LogLine, true))
                        {
                            cache.Wrapper = wrapper;
                            if (!initialMapStateSaved)
                            {
                                Task.Run(() =>
                                {
                                    initialMapStateSaved = true;
                                    cache.DownloadChunks();
                                    using (FileStream fileStream = File.Open(filename, FileMode.Create, FileAccess.Write))
                                    {
                                        using (BinaryWriter writer = new BinaryWriter(fileStream))
                                        {
                                            writer.Write(x1);
                                            writer.Write(y1);
                                            writer.Write(x2);
                                            writer.Write(y2);
                                            writer.Write(DateTime.Now.ToBinary());
                                            for (short y = y1; y <= y2; y++)
                                            {
                                                for (short x = x1; x <= x2; x++)
                                                {
                                                    writer.Write((byte)cache.GetPixelColor(x, y));
                                                }
                                            }
                                        }
                                    }
                                    logger.LogLine("Chunk data is saved to file", MessageGroup.TechInfo);
                                    lockingStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.None);
                                });
                            }

                            wrapper.OnPixelChanged += (o, e) =>
                            {
                                short x = PixelMap.ConvertToAbsolute(e.Chunk.Item1, e.Pixel.Item1);
                                short y = PixelMap.ConvertToAbsolute(e.Chunk.Item2, e.Pixel.Item2);
                                if (x <= x2 && x >= x1 && y <= y2 && y >= y1)
                                {
                                    logger.LogPixel("Received pixel update:", MessageGroup.PixelInfo, x, y, e.Color);
                                    lock (listLockObj)
                                    {
                                        updates.Add((x, y, e.Color));
                                    }
                                }
                            };
                            wrapper.StartListening();
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.LogLine($"Unhandled exception: {ex.Message}", MessageGroup.Error);
                    }
                } while (true);
            }
            finally
            {
                finishCTS.Cancel();
                Thread.Sleep(1000);
                finishCTS.Dispose();
                logger?.Dispose();
                if (saveThread.IsAlive)
                {
                    saveThread.Interrupt();
                }
            }
        }
Ejemplo n.º 15
0
        private static void Main(string[] args)
        {
            try
            {
                if (args.Length == 1)
                {
                    try
                    {
                        SaveFingerprint(Guid.Parse(args[0]));
                        Console.WriteLine("Fingerprint is saved, now you can relauch bot with needed parameters");
                    }
                    catch
                    {
                        Console.WriteLine("You should pass correct 128-bit fingerprint (GUID)");
                    }
                    return;
                }
                ushort           width, height;
                PlacingOrderMode order = PlacingOrderMode.Random;
                notificationMode = CaptchaNotificationMode.Browser;
                try
                {
                    try
                    {
                        leftX       = short.Parse(args[0]);
                        topY        = short.Parse(args[1]);
                        fingerprint = GetFingerprint();
                        string logFilePath = null;
                        if (args.Length > 3)
                        {
                            notificationMode = CaptchaNotificationMode.None;
                            string upper = args[3].ToUpper();
                            if (upper.Contains('B'))
                            {
                                notificationMode |= CaptchaNotificationMode.Browser;
                            }
                            if (upper.Contains('S'))
                            {
                                notificationMode |= CaptchaNotificationMode.Sound;
                            }
                            if (args.Length > 4)
                            {
                                defendMode = args[4].ToUpper() == "Y";

                                if (args.Length > 5)
                                {
                                    switch (args[5].ToUpper())
                                    {
                                    case "R":
                                        order = PlacingOrderMode.FromRight;
                                        break;

                                    case "L":
                                        order = PlacingOrderMode.FromLeft;
                                        break;

                                    case "T":
                                        order = PlacingOrderMode.FromTop;
                                        break;

                                    case "B":
                                        order = PlacingOrderMode.FromBottom;
                                        break;
                                    }

                                    if (args.Length > 6)
                                    {
                                        try
                                        {
                                            File.OpenWrite(args[6]).Dispose();
                                            logFilePath = args[6];
                                        }
                                        catch
                                        { }
                                    }
                                }
                            }
                        }
                        logger      = new Logger(finishCTS.Token, logFilePath);
                        imagePixels = ImageProcessing.PixelColorsByUri(args[2], logger.LogLine);
                        checked
                        {
                            width  = (ushort)imagePixels.GetLength(0);
                            height = (ushort)imagePixels.GetLength(1);
                            short check;
                            check = (short)(leftX + width);
                            check = (short)(topY + height);
                        }
                    }
                    catch (OverflowException)
                    {
                        throw new Exception("Entire image should be inside the map");
                    }
                    catch (WebException)
                    {
                        throw new Exception("Cannot download image");
                    }
                    catch (ArgumentException)
                    {
                        throw new Exception("Cannot convert image");
                    }
                    catch (IOException)
                    {
                        throw new Exception("Fingerprint is not saved, pass it from browser as only parameter to app to save before usage");
                    }
                    catch
                    {
                        throw new Exception("Parameters: <leftX> <topY> <imageURI> [notificationMode: N/B/S/BS = B] [defendMode: Y/N = N] [buildFrom L/R/T/B/RND = RND] [logFileName = none]");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    finishCTS.Cancel();
                    return;
                }
                IEnumerable <int> allY           = Enumerable.Range(0, height);
                IEnumerable <int> allX           = Enumerable.Range(0, width);
                Pixel[]           nonEmptyPixels = allX.
                                                   SelectMany(X => allY.Select(Y =>
                                                                               (X: (short)(X + leftX), Y: (short)(Y + topY), C: imagePixels[X, Y]))).
                                                   Where(xy => xy.C != PixelColor.None).ToArray();
                switch (order)
                {
                case PlacingOrderMode.FromLeft:
                    pixelsToBuild = nonEmptyPixels.OrderBy(xy => xy.Item1).ToList();
                    break;

                case PlacingOrderMode.FromRight:
                    pixelsToBuild = nonEmptyPixels.OrderByDescending(xy => xy.Item1).ToList();
                    break;

                case PlacingOrderMode.FromTop:
                    pixelsToBuild = nonEmptyPixels.OrderBy(xy => xy.Item2).ToList();
                    break;

                case PlacingOrderMode.FromBottom:
                    pixelsToBuild = nonEmptyPixels.OrderByDescending(xy => xy.Item2).ToList();
                    break;

                default:
                    Random rnd = new Random();
                    for (int i = 0; i < nonEmptyPixels.Length; i++)
                    {
                        int   r   = rnd.Next(i, nonEmptyPixels.Length);
                        Pixel tmp = nonEmptyPixels[r];
                        nonEmptyPixels[r] = nonEmptyPixels[i];
                        nonEmptyPixels[i] = tmp;
                    }
                    pixelsToBuild = nonEmptyPixels;
                    break;
                }
                cache = new ChunkCache(pixelsToBuild, logger.LogLine);
                mapDownloadedResetEvent = new ManualResetEvent(false);
                cache.OnMapDownloaded  += (o, e) => mapDownloadedResetEvent.Set();
                if (defendMode)
                {
                    gotGriefed             = new AutoResetEvent(false);
                    cache.OnMapDownloaded += (o, e) => gotGriefed.Set();
                    waitingGriefLock       = new object();
                }
                statsThread = new Thread(StatsCollectionThreadBody);
                statsThread.Start();
                do
                {
                    try
                    {
                        using (InteractionWrapper wrapper = new InteractionWrapper(fingerprint, logger.LogLine))
                        {
                            wrapper.OnPixelChanged   += LogPixelChanged;
                            wrapper.OnConnectionLost += (o, e) => mapDownloadedResetEvent.Reset();
                            cache.Wrapper             = wrapper;
                            cache.DownloadChunks();
                            placed.Clear();
                            bool wasChanged;
                            do
                            {
                                wasChanged     = false;
                                repeatingFails = false;
                                foreach (Pixel pixel in pixelsToBuild)
                                {
                                    (short x, short y, PixelColor color) = pixel;
                                    PixelColor actualColor = cache.GetPixelColor(x, y);
                                    if (!IsCorrectPixelColor(actualColor, color))
                                    {
                                        wasChanged = true;
                                        bool success;
                                        placed.Add(pixel);
                                        do
                                        {
                                            byte placingPixelFails = 0;
                                            mapDownloadedResetEvent.WaitOne();
                                            success = wrapper.PlacePixel(x, y, color, out double cd, out double totalCd, out string error);
                                            if (success)
                                            {
                                                string prefix = cd == 4 ? "P" : "Rep";
                                                logger.LogPixel($"{prefix}laced pixel:", MessageGroup.Pixel, x, y, color);
                                                Thread.Sleep(TimeSpan.FromSeconds(totalCd < 53 ? 1 : cd));
                                            }
                                            else
                                            {
                                                if (cd == 0.0)
                                                {
                                                    logger.LogLine("Please go to browser and place pixel, then return and press any key", MessageGroup.Captcha);
                                                    if (notificationMode.HasFlag(CaptchaNotificationMode.Sound))
                                                    {
                                                        Task.Run(() =>
                                                        {
                                                            for (int j = 0; j < 7; j++)
                                                            {
                                                                Console.Beep(1000, 100);
                                                            }
                                                        });
                                                    }
                                                    if (notificationMode.HasFlag(CaptchaNotificationMode.Browser))
                                                    {
                                                        Process.Start($"{InteractionWrapper.BaseHttpAdress}/#{x},{y},30");
                                                    }
                                                    Thread.Sleep(100);
                                                    logger.ConsoleLoggingResetEvent.Reset();
                                                    while (Console.KeyAvailable)
                                                    {
                                                        Console.ReadKey(true);
                                                    }
                                                    Console.ReadKey(true);
                                                    logger.ConsoleLoggingResetEvent.Set();
                                                }
                                                else
                                                {
                                                    logger.LogLine($"Failed to place pixel: {error}", MessageGroup.PixelFail);
                                                    if (++placingPixelFails == 3)
                                                    {
                                                        throw new Exception("Cannot place pixel 3 times");
                                                    }
                                                }
                                                Thread.Sleep(TimeSpan.FromSeconds(cd));
                                            }
                                        } while (!success);
                                    }
                                }
                                if (defendMode)
                                {
                                    if (!wasChanged)
                                    {
                                        logger.LogLine("Image is intact, waiting...", MessageGroup.ImageDone);
                                        lock (waitingGriefLock)
                                        {
                                            gotGriefed.Reset();
                                            gotGriefed.WaitOne();
                                        }
                                        Thread.Sleep(new Random().Next(500, 3000));
                                    }
                                }
                            }while (defendMode || wasChanged);
                            logger.LogLine("Building is finished, exiting...", MessageGroup.ImageDone);
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.LogLine($"Unhandled exception: {ex.Message}", MessageGroup.Error);
                        int delay = repeatingFails ? 30 : 10;
                        repeatingFails = true;
                        logger.LogLine($"Reconnecting in {delay} seconds...", MessageGroup.TechState);
                        Thread.Sleep(TimeSpan.FromSeconds(delay));
                        continue;
                    }
                } while (true);
            }
            finally
            {
                finishCTS.Cancel();
                gotGriefed?.Dispose();
                mapDownloadedResetEvent?.Dispose();
                logger?.Dispose();
                Thread.Sleep(1000);
                finishCTS.Dispose();
                if (statsThread?.IsAlive ?? false)
                {
                    statsThread.Interrupt(); //fallback, should never work
                }
            }
        }
Ejemplo n.º 16
0
        private static void Main(string[] args)
        {
            try
            {
                if (!ParseArguments(args, out bool isVerbError))
                {
                    bool exit = true;
                    if (isVerbError)
                    {
                        Console.WriteLine("No command were found");
                        Console.WriteLine("Check if your scripts are updated with 'run' command before other parameters");
                        Console.WriteLine();
                        Console.WriteLine("If you want to start app with 'run' command added, press Enter");
                        Console.WriteLine("Please note that this option is added for compatibility with older scripts and will be removed soon");
                        Console.WriteLine("Press any other key to exit");
                        while (Console.KeyAvailable)
                        {
                            Console.ReadKey(true);
                        }
                        if (Console.ReadKey(true).Key == ConsoleKey.Enter)
                        {
                            Console.Clear();
                            if (ParseArguments(args.Prepend("run"), out _))
                            {
                                exit = false;
                            }
                        }
                    }
                    if (exit)
                    {
                        return;
                    }
                }

                logger = new Logger(options?.LogFilePath, finishCTS.Token)
                {
                    ShowDebugLogs = options?.ShowDebugLogs ?? false
                };
                logger.LogDebug("Command line: " + Environment.CommandLine);
                HttpWrapper.Logger = logger;

                if (checkUpdates || !options.DisableUpdates)
                {
                    if (UpdateChecker.IsStartingUpdate(logger, checkUpdates) || checkUpdates)
                    {
                        return;
                    }
                }

                cache = new ChunkCache(options.LeftX, options.TopY, options.RightX, options.BottomY, logger);
                bool initialMapSavingStarted = false;
                saveThread = new Thread(SaveChangesThreadBody);
                saveThread.Start();
                if (string.IsNullOrWhiteSpace(options.FileName))
                {
                    options.FileName = string.Format("pixels_({0};{1})-({2};{3})_{4:yyyy.MM.dd_HH-mm}.bin", options.LeftX, options.TopY, options.RightX, options.BottomY, DateTime.Now);
                }
                Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(options.FileName)));
                do
                {
                    try
                    {
                        HttpWrapper.ConnectToApi();
                        using (WebsocketWrapper wrapper = new WebsocketWrapper(logger, true))
                        {
                            cache.Wrapper = wrapper;
                            if (!initialMapSavingStarted)
                            {
                                logger.LogDebug("Main(): initiating map saving");
                                initialMapSavingStarted = true;
                                lockingStreamTask       = Task.Run(SaveInitialMapState);
                            }
                            wrapper.OnPixelChanged += Wrapper_OnPixelChanged;
                            stopListening           = wrapper.StopListening;
                            Console.CancelKeyPress += (o, e) =>
                            {
                                logger.LogDebug("Console.CancelKeyPress received");
                                e.Cancel = true;
                                wrapper.StopListening();
                            };
                            logger.LogInfo("Press Ctrl+C to stop");
                            wrapper.StartListening();
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.LogError($"Unhandled exception: {ex.Message}");
                        Thread.Sleep(1000);
                    }
                } while (true);
            }
            catch (Exception ex)
            {
                logger?.LogError($"Unhandled app level exception: {ex.Message}");
            }
            finally
            {
                if (logger != null)
                {
                    logger.LogInfo("Exiting when everything is saved...");
                    logger.LogInfo($"Logs were saved to {logger.LogFilePath}");
                }
                finishCTS.Cancel();
                if (logger != null)
                {
                    Thread.Sleep(500);
                }
                finishCTS.Dispose();
                logger?.Dispose();
                if (saveThread != null && !saveThread.Join(TimeSpan.FromMinutes(1)))
                {
                    Console.WriteLine("Save thread doesn't finish, aborting");
                }
                Console.ForegroundColor = ConsoleColor.White;
                Environment.Exit(0);
            }
        }
Ejemplo n.º 17
0
        private static void Main(string[] args)
        {
            try
            {
                if (!ParseArguments(args, out bool isVerbError))
                {
                    bool exit = true;
                    if (isVerbError)
                    {
                        Console.WriteLine("No command was found");
                        Console.WriteLine("Check if your scripts are updated with 'run' command before other parameters");
                        Console.WriteLine();
                        Console.WriteLine("If you want to start bot with 'run' command added, press Enter");
                        Console.WriteLine("Please note that this option is added for compatibility with older scripts and will be removed soon");
                        Console.WriteLine("Press any other key to exit");
                        while (Console.KeyAvailable)
                        {
                            Console.ReadKey(true);
                        }
                        if (Console.ReadKey(true).Key == ConsoleKey.Enter)
                        {
                            Console.Clear();
                            if (ParseArguments(args.Prepend("run"), out _))
                            {
                                exit = false;
                            }
                        }
                    }
                    if (exit)
                    {
                        return;
                    }
                }

                logger = new Logger(options?.LogFilePath, finishCTS.Token)
                {
                    ShowDebugLogs = options?.ShowDebugLogs ?? false
                };
                logger.LogDebug("Command line: " + Environment.CommandLine);
                HttpWrapper.Logger = logger;

                if (checkUpdates || !options.DisableUpdates)
                {
                    if (UpdateChecker.IsStartingUpdate(logger, checkUpdates) || checkUpdates)
                    {
                        return;
                    }
                }

                try
                {
                    imagePixels = ImageProcessing.PixelColorsByUri(options.ImagePath, logger);
                }
                catch (WebException ex)
                {
                    logger.LogError("Cannot download image");
                    logger.LogDebug($"Main(): error downloading image - {ex.Message}");
                    return;
                }
                catch (ArgumentException ex)
                {
                    logger.LogError("Cannot convert image");
                    logger.LogDebug($"Main(): error converting image - {ex.Message}");
                    return;
                }

                try
                {
                    checked
                    {
                        width  = (ushort)imagePixels.GetLength(0);
                        height = (ushort)imagePixels.GetLength(1);
                        short check;
                        check = (short)(options.LeftX + width);
                        check = (short)(options.TopY + height);
                    }
                }
                catch (OverflowException ex)
                {
                    logger.LogError("Entire image should be inside the map");
                    logger.LogDebug($"Main(): error checking boundaries - {ex.Message}");
                    return;
                }

                logger.LogTechState("Calculating pixel placing order...");
                if (!CalculatePixelOrder())
                {
                    return;
                }
                logger.LogTechInfo("Pixel placing order is calculated");

                cache = new ChunkCache(pixelsToBuild, logger);
                mapUpdatedResetEvent = new ManualResetEvent(false);
                cache.OnMapUpdated  += (o, e) =>
                {
                    logger.LogDebug("Cache.OnMapUpdated handler: Map updated event received");
                    mapUpdatedResetEvent.Set();
                };
                if (options.DefenseMode)
                {
                    gotGriefed          = new AutoResetEvent(false);
                    cache.OnMapUpdated += (o, e) => gotGriefed.Set();
                    waitingGriefLock    = new object();
                }
                statsThread = new Thread(StatsCollectionThreadBody);
                statsThread.Start();
                do
                {
                    try
                    {
                        HttpWrapper.ConnectToApi();
                        MainWorkingBody();
                        return;
                    }
                    catch (PausingException ex)
                    {
                        logger.LogError($"Unhandled exception: {ex.Message}");
                        logger.LogInfo($"Check that problem is resolved and press any key to continue");
                        while (Console.KeyAvailable)
                        {
                            Console.ReadKey(true);
                        }
                        Console.ReadKey(true);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError($"Unhandled exception: {ex.Message}");
                        int delay = repeatingFails ? 30 : 10;
                        repeatingFails = true;
                        logger.LogTechState($"Reconnecting in {delay} seconds...");
                        Thread.Sleep(TimeSpan.FromSeconds(delay));
                        continue;
                    }
                } while (true);
            }
            catch (Exception ex)
            {
                string msg = $"Unhandled app level exception: {ex.Message}";
                if (logger != null)
                {
                    logger.LogError(msg);
                }
                else
                {
                    Console.WriteLine(msg);
                }
            }
            finally
            {
                if (logger != null)
                {
                    logger.LogInfo("Exiting...");
                    logger.LogInfo($"Logs were saved to {logger.LogFilePath}");
                }
                finishCTS.Cancel();
                if (logger != null)
                {
                    Thread.Sleep(500);
                }
                gotGriefed?.Dispose();
                mapUpdatedResetEvent?.Dispose();
                logger?.Dispose();
                finishCTS.Dispose();
                Console.ForegroundColor = ConsoleColor.White;
                Environment.Exit(0);
            }
        }
Ejemplo n.º 18
0
        internal void ProfilerSnapshot()
        {
            VertexBuffer.Dispose(ref profileVertexBuffer);

            t.ResetTransformation();
            FontRenderer f      = FontRenderer.Instance;
            Player       player = World.Instance.Player;

            f.BeginBatch();
            f.CharScale = 1;
            string report = p.Report();
            float  y      = TheGame.Instance.Height - FontRenderer.Instance.LineHeight;

            using (StringReader sr = new StringReader(report))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    f.RenderTextShadow(line, 0, y);
                    y -= f.LineHeight;
                }
            }

            // log...
            y -= f.LineHeight;

            if (World.Instance.PlayerVoxelTrace.Hit)
            {
                Vector4 impactpos = World.Instance.PlayerVoxelTrace.ImpactPosition;
                string  line      = string.Format(GetVectorAsString("impactpos", impactpos));
                f.RenderTextShadow(line, 0, y);
                y -= f.LineHeight;
            }
            else
            {
                f.RenderTextShadow("impactpos", 0, y);
                y -= f.LineHeight;

                Vector3 pos = new Vector3(player.Position.X, player.Position.Y, player.Position.Z);
                if (pos.Y > Chunk.MaxSizeY - 1)
                {
                    pos.Y = Chunk.MaxSizeY - 1;
                }
                else if (pos.Y < 0)
                {
                    pos.Y = 0;
                }
                PositionChunk chunkPos  = PositionChunk.CreateFrom(pos);
                Vector3       chunkPos3 = new Vector3(chunkPos.X, chunkPos.Y, chunkPos.Z);
                f.RenderTextShadow(string.Format(GetVectorAsString("chunkpos", chunkPos3)), 0, y);
                y -= f.LineHeight;
                ChunkCache cache = World.Instance.GetCachedChunks();
                Chunk      c     = cache.GetChunk(chunkPos);
                if (c != null)
                {
                    f.RenderTextShadow(string.Format("chunk.Stage      = {0}", c.Stage.ToString()), 0, y);
                    y -= f.LineHeight;
                    f.RenderTextShadow(string.Format("chunk.col.stage  = {0}", c.Column.Stage.ToString()), 0, y);
                    y -= f.LineHeight;
                    f.RenderTextShadow(string.Format("chunk.col.active = {0}", c.Column.Active.ToString()), 0, y);
                    y -= f.LineHeight;
                    f.RenderTextShadow(string.Format("cache.alleighbors= {0}", cache.AllNeighborColumns(c.Column).Where(cc => cc != null).Count()), 0, y);
                    y -= f.LineHeight;

                    List <Chunk> chunks = new List <Chunk>();
                    for (int i = 0; i < 8; i++)
                    {
                        chunks.Add(cache.GetChunk(new PositionChunk(c.Position.X, i, c.Position.Z)));
                    }
                }
            }
            f.RenderTextShadow(GetVectorAsString("direction", player.Direction), 0, y);

            y -= f.LineHeight;
            f.RenderTextShadow(GetVectorAsString("position", player.Position), 0, y);

            y -= f.LineHeight;
            y -= f.LineHeight;
            string[] lastLines = Log.Instance.Last(70);
            foreach (string line in lastLines)
            {
                f.RenderTextShadow(line, 0, y);
                y -= f.LineHeight;
            }
            f.StopBatch();
            profileVertexBuffer = t.GetVertexBuffer();
        }
Ejemplo n.º 19
0
 public BetaRegion(BetaRegionManager rm, ChunkCache cache, int rx, int rz)
     : base(rm, cache, rx, rz)
 {
 }
Ejemplo n.º 20
0
        private void RenderPass1AndBuildPass2List()
        {
            t.ResetTransformation();

            pass2ChunkRenderers.Clear();
            cachedChunks = World.Instance.GetCachedChunks();
            if (cachedChunks.Count != 0)
            {
                Counters.Instance.SetValue("c.all     ", cachedChunks.Count);
                Counters.Instance.SetValue("c.notgen  ", cachedChunks.OrderedChunks.Where(c => c.Stage == Chunk.ChunkStageEnum.NotGenerated).Count());
                Counters.Instance.SetValue("c.gen     ", cachedChunks.OrderedChunks.Where(c => c.Stage == Chunk.ChunkStageEnum.Generated).Count());
                Counters.Instance.SetValue("c.upd     ", cachedChunks.OrderedChunks.Where(c => c.Stage == Chunk.ChunkStageEnum.Update).Count());
                Counters.Instance.SetValue("col.all   ", cachedChunks.ChunkColumns.Values.Count());
                Counters.Instance.SetValue("col.notgen", cachedChunks.ChunkColumns.Values.Where(c => c.Stage == ChunkColumn.ColumnStageEnum.NotGenerated).Count());
                Counters.Instance.SetValue("col.gen   ", cachedChunks.ChunkColumns.Values.Where(c => c.Stage == ChunkColumn.ColumnStageEnum.Generated).Count());
                Counters.Instance.SetValue("col.rdygen", cachedChunks.ChunkColumns.Values.Where(c => c.Stage == ChunkColumn.ColumnStageEnum.AllNeighborsGenerated).Count());
                Counters.Instance.SetValue("col.deco  ", cachedChunks.ChunkColumns.Values.Where(c => c.Stage == ChunkColumn.ColumnStageEnum.Decorated).Count());
            }

            if (cachedChunks.Count == 0)
            {
                return;
            }

            float viewRadiusSquared = (int)((GameSettings.ViewRadius * GameSettings.ViewRadius) / 256f);

            forceCachedRendering = false;
            if (cachedChunks.IsDirty)
            {
                chunksToRender = cachedChunks.OrderedChunks.Where(c =>
                {
                    float dx = c.Position.X - cachedChunks.LastCenterChunk.X;
                    float dy = c.Position.Y - cachedChunks.LastCenterChunk.Y;
                    float dz = c.Position.Z - cachedChunks.LastCenterChunk.Z;
                    return(dx * dx + dy * dy + dz * dz <= viewRadiusSquared);
                }).OrderBy(c =>
                {
                    float dx = c.Position.X - cachedChunks.LastCenterChunk.X;
                    float dy = c.Position.Y - cachedChunks.LastCenterChunk.Y;
                    float dz = c.Position.Z - cachedChunks.LastCenterChunk.Z;
                    return(dx * dx + dy * dy + dz * dz);
                }).ToList();
                cachedChunks.IsDirty = false;
            }

            p.StartSection("renderchunks");
            foreach (Chunk chunk in chunksToRender)
            {
                RenderChunk(chunk);
            }
            p.EndStartSection("dispose");

            // dispose and remove expired chunks
            var expiredRenderer = chunkRenderers.Where(pair => pair.Value.Expired).ToList();

            expiredRenderer.ForEach(pair =>
            {
                pair.Value.Dispose();
                chunkRenderers.Remove(pair.Key);
            });
            Counters.Instance.SetValue("ChunkRenderer objects", chunkRenderers.Count);
            p.EndSection();
        }
Ejemplo n.º 21
0
 public BetaRegionManager(string regionDir, ChunkCache cache)
     : base(regionDir, cache)
 {
 }
Ejemplo n.º 22
0
 public AnvilRegion(AnvilRegionManager rm, ChunkCache cache, int rx, int rz)
     : base(rm, cache, rx, rz)
 {
 }