public async Task Collect(CollectTask collectTask)
		{
			var blockFactory = new BlockFactory(collectTask);
			var blockController = new BlockController();
			blockController.Trace = DataCollector.Trace;
			blockFactory.Trace = DataCollector.Trace;

			// Create repo for write results
			var inputRepo = getRepository(collectTask.Input);
			var outputRepo = getRepository(collectTask.Output);

			var inputBufferBlock = blockFactory.InputBuffer();
			var bacthBlock = blockFactory.Batch<string>();
			var processBlock = blockFactory.Process();
			var outputBufferBlock = blockFactory.OutputBuffer();
			var outputBlock = blockFactory.WriteResults(outputRepo);

			blockController.LinkWithCompletion(inputBufferBlock, bacthBlock);
			blockController.LinkWithCompletion(bacthBlock, processBlock);
			blockController.LinkWithCompletion(processBlock, outputBufferBlock);
			blockController.LinkWithCompletion(outputBufferBlock, outputBlock);

			// Read data and send to blocks
			foreach (var item in inputRepo.GetInputData())
			{
				await inputBufferBlock.SendAsync(item);
				collectTask.AllItems++;

                if (collectTask.AllItems % 524288 == 0)
                    Thread.Sleep(TimeSpan.FromMinutes(15));

				if (collectTask.CancellationSource.IsCancellationRequested)
					break;
			}
			inputBufferBlock.Complete();

			await outputBlock.Completion;

			inputRepo.Dispose();
			outputRepo.Dispose();
		}
Esempio n. 2
0
 void Start()
 {
     createdObject = new List<GameObject>();
     _instant = this;
 }
Esempio n. 3
0
        public static Item GetItem(int id, short metadata)
        {
            Item item = null;

            if (CustomItemFactory != null)
            {
                item = CustomItemFactory.GetItem(id, metadata);
            }

            if (item != null)
            {
                return(item);
            }

            if (id == 54)
            {
                item = new ItemChest(metadata);
            }
            else if (id == 44)
            {
                item = new ItemSlab(id, metadata);
            }
            else if (id == 61)
            {
                item = new ItemFurnace(metadata);
            }
            else if (id == 63)
            {
                item = new ItemSign(metadata);
            }
            else if (id == 68)
            {
                item = new ItemSign(metadata);
            }
            else if (id == 116)
            {
                item = new ItemEnchantingTable(metadata);
            }
            else if (id == 158)
            {
                item = new ItemSlab(id, metadata);
            }
            else if (id == 256)
            {
                item = new ItemIronShovel(metadata);
            }
            else if (id == 258)
            {
                item = new ItemIronAxe(metadata);
            }
            else if (id == 259)
            {
                item = new ItemFlintAndSteel(metadata);
            }
            else if (id == 260)
            {
                item = new ItemApple();
            }
            else if (id == 261)
            {
                item = new ItemBow(metadata);
            }
            else if (id == 263)
            {
                item = new ItemCoal(metadata);
            }
            else if (id == 267)
            {
                item = new ItemIronSword(metadata);
            }
            else if (id == 268)
            {
                item = new ItemWoodenSword(metadata);
            }
            else if (id == 269)
            {
                item = new ItemWoodenShovel(metadata);
            }
            else if (id == 270)
            {
                item = new ItemWoodenPickaxe(metadata);
            }
            else if (id == 271)
            {
                item = new ItemWoodenAxe(metadata);
            }
            else if (id == 272)
            {
                item = new ItemStoneSword(metadata);
            }
            else if (id == 273)
            {
                item = new ItemStoneShovel(metadata);
            }
            else if (id == 275)
            {
                item = new ItemStoneAxe(metadata);
            }
            else if (id == 276)
            {
                item = new ItemDiamondSword(metadata);
            }
            else if (id == 277)
            {
                item = new ItemDiamondShovel(metadata);
            }
            else if (id == 279)
            {
                item = new ItemDiamondAxe(metadata);
            }
            else if (id == 280)
            {
                item = new ItemStick(metadata);
            }
            else if (id == 283)
            {
                item = new ItemGoldSword(metadata);
            }
            else if (id == 284)
            {
                item = new ItemGoldShovel(metadata);
            }
            else if (id == 286)
            {
                item = new ItemGoldAxe(metadata);
            }
            else if (id == 290)
            {
                item = new ItemWoodenHoe(metadata);
            }
            else if (id == 291)
            {
                item = new ItemStoneHoe(metadata);
            }
            else if (id == 292)
            {
                item = new ItemIronHoe(metadata);
            }
            else if (id == 293)
            {
                item = new ItemDiamondHoe(metadata);
            }
            else if (id == 294)
            {
                item = new ItemGoldHoe(metadata);
            }
            else if (id == 297)
            {
                item = new ItemBread();
            }
            else if (id == 298)
            {
                item = new ItemLeatherHelmet(metadata);
            }
            else if (id == 299)
            {
                item = new ItemLeatherChestplate(metadata);
            }
            else if (id == 300)
            {
                item = new ItemLeatherLeggings(metadata);
            }
            else if (id == 301)
            {
                item = new ItemLeatherBoots(metadata);
            }
            else if (id == 302)
            {
                item = new ItemChainmailHelmet(metadata);
            }
            else if (id == 303)
            {
                item = new ItemChainmailChestplate(metadata);
            }
            else if (id == 304)
            {
                item = new ItemChainmailLeggings(metadata);
            }
            else if (id == 305)
            {
                item = new ItemChainmailBoots(metadata);
            }
            else if (id == 309)
            {
                item = new ItemIronBoots(metadata);
            }
            else if (id == 308)
            {
                item = new ItemIronLeggings(metadata);
            }
            else if (id == 307)
            {
                item = new ItemIronChestplate(metadata);
            }
            else if (id == 306)
            {
                item = new ItemIronHelmet(metadata);
            }
            else if (id == 310)
            {
                item = new ItemDiamondHelmet(metadata);
            }
            else if (id == 311)
            {
                item = new ItemDiamondChestplate(metadata);
            }
            else if (id == 312)
            {
                item = new ItemDiamondLeggings(metadata);
            }
            else if (id == 313)
            {
                item = new ItemDiamondBoots(metadata);
            }
            else if (id == 314)
            {
                item = new ItemGoldHelmet(metadata);
            }
            else if (id == 315)
            {
                item = new ItemGoldChestplate(metadata);
            }
            else if (id == 316)
            {
                item = new ItemGoldLeggings(metadata);
            }
            else if (id == 317)
            {
                item = new ItemGoldBoots(metadata);
            }
            else if (id == 319)
            {
                item = new ItemRawPorkchop(metadata);
            }
            else if (id == 320)
            {
                item = new ItemCookedPorkshop();
            }
            else if (id == 322)
            {
                item = new ItemGoldenApple();
            }
            else if (id == 323)
            {
                item = new ItemSign(metadata);
            }
            else if (id == 324)
            {
                item = new ItemDoor(metadata);
            }
            else if (id == 325)
            {
                item = new ItemBucket(metadata);
            }
            else if (id == 332)
            {
                item = new ItemSnowball(metadata);
            }
            else if (id == 344)
            {
                item = new ItemEgg(metadata);
            }
            else if (id == 355)
            {
                item = new ItemBed(metadata);
            }
            else if (id == 357)
            {
                item = new ItemCookie();
            }
            else if (id == 360)
            {
                item = new ItemMelonSlice();
            }
            else if (id == 363)
            {
                item = new ItemRawBeef();
            }
            else if (id == 364)
            {
                item = new ItemSteak();
            }
            else if (id == 365)
            {
                item = new ItemRawChicken();
            }
            else if (id == 366)
            {
                item = new ItemCoockedChicken();
            }
            else if (id == 383)
            {
                item = new ItemSpawnEgg(metadata);
            }
            else if (id == 391)
            {
                item = new ItemCarrot();
            }
            else if (id == 392)
            {
                item = new ItemPotato();
            }
            else if (id == 393)
            {
                item = new ItemBakedPotato();
            }
            else if (id == 397)
            {
                item = new ItemMobHead(metadata);
            }
            else if (id == 400)
            {
                item = new ItemPumpkinPie();
            }
            else if (id <= 255)
            {
                Block block = BlockFactory.GetBlockById((byte)id);
                if (CustomBlockItemFactory == null)
                {
                    item = new ItemBlock(block, metadata);
                }
                else
                {
                    item = CustomBlockItemFactory.GetBlockItem(block, metadata);
                }
            }
            else
            {
                item = new Item(id, metadata);
            }

            return(item);
        }
        private void PopulateChunk(ChunkColumn chunk)
        {
            var bottom   = new SimplexOctaveGenerator(Globals.Seed.GetHashCode(), 8);
            var overhang = new SimplexOctaveGenerator(Globals.Seed.GetHashCode(), 8);

            overhang.SetScale(1 / OverhangScale);
            bottom.SetScale(1 / Groundscale);


            for (var x = 0; x < 16; x++)
            {
                for (var z = 0; z < 16; z++)
                {
                    float ox = x + chunk.X * 16;
                    float oz = z + chunk.Z * 16;

                    var cBiome = _biomeManager.GetBiome((int)ox, (int)oz);
                    chunk.BiomeId[x * 16 + z] = cBiome.MinecraftBiomeId;

                    var bottomHeight =
                        (int)
                        ((bottom.Noise(ox, oz, BottomsFrequency, BottomsAmplitude) * BottomsMagnitude) + BottomOffset + cBiome.BaseHeight);

                    var maxHeight =
                        (int)
                        ((overhang.Noise(ox, oz, OverhangFrequency, OverhangAmplitude) * OverhangsMagnitude) + bottomHeight +
                         OverhangOffset);
                    maxHeight = Math.Max(1, maxHeight);

                    for (var y = 0; y < maxHeight && y < 256; y++)
                    {
                        if (y == 0)
                        {
                            chunk.SetBlock(x, y, z, BlockFactory.GetBlockById(7));
                            continue;
                        }

                        if (y > bottomHeight)
                        {
                            //part where we do the overhangs
                            if (EnableOverhang)
                            {
                                var density = overhang.Noise(ox, y, oz, OverhangFrequency, OverhangAmplitude);
                                if (density > Threshold)
                                {
                                    chunk.SetBlock(x, y, z, BlockFactory.GetBlockById(1));
                                }
                            }
                        }
                        else
                        {
                            chunk.SetBlock(x, y, z, BlockFactory.GetBlockById(1));
                        }
                    }

                    //Turn the blocks ontop into the correct material
                    for (var y = 0; y < 256; y++)
                    {
                        if (chunk.GetBlock(x, y + 1, z) == 0 && chunk.GetBlock(x, y, z) == 1)
                        {
                            chunk.SetBlock(x, y, z, cBiome.TopBlock);

                            chunk.SetBlock(x, y - 1, z, cBiome.Filling);
                            chunk.SetBlock(x, y - 2, z, cBiome.Filling);
                        }
                    }

                    foreach (var decorator in cBiome.Decorators)
                    {
                        decorator.Decorate(chunk, cBiome, x, z);
                    }
                    new OreDecorator().Decorate(chunk, cBiome, x, z);                     //Ores :)
                    new BedrockDecorator().Decorate(chunk, cBiome, x, z);                 //Random bedrock :)
                }
            }

            new WaterDecorator().Decorate(chunk, new PlainsBiome());             //For now, ALWAYS use the water decorator on all chunks...
            _cavegen.GenerateCave(chunk);
            new LavaDecorator().Decorate(chunk, new PlainsBiome());
        }
Esempio n. 5
0
        public void Load(Player player, params string[] schematicFile)
        {
            string filename = string.Join(" ", schematicFile);

            NbtFile     file      = new NbtFile(@"D:\Downloads\schematics\medieval-castle.schematic");
            NbtCompound schematic = file.RootTag;
            var         width     = schematic["Width"].ShortValue;
            var         length    = schematic["Length"].ShortValue;
            var         height    = schematic["Height"].ShortValue;
            bool        useAlpha  = schematic["Materials"].StringValue.Equals("Alpha");

            byte[] blocks    = schematic["Blocks"].ByteArrayValue;
            byte[] blockData = schematic["Data"].ByteArrayValue;

            var buffer = new List <Block>();

            for (int x = 0; x < width; ++x)
            {
                for (int y = 0; y < height; ++y)
                {
                    for (int z = 0; z < length; ++z)
                    {
                        int index = y * width * length + z * width + x;
                        BlockCoordinates coord = new BlockCoordinates(x, y, z);

                        if (blocks[index] == 0)
                        {
                            continue;
                        }

                        int  blockId = blocks[index];
                        byte data    = blockData[index];

                        Func <int, byte, byte> dataConverter = (i, b) => b;                        // Default no-op converter
                        if (AnvilWorldProvider.Convert.ContainsKey(blockId))
                        {
                            dataConverter = AnvilWorldProvider.Convert[blockId].Item2;
                            blockId       = AnvilWorldProvider.Convert[blockId].Item1;
                        }
                        else
                        {
                            if (BlockFactory.GetBlockById((byte)blockId).GetType() == typeof(Block))
                            {
                                Log.Warn($"No block implemented for block ID={blockId}, Meta={data}");
                                //blockId = 57;
                            }
                        }

                        if (blockId > 255)
                        {
                            Log.Warn($"Failed mapping for block ID={blockId}, Meta={data}");
                            blockId = 41;
                        }

                        var metadata = dataConverter(blockId, data);

                        Block block = BlockFactory.GetBlockById((byte)blockId);
                        block.Coordinates = coord;
                        block.Metadata    = metadata;
                        buffer.Add(block);
                    }
                }
            }

            //NbtList blockEntities = schematic["TileEntities"] as NbtList;
            //if (blockEntities != null)
            //{
            //	foreach (var blockEntity in blockEntities)
            //	{
            //	}
            //}

            Clipboard clipboard = new Clipboard(player.Level, buffer);

            clipboard.Origin   = new BlockCoordinates(clipboard.GetMin());
            Selector.Clipboard = clipboard;
            player.SendMessage("Loaded schematic from file");
        }
Esempio n. 6
0
        public bool BreakWalls(Vector3 forward, Vector3 right)
        {
            BlockFactory blockFactory = Factory.Get <BlockFactory>();
            Vector3      basePos      = this.Position + new Vector3(0, 0.2f + (this.Height * -0.5f) - this.SupportHeight, 0) + forward * -1.0f;
            bool         broke        = false;

            foreach (Voxel map in Voxel.ActivePhysicsVoxels.ToList())
            {
                List <Voxel.Coord> removals      = new List <Voxel.Coord>();
                Quaternion         mapQuaternion = Quaternion.CreateFromRotationMatrix(map.Transform);
                Voxel.Coord        top           = map.GetCoordinate(basePos + new Vector3(0, this.Height + this.SupportHeight + 0.5f, 0));
                Direction          upDir         = map.GetRelativeDirection(Vector3.Up);
                Direction          rightDir      = map.GetRelativeDirection(right);
                Direction          forwardDir    = map.GetRelativeDirection(forward);
                Voxel.Coord        center        = map.GetCoordinate(basePos);
                for (Voxel.Coord y = center.Clone(); y.GetComponent(upDir) <= top.GetComponent(upDir); y = y.Move(upDir))
                {
                    int minZ = center.GetComponent(rightDir) - 10;
                    int maxZ = minZ + 20;
                    foreach (Voxel.Coord x in this.spreadFromCenter(y, rightDir))
                    {
                        Voxel.Coord z = x.Clone();
                        for (int i = 0; i < 4; i++)
                        {
                            Voxel.State state           = map[z];
                            int         zRightDimension = z.GetComponent(rightDir);
                            if (zRightDimension > minZ && zRightDimension < maxZ && state.ID != 0 && !removals.Contains(z))
                            {
                                if (state.Permanent || state.Hard)
                                {
                                    if (zRightDimension >= center.GetComponent(rightDir))
                                    {
                                        maxZ = zRightDimension;
                                    }
                                    else
                                    {
                                        minZ = zRightDimension;
                                    }
                                    break;
                                }
                                else
                                {
                                    broke = true;
                                    removals.Add(z);
                                    Vector3   cellPos        = map.GetAbsolutePosition(z);
                                    Vector3   toCell         = cellPos - basePos;
                                    Entity    block          = blockFactory.CreateAndBind(this.main);
                                    Transform blockTransform = block.Get <Transform>();
                                    blockTransform.Position.Value   = cellPos;
                                    blockTransform.Quaternion.Value = Quaternion.CreateFromYawPitchRoll(((float)this.random.NextDouble() - 0.5f) * 2.0f, ((float)this.random.NextDouble() - 0.5f) * 2.0f, ((float)this.random.NextDouble() - 0.5f) * 2.0f);
                                    state.ApplyToBlock(block);
                                    toCell += forward * 4.0f;
                                    toCell.Normalize();
                                    PhysicsBlock physicsBlock = block.Get <PhysicsBlock>();
                                    physicsBlock.LinearVelocity.Value  = toCell * 15.0f;
                                    physicsBlock.AngularVelocity.Value = new Vector3(((float)this.random.NextDouble() - 0.5f) * 2.0f * (float)Math.PI, ((float)this.random.NextDouble() - 0.5f) * 2.0f * (float)Math.PI, ((float)this.random.NextDouble() - 0.5f) * 2.0f * (float)Math.PI);
                                    main.Add(block);
                                }
                            }
                            z = z.Move(forwardDir);
                        }
                    }
                }

                if (removals.Count > 0)
                {
                    map.Empty(removals);
                    map.Regenerate();
                }
            }
            return(broke);
        }
Esempio n. 7
0
 public ItemCauldron() : base("minecraft:cauldron", 380, 0)
 {
     Block = BlockFactory.GetBlockById(118);
 }
Esempio n. 8
0
        public static void Main(string[] args)
        {
            var configFilepath = args[0];
            var password       = args[1];

            // config
            var nodeConfig      = ConfigDeserializer.Deserialize <NodeConfig>(configFilepath);
            var console         = ConsoleFactory.Build(nodeConfig.IsMiningNode);
            var ipAddress       = IpAddressProvider.GetLocalIpAddress();
            var electionEndTime = nodeConfig.IsClassDemo ? DateTime.Now.AddSeconds(120) : nodeConfig.ElectionEndTime;

            // password check
            var voterDb    = new VoterDatabaseFacade(nodeConfig.VoterDbFilepath);
            var foundMiner = voterDb.TryGetVoterEncryptedKeyPair(password, out var encryptedKeyPair);

            if (!foundMiner)
            {
                Console.WriteLine("incorrect password: you may not mine!");
                return;
            }

            // blockchain
            var blockchain = new Blockchain();

            // networking
            var registrarClientFactory     = new RegistrarClientFactory();
            var registrarClient            = registrarClientFactory.Build(ipAddress, RegistrarPort);
            var registrationRequestFactory = new RegistrationRequestFactory();
            var myConnectionInfo           = new NodeConnectionInfo(ipAddress, nodeConfig.Port);
            var knownNodeStore             = new KnownNodeStore();
            var nodeClientFactory          = new NodeClientFactory();
            var handshakeRequestFactory    = new HandshakeRequestFactory(blockchain);
            var nodeClientStore            = new NodeClientStore();
            var nodeServerFactory          = new NodeServerFactory();

            // votes
            var protoVoteFactory = new ProtoVoteFactory();
            var voteForwarder    = new VoteForwarder(nodeClientStore, protoVoteFactory);
            var voteMemoryPool   = new VoteMemoryPool(voteForwarder, console);

            // blocks
            var merkleNodeFactory = new MerkleNodeFactory();
            var merkleTreeFactory = new MerkleTreeFactory(merkleNodeFactory);
            var minerId           = encryptedKeyPair.PublicKey.GetBase64String();
            var blockFactory      = new BlockFactory(merkleTreeFactory, minerId);
            var protoBlockFactory = new ProtoBlockFactory(protoVoteFactory);
            var blockForwarder    = new BlockForwarder(nodeClientStore, protoBlockFactory);
            var voteValidator     = new VoteValidator(blockchain, voterDb, electionEndTime);
            var blockValidator    = new BlockValidator(blockFactory, voteValidator);
            var blockchainAdder   = new BlockchainAdder(blockchain, voteMemoryPool, blockForwarder, console);

            // mining
            var difficultyTarget = TargetFactory.Build(BlockHeader.DefaultBits);
            var miner            = new Miner(
                blockchain,
                voteMemoryPool,
                difficultyTarget,
                blockFactory,
                blockchainAdder,
                console);

            // interaction
            var voteSerializer           = new VoteSerializer();
            var electionAlgorithmFactory = new ElectionAlgorithmFactory(voteSerializer);
            var electionAlgorithm        = electionAlgorithmFactory.Build(nodeConfig.ElectionType);
            var electionResultProvider   = new ElectionResultProvider(
                electionAlgorithm,
                electionEndTime,
                voteMemoryPool,
                blockchain);
            var voterTerminal = new VoterTerminal.VoterTerminal(
                voterDb,
                nodeConfig.Candidates.ToArray(),
                voteSerializer,
                voteMemoryPool,
                electionResultProvider,
                blockchain);
            var votingBooth = new VoterTerminal.VoterBooth(voterTerminal, nodeConfig.ElectionType);

            // startup
            var nodeServer = nodeServerFactory.Build(
                myConnectionInfo,
                knownNodeStore,
                nodeClientFactory,
                nodeClientStore,
                voteMemoryPool,
                blockchain,
                miner,
                voteValidator,
                blockValidator,
                blockchainAdder,
                console);
            var boostrapper = new Bootstrapper(
                MinNetworkSize,
                knownNodeStore,
                nodeClientFactory,
                handshakeRequestFactory,
                nodeClientStore,
                registrarClient,
                registrationRequestFactory,
                nodeServer);

            Console.WriteLine("bootstrapping node network...");
            boostrapper.Bootstrap(myConnectionInfo);
            Console.WriteLine($"{MinNetworkSize} nodes in network! bootstrapping complete");

            if (nodeConfig.IsMiningNode)
            {
                Console.WriteLine("starting miner...");
                miner.Start();

                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("Press any key to quit");
                Console.ReadKey();
            }
            else
            {
                votingBooth.LaunchBooth();
            }
        }
Esempio n. 9
0
 public LevelManager(BlockFactory blockFactory, AsyncProcessor asyncProcessor, GameSettings gameSettings)
 {
     _blockFactory   = blockFactory;
     _asyncProcessor = asyncProcessor;
     _gameSettings   = gameSettings;
 }
Esempio n. 10
0
        public override void PlaceBlock(Level world, Player player, BlockCoordinates blockCoordinates, BlockFace face, Vector3 faceCoords)
        {
            ItemBlock itemBlock = new ItemBlock(BlockFactory.GetBlockById(141));

            itemBlock.PlaceBlock(world, player, blockCoordinates, face, faceCoords);
        }
Esempio n. 11
0
        public override void HandleMcpeStartGame(McpeStartGame message)
        {
            Client.EntityId        = message.runtimeEntityId;
            Client.NetworkEntityId = message.entityIdSelf;
            Client.SpawnPoint      = message.spawn;
            Client.CurrentLocation = new PlayerLocation(Client.SpawnPoint, message.rotation.X, message.rotation.X, message.rotation.Y);

            BlockPalette blockPalette = message.blockPalette;

            Client.BlockPalette = blockPalette;

            Log.Warn($"Got position from startgame packet: {Client.CurrentLocation}");


            //var fileNameBlockstates = Path.GetTempPath() + "blockstates_" + Guid.NewGuid() + ".json";
            var fileNameItemstates = Path.GetTempPath() + "itemstates_" + Guid.NewGuid() + ".json";

            File.WriteAllText(fileNameItemstates, JsonConvert.SerializeObject(message.itemstates));

            string fileName = Path.GetTempPath() + "MissingBlocks_" + Guid.NewGuid() + ".txt";

            using (FileStream file = File.OpenWrite(fileName))
            {
                var writer = new IndentedTextWriter(new StreamWriter(file));

                Log.Warn($"Directory:\n{Path.GetTempPath()}");
                Log.Warn($"Filename:\n{fileName}");

                writer.WriteLine($"namespace MiNET.Blocks");
                writer.WriteLine($"{{");
                writer.Indent++;

                var blocks = new List <(int, string)>();

                foreach (IGrouping <string, BlockStateContainer> blockstateGrouping in blockPalette.OrderBy(record => record.Name).ThenBy(record => record.Data).GroupBy(record => record.Name))
                {
                    var currentBlockState = blockstateGrouping.First();
                    var defaultBlockState = blockstateGrouping.FirstOrDefault(bs => bs.Data == 0);

                    Log.Debug($"{currentBlockState.RuntimeId}, {currentBlockState.Name}, {currentBlockState.Data}");
                    Block blockById     = BlockFactory.GetBlockById(currentBlockState.Id);
                    bool  existingBlock = blockById.GetType() != typeof(Block) && !blockById.IsGenerated;
                    int   id            = existingBlock ? currentBlockState.Id : -1;

                    string blockClassName = CodeName(currentBlockState.Name.Replace("minecraft:", ""), true);

                    blocks.Add((blockById.Id, blockClassName));
                    writer.WriteLineNoTabs($"");

                    writer.WriteLine($"public partial class {blockClassName} {(existingBlock ? "" : ": Block")} // {blockById.Id} typeof={blockById.GetType().Name}");
                    writer.WriteLine($"{{");
                    writer.Indent++;

                    var bits = new List <BlockStateByte>();
                    foreach (var state in blockstateGrouping.First().States)
                    {
                        var q = blockstateGrouping.SelectMany(c => c.States);

                        // If this is on base, skip this property. We need this to implement common functionality.
                        Type baseType     = blockById.GetType().BaseType;
                        bool propOverride = baseType != null &&
                                            ("Block" != baseType.Name &&
                                             baseType.GetProperty(CodeName(state.Name, true)) != null);

                        switch (state)
                        {
                        case BlockStateByte blockStateByte:
                        {
                            var  values     = q.Where(s => s.Name == state.Name).Select(d => ((BlockStateByte)d).Value).Distinct().OrderBy(s => s).ToList();
                            byte defaultVal = ((BlockStateByte)defaultBlockState?.States.First(s => s.Name == state.Name))?.Value ?? 0;
                            if (values.Min() == 0 && values.Max() == 1)
                            {
                                bits.Add(blockStateByte);
                                writer.Write($"[StateBit] ");
                                writer.WriteLine($"public {(propOverride ? "override" : "")} bool {CodeName(state.Name, true)} {{ get; set; }} = {(defaultVal == 1 ? "true" : "false")};");
                            }
                            else
                            {
                                writer.Write($"[StateRange({values.Min()}, {values.Max()})] ");
                                writer.WriteLine($"public {(propOverride ? "override" : "")} byte {CodeName(state.Name, true)} {{ get; set; }} = {defaultVal};");
                            }
                            break;
                        }

                        case BlockStateInt blockStateInt:
                        {
                            var values     = q.Where(s => s.Name == state.Name).Select(d => ((BlockStateInt)d).Value).Distinct().OrderBy(s => s).ToList();
                            int defaultVal = ((BlockStateInt)defaultBlockState?.States.First(s => s.Name == state.Name))?.Value ?? 0;
                            writer.Write($"[StateRange({values.Min()}, {values.Max()})] ");
                            writer.WriteLine($"public {(propOverride ? "override" : "")} int {CodeName(state.Name, true)} {{ get; set; }} = {defaultVal};");
                            break;
                        }

                        case BlockStateString blockStateString:
                        {
                            var    values     = q.Where(s => s.Name == state.Name).Select(d => ((BlockStateString)d).Value).Distinct().ToList();
                            string defaultVal = ((BlockStateString)defaultBlockState?.States.First(s => s.Name == state.Name))?.Value ?? "";
                            if (values.Count > 1)
                            {
                                writer.WriteLine($"[StateEnum({string.Join(',', values.Select(v => $"\"{v}\""))})]");
                            }
                            writer.WriteLine($"public {(propOverride ? "override" : "")} string {CodeName(state.Name, true)} {{ get; set; }} = \"{defaultVal}\";");
                            break;
                        }

                        default:
                            throw new ArgumentOutOfRangeException(nameof(state));
                        }
                    }

                    if (id == -1 || blockById.IsGenerated)
                    {
                        writer.WriteLine($"");

                        writer.WriteLine($"public {blockClassName}() : base({currentBlockState.Id})");
                        writer.WriteLine($"{{");
                        writer.Indent++;
                        writer.WriteLine($"IsGenerated = true;");
                        writer.Indent--;
                        writer.WriteLine($"}}");
                    }

                    writer.WriteLineNoTabs($"");
                    writer.WriteLine($"public override void SetState(List<IBlockState> states)");
                    writer.WriteLine($"{{");
                    writer.Indent++;
                    writer.WriteLine($"foreach (var state in states)");
                    writer.WriteLine($"{{");
                    writer.Indent++;
                    writer.WriteLine($"switch(state)");
                    writer.WriteLine($"{{");
                    writer.Indent++;

                    foreach (var state in blockstateGrouping.First().States)
                    {
                        writer.WriteLine($"case {state.GetType().Name} s when s.Name == \"{state.Name}\":");
                        writer.Indent++;
                        writer.WriteLine($"{CodeName(state.Name, true)} = {(bits.Contains(state) ? "Convert.ToBoolean(s.Value)" : "s.Value")};");
                        writer.WriteLine($"break;");
                        writer.Indent--;
                    }

                    writer.Indent--;
                    writer.WriteLine($"}} // switch");
                    writer.Indent--;
                    writer.WriteLine($"}} // foreach");
                    writer.Indent--;
                    writer.WriteLine($"}} // method");

                    writer.WriteLineNoTabs($"");
                    writer.WriteLine($"public override BlockStateContainer GetState()");
                    writer.WriteLine($"{{");
                    writer.Indent++;
                    writer.WriteLine($"var record = new BlockStateContainer();");
                    writer.WriteLine($"record.Name = \"{blockstateGrouping.First().Name}\";");
                    writer.WriteLine($"record.Id = {blockstateGrouping.First().Id};");
                    foreach (var state in blockstateGrouping.First().States)
                    {
                        string propName = CodeName(state.Name, true);
                        writer.WriteLine($"record.States.Add(new {state.GetType().Name} {{Name = \"{state.Name}\", Value = {(bits.Contains(state) ? $"Convert.ToByte({propName})" : propName)}}});");
                    }
                    writer.WriteLine($"return record;");
                    writer.Indent--;
                    writer.WriteLine($"}} // method");

                    //writer.WriteLine($"");

                    //writer.WriteLine($"public byte GetMetadataFromState()");
                    //writer.WriteLine($"{{");
                    //writer.Indent++;

                    //writer.WriteLine($"switch(this)");
                    //writer.WriteLine($"{{");
                    //writer.Indent++;


                    //i = 0;
                    //foreach (var record in message.BlockPalette.Where(b => b.Id == enumerator.Current.Id).OrderBy(b => b.Data))
                    //{
                    //	//case { } b when b.ButtonPressedBit == 0 && b.FacingDirection == 0:
                    //	//	return 0;

                    //	writer.Write($"case {{ }} b when true");
                    //	string retVal = "";
                    //	foreach (var state in record.States.OrderBy(s => s.Name).ThenBy(s => s.Value))
                    //	{
                    //		if (state.Type == (byte) NbtTagType.Byte)
                    //		{
                    //			writer.Write($" && b.{Client.CodeName(state.Name, true)} == {state.Value}");
                    //		}
                    //		else if (state.Type == (byte) NbtTagType.Int)
                    //		{
                    //			writer.Write($" && b.{Client.CodeName(state.Name, true)} == {state.Value}");
                    //		}
                    //		else if (state.Type == (byte) NbtTagType.String)
                    //		{
                    //			writer.Write($" && b.{Client.CodeName(state.Name, true)} == \"{state.Value}\"");
                    //		}
                    //	}
                    //	writer.WriteLine($":");

                    //	writer.Indent++;
                    //	writer.WriteLine($"return { i++ };");
                    //	writer.Indent--;
                    //}

                    //writer.Indent--;
                    //writer.WriteLine($"}} // switch");

                    //writer.WriteLine($"throw new ArithmeticException(\"Invalid state. Unable to convert state to valid metadata\");");

                    //writer.Indent--;
                    //writer.WriteLine($"}} // method");

                    writer.Indent--;
                    writer.WriteLine($"}} // class");
                }

                writer.Indent--;
                writer.WriteLine($"}}");

                foreach (var block in blocks.OrderBy(tuple => tuple.Item1))
                {
                    writer.WriteLine($"else if (blockId == {block.Item1}) block = new {block.Item2}();");
                }

                writer.Flush();
            }

            //			Log.Debug($@"
            //StartGame:
            //	entityId: {message.entityIdSelf}
            //	runtimeEntityId: {message.runtimeEntityId}
            //	spawn: {message.spawn}
            //	unknown1: {message.unknown1}
            //	dimension: {message.dimension}
            //	generator: {message.generator}
            //	gamemode: {message.gamemode}
            //	difficulty: {message.difficulty}
            //	hasAchievementsDisabled: {message.hasAchievementsDisabled}
            //	dayCycleStopTime: {message.dayCycleStopTime}
            //	eduMode: {message.eduMode}
            //	rainLevel: {message.rainLevel}
            //	lightnigLevel: {message.lightnigLevel}
            //	enableCommands: {message.enableCommands}
            //	isTexturepacksRequired: {message.isTexturepacksRequired}
            //	secret: {message.levelId}
            //	worldName: {message.worldName}
            //");

            LogGamerules(message.gamerules);

            Client.LevelInfo.LevelName = "Default";
            Client.LevelInfo.Version   = 19133;
            Client.LevelInfo.GameType  = message.gamemode;

            //ClientUtils.SaveLevel(_level);

            {
                var packet = McpeRequestChunkRadius.CreateObject();
                Client.ChunkRadius = 5;
                packet.chunkRadius = Client.ChunkRadius;

                Client.SendPacket(packet);
            }
        }
Esempio n. 12
0
        public void EncodePalettedChunk()
        {
            //PaletteChunk chunk = new PaletteChunk();
            //chunk.GetBytes()

            uint waste = BlockFactory.GetRuntimeId(0, 0);

            int[] legacyToRuntimeId = BlockFactory.LegacyToRuntimeId;

            short[] blocks = new short[4096];
            Random  random = new Random();

            for (int i = 0; i < blocks.Length; i++)
            {
                blocks[i] = (short)random.Next(8);
            }
            //blocks[0] = 0b000;
            //blocks[1] = 0b111;
            //blocks[2] = 0b111;
            //blocks[3] = 0b111;
            //blocks[4] = 0b111;
            //blocks[5] = 0b111;
            //blocks[6] = 0b111;
            //blocks[7] = 0b001;
            //blocks[8] = 0b010;
            //blocks[9] = 0b011;
            //blocks[10] = 0b100;
            //blocks[11] = 0b101;
            byte[] metas = new byte[4096];

            int count = 10_000;
            var sw    = Stopwatch.StartNew();

            for (int c = 0; c < count; c++)
            {
                for (int sc = 0; sc < 8; sc++)
                {
                    var  palette  = new Dictionary <uint, byte>();
                    uint prevHash = uint.MaxValue;
                    for (int i = 0; i < 4096; i++)
                    {
                        uint hash = (uint)blocks[i] << 4 | metas[i];
                        if (hash == prevHash)
                        {
                            continue;
                        }

                        prevHash      = hash;
                        palette[hash] = 0;
                    }

                    // log2(number of entries) => bits needed to store them
                    //Assert.AreEqual(0, Math.Ceiling(Math.Log(1, 2)));
                    //Assert.AreEqual(1, Math.Ceiling(Math.Log(2, 2)));
                    //Assert.AreEqual(2, Math.Ceiling(Math.Log(3, 2)));
                    //Assert.AreEqual(2, Math.Ceiling(Math.Log(4, 2)));
                    //Assert.AreEqual(3, Math.Ceiling(Math.Log(5, 2)));
                    //Assert.AreEqual(3, Math.Ceiling(Math.Log(palette.Count, 2)));
                    //Assert.AreEqual(3, Math.Ceiling(Math.Log(8, 2)));
                    //Assert.AreEqual(4, Math.Ceiling(Math.Log(9, 2)));
                    //Assert.AreEqual(4, Math.Ceiling(Math.Log(16, 2)));
                    //Assert.AreEqual(5, Math.Ceiling(Math.Log(17, 2)));
                    //Assert.AreEqual(5, Math.Ceiling(Math.Log(32, 2)));
                    //Assert.AreEqual(6, Math.Ceiling(Math.Log(33, 2)));
                    //Assert.AreEqual(6, Math.Ceiling(Math.Log(64, 2)));
                    //Assert.AreEqual(7, Math.Ceiling(Math.Log(65, 2)));
                    //Assert.AreEqual(7, Math.Ceiling(Math.Log(128, 2)));
                    //Assert.AreEqual(8, Math.Ceiling(Math.Log(129, 2)));
                    //Assert.AreEqual(8, Math.Ceiling(Math.Log(256, 2)));
                    //Assert.AreEqual(16, Math.Ceiling(Math.Log(ushort.MaxValue, 2)));

                    int bitsPerBlock = (int)Math.Ceiling(Math.Log(palette.Count, 2));

                    switch (bitsPerBlock)
                    {
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                    case 6:
                        //Paletted1 = 1,   // 32 blocks per word
                        //Paletted2 = 2,   // 16 blocks per word
                        //Paletted3 = 3,   // 10 blocks and 2 bits of padding per word
                        //Paletted4 = 4,   // 8 blocks per word
                        //Paletted5 = 5,   // 6 blocks and 2 bits of padding per word
                        //Paletted6 = 6,   // 5 blocks and 2 bits of padding per word
                        break;

                    case 7:
                    case 8:
                        //Paletted8 = 8,  // 4 blocks per word
                        bitsPerBlock = 8;
                        break;

                    case int i when i > 8:
                        //Paletted16 = 16, // 2 blocks per word
                        bitsPerBlock = 16;
                        break;

                    default:
                        break;
                    }

                    int blocksPerWord = (int)Math.Floor(32f / bitsPerBlock);                      // Floor to remove padding bits
                    int wordsPerChunk = (int)Math.Ceiling(4096f / blocksPerWord);

                    Assert.AreEqual(10, blocksPerWord);

                    byte t = 0;
                    foreach (var b in palette.ToArray())
                    {
                        palette[b.Key] = t++;
                    }

                    uint[] indexes = new uint[wordsPerChunk];

                    int position = 0;
                    for (int w = 0; w < wordsPerChunk; w++)
                    {
                        uint word = 0;
                        for (int block = 0; block < blocksPerWord; block++)
                        {
                            if (position >= 4096)
                            {
                                continue;
                            }

                            uint state = palette[(uint)blocks[position] << 4 | metas[position]];
                            word |= state << (bitsPerBlock * block);

                            //string bin = Convert.ToString(word, 2);
                            //bin = new string('0', 32 - bin.Length) + bin;
                            //Console.WriteLine($"{bin}");

                            position++;
                        }
                        indexes[w] = word;
                    }
                }
            }
            Console.WriteLine($"time={sw.ElapsedMilliseconds}");
        }
Esempio n. 13
0
        public void GenerateClassesForBlocks()
        {
            BlockPallet pallet = null;

            var assembly = Assembly.GetAssembly(typeof(Block));

            using (var stream = assembly.GetManifestResourceStream(typeof(Block).Namespace + ".blockstates.json"))
                using (var reader = new StreamReader(stream))
                {
                    pallet = BlockPallet.FromJson(reader.ReadToEnd());
                }

            List <(int, string)> blocks = new List <(int, string)>();

            string fileName = Path.GetTempPath() + "MissingBlocks_" + Guid.NewGuid() + ".txt";

            using (FileStream file = File.OpenWrite(fileName))
            {
                Log.Warn($"Writing new blocks to filename:\n{fileName}");

                IndentedTextWriter writer = new IndentedTextWriter(new StreamWriter(file));

                writer.WriteLine($"namespace MiNET.Blocks");
                writer.WriteLine($"{{");
                writer.Indent++;


                foreach (IGrouping <string, BlockRecord> blockstate in pallet.OrderBy(r => r.Name).ThenBy(r => r.Data).GroupBy(r => r.Name))
                {
                    var enumerator = blockstate.GetEnumerator();
                    enumerator.MoveNext();
                    var value = enumerator.Current;
                    if (value == null)
                    {
                        continue;
                    }
                    Log.Debug($"{value.RuntimeId}, {value.Name}, {value.Data}");
                    int id = BlockFactory.GetBlockIdByName(value.Name.Replace("minecraft:", ""));

                    if (id == 0 && !value.Name.Contains("air"))
                    {
                        string blockName = CodeName(value.Name.Replace("minecraft:", ""), true);

                        blocks.Add((value.Id, blockName));

                        writer.WriteLine($"public class {blockName}: Block");
                        writer.WriteLine($"{{");
                        writer.Indent++;

                        writer.WriteLine($"public {blockName}() : base({value.Id})");
                        writer.WriteLine($"{{");
                        writer.Indent++;

                        writer.WriteLine($"Name = \"{value.Name}\";");

                        do
                        {
                            writer.WriteLine($"// runtime id: {enumerator.Current.RuntimeId} 0x{enumerator.Current.RuntimeId:X}, data: {enumerator.Current.Data}");
                        } while (enumerator.MoveNext());

                        writer.Indent--;
                        writer.WriteLine($"}}");

                        writer.Indent--;
                        writer.WriteLine($"}}");
                    }
                }
                writer.Indent--;
                writer.WriteLine($"}}");

                foreach (var block in blocks.OrderBy(tuple => tuple.Item1))
                {
                    writer.WriteLine($"else if (blockId == {block.Item1}) block = new {block.Item2}();");
                }

                writer.Flush();
            }
        }
Esempio n. 14
0
 public BlockState Get(uint id)
 {
     return(BlockFactory.GetBlockState(id));
 }
        private void UpdateHandItems()
        {
            var s = GetSlot(CurrentSlot + 36);

            Hand = s.ItemId > 255 ? ItemFactory.GetItemById(s.ItemId, s.MetaData) : BlockFactory.GetBlockById((ushort)s.ItemId, s.MetaData);
        }
Esempio n. 16
0
 public ItemFrame() : base("minecraft:frame", 389)
 {
     Block = BlockFactory.GetBlockById(199);
 }
Esempio n. 17
0
        private void ErosionIteration(int inbrushSize, int erodeFaces, BlockBuffer current, BlockBuffer target)
        {
            double brushSizeSquared         = inbrushSize * inbrushSize;
            int    brushSize                = inbrushSize + 1;
            Dictionary <int, int> frequency = new Dictionary <int, int>();

            for (int x = -brushSize; x <= brushSize; x++)
            {
                for (int y = -brushSize; y <= brushSize; y++)
                {
                    for (int z = -brushSize; z <= brushSize; z++)
                    {
                        BlockCoordinates coord = new BlockCoordinates(x, y, z);
                        target[coord] = (Block)current[coord];

                        if (x * x + y * y + z * z >= brushSizeSquared)
                        {
                            continue;
                        }
                        Block state = current[coord];
                        if (state is Air)
                        {
                            continue;
                        }
                        int total        = 0;
                        int highest      = 1;
                        int highestState = state.Id;
                        frequency.Clear();
                        foreach (var offs in FACES_TO_CHECK)
                        {
                            Block next = current[coord + offs];
                            if (!(next is Air))
                            {
                                continue;
                            }
                            total++;

                            int count;
                            if (!frequency.ContainsKey(next.Id))
                            {
                                count = 1;
                            }
                            else
                            {
                                count = frequency[next.Id];
                                count++;
                            }

                            if (count > highest)
                            {
                                highest      = count;
                                highestState = next.Id;
                            }
                            frequency[next.Id] = count;
                        }
                        if (total > erodeFaces)
                        {
                            target[coord] = BlockFactory.GetBlockById(highestState);
                        }
                    }
                }
            }
        }
Esempio n. 18
0
        public static Item GetItem(short id, short metadata = 0, int count = 1)
        {
            //if (id != 0 && count == 0) return null;

            Item item = null;

            if (CustomItemFactory != null)
            {
                item = CustomItemFactory.GetItem(id, metadata, count);
            }

            if (item != null)
            {
                return(item);
            }

            if (id == 0)
            {
                item = new ItemAir();
            }
            else if (id == 54)
            {
                item = new ItemChest();
            }
            else if (id == 44)
            {
                item = new ItemSlab(id, metadata);
            }
            else if (id == 61)
            {
                item = new ItemFurnace();
            }
            else if (id == 63)
            {
                item = new ItemSign();
            }
            else if (id == 68)
            {
                item = new ItemSign();
            }
            else if (id == 116)
            {
                item = new ItemEnchantingTable();
            }
            else if (id == 158)
            {
                item = new ItemSlab(id, metadata);
            }
            else if (id == 182)
            {
                item = new ItemSlab(id, metadata);
            }
            else if (id == 199)
            {
                item = new ItemItemFrame();
            }
            else if (id == 256)
            {
                item = new ItemIronShovel();
            }
            else if (id == 257)
            {
                item = new ItemIronPickaxe();
            }
            else if (id == 258)
            {
                item = new ItemIronAxe();
            }
            else if (id == 259)
            {
                item = new ItemFlintAndSteel();
            }
            else if (id == 260)
            {
                item = new ItemApple();
            }
            else if (id == 261)
            {
                item = new ItemBow();
            }
            else if (id == 262)
            {
                item = new ItemArrow();
            }
            else if (id == 263)
            {
                item = new ItemCoal();
            }
            else if (id == 267)
            {
                item = new ItemIronSword();
            }
            else if (id == 268)
            {
                item = new ItemWoodenSword();
            }
            else if (id == 269)
            {
                item = new ItemWoodenShovel();
            }
            else if (id == 270)
            {
                item = new ItemWoodenPickaxe();
            }
            else if (id == 271)
            {
                item = new ItemWoodenAxe();
            }
            else if (id == 272)
            {
                item = new ItemStoneSword();
            }
            else if (id == 273)
            {
                item = new ItemStoneShovel();
            }
            else if (id == 274)
            {
                item = new ItemStonePickaxe();
            }
            else if (id == 275)
            {
                item = new ItemStoneAxe();
            }
            else if (id == 276)
            {
                item = new ItemDiamondSword();
            }
            else if (id == 277)
            {
                item = new ItemDiamondShovel();
            }
            else if (id == 278)
            {
                item = new ItemDiamondPickaxe();
            }
            else if (id == 279)
            {
                item = new ItemDiamondAxe();
            }
            else if (id == 280)
            {
                item = new ItemStick();
            }
            else if (id == 283)
            {
                item = new ItemGoldSword();
            }
            else if (id == 284)
            {
                item = new ItemGoldShovel();
            }
            else if (id == 285)
            {
                item = new ItemGoldPickaxe();
            }
            else if (id == 286)
            {
                item = new ItemGoldAxe();
            }
            else if (id == 290)
            {
                item = new ItemWoodenHoe();
            }
            else if (id == 291)
            {
                item = new ItemStoneHoe();
            }
            else if (id == 292)
            {
                item = new ItemIronHoe();
            }
            else if (id == 293)
            {
                item = new ItemDiamondHoe();
            }
            else if (id == 294)
            {
                item = new ItemGoldHoe();
            }
            else if (id == 295)
            {
                item = new ItemWheatSeeds();
            }
            else if (id == 296)
            {
                item = new ItemWheat();
            }
            else if (id == 297)
            {
                item = new ItemBread();
            }
            else if (id == 298)
            {
                item = new ItemLeatherHelmet();
            }
            else if (id == 299)
            {
                item = new ItemLeatherChestplate();
            }
            else if (id == 300)
            {
                item = new ItemLeatherLeggings();
            }
            else if (id == 301)
            {
                item = new ItemLeatherBoots();
            }
            else if (id == 302)
            {
                item = new ItemChainmailHelmet();
            }
            else if (id == 303)
            {
                item = new ItemChainmailChestplate();
            }
            else if (id == 304)
            {
                item = new ItemChainmailLeggings();
            }
            else if (id == 305)
            {
                item = new ItemChainmailBoots();
            }
            else if (id == 309)
            {
                item = new ItemIronBoots();
            }
            else if (id == 308)
            {
                item = new ItemIronLeggings();
            }
            else if (id == 307)
            {
                item = new ItemIronChestplate();
            }
            else if (id == 306)
            {
                item = new ItemIronHelmet();
            }
            else if (id == 310)
            {
                item = new ItemDiamondHelmet();
            }
            else if (id == 311)
            {
                item = new ItemDiamondChestplate();
            }
            else if (id == 312)
            {
                item = new ItemDiamondLeggings();
            }
            else if (id == 313)
            {
                item = new ItemDiamondBoots();
            }
            else if (id == 314)
            {
                item = new ItemGoldHelmet();
            }
            else if (id == 315)
            {
                item = new ItemGoldChestplate();
            }
            else if (id == 316)
            {
                item = new ItemGoldLeggings();
            }
            else if (id == 317)
            {
                item = new ItemGoldBoots();
            }
            else if (id == 319)
            {
                item = new ItemRawPorkchop();
            }
            else if (id == 320)
            {
                item = new ItemCookedPorkshop();
            }
            else if (id == 322)
            {
                item = new ItemGoldenApple();
            }
            else if (id == 323)
            {
                item = new ItemSign();
            }
            else if (id == 324)
            {
                item = new ItemWoodenDoor();
            }
            else if (id == 325)
            {
                item = new ItemBucket(metadata);
            }
            else if (id == 331)
            {
                item = new ItemRedstone();
            }
            else if (id == 332)
            {
                item = new ItemSnowball();
            }
            else if (id == 344)
            {
                item = new ItemEgg();
            }
            else if (id == 345)
            {
                item = new ItemCompass();
            }
            else if (id == 351)
            {
                item = new ItemDye();
            }
            else if (id == 352)
            {
                item = new ItemBone();
            }
            else if (id == 355)
            {
                item = new ItemBed();
            }
            else if (id == 357)
            {
                item = new ItemCookie();
            }
            else if (id == 358)
            {
                item = new ItemMap();
            }
            else if (id == 360)
            {
                item = new ItemMelonSlice();
            }
            else if (id == 363)
            {
                item = new ItemBeef();
            }
            else if (id == 364)
            {
                item = new ItemCookedBeef();
            }
            else if (id == 365)
            {
                item = new ItemRawChicken();
            }
            else if (id == 366)
            {
                item = new ItemCookedChicken();
            }
            else if (id == 373)
            {
                item = new ItemPotion(metadata);
            }
            else if (id == 380)
            {
                item = new ItemCauldron();
            }
            else if (id == 383)
            {
                item = new ItemSpawnEgg(metadata);
            }
            else if (id == 391)
            {
                item = new ItemCarrot();
            }
            else if (id == 392)
            {
                item = new ItemPotato();
            }
            else if (id == 393)
            {
                item = new ItemBakedPotato();
            }
            else if (id == 395)
            {
                item = new ItemEmptyMap();
            }
            else if (id == 397)
            {
                item = new ItemMobHead(metadata);
            }
            else if (id == 400)
            {
                item = new ItemPumpkinPie();
            }
            else if (id == 423)
            {
                item = new ItemMuttonRaw();
            }
            else if (id == 424)
            {
                item = new ItemMuttonCooked();
            }
            else if (id == 427)
            {
                item = new ItemSpruceDoor();
            }
            else if (id == 428)
            {
                item = new ItemBirchDoor();
            }
            else if (id == 429)
            {
                item = new ItemJungleDoor();
            }
            else if (id == 430)
            {
                item = new ItemAcaciaDoor();
            }
            else if (id == 431)
            {
                item = new ItemDarkOakDoor();
            }
            else if (id == 444)
            {
                item = new ItemElytra();
            }
            else if (id == 458)
            {
                item = new ItemBeetrootSeeds();
            }
            else if (id <= 255)
            {
                Block block = BlockFactory.GetBlockById((byte)id);
                if (CustomBlockItemFactory == null)
                {
                    item = new ItemBlock(block, metadata);
                }
                else
                {
                    item = CustomBlockItemFactory.GetBlockItem(block, metadata, count);
                }
            }
            else
            {
                item = new Item(id, metadata, count);
            }

            // This might now be a good idea if the constructor changes these
            // properties for custom items.
            item.Metadata = metadata;
            item.Count    = (byte)count;

            return(item);
        }
Esempio n. 19
0
        public ChunkColumn GetChunk(int X, int Z)
        {
            var width = 32;
            var depth = 32;

            var rx = X >> 5;
            var rz = Z >> 5;

            var filePath = Path.Combine(_basePath, string.Format(@"region\r.{0}.{1}.mca", rx, rz));

            if (!File.Exists(filePath))
            {
                return(_backEndGenerator.GenerateChunkColumn(new Vector2(X, Z)));
            }

            using (var regionFile = File.OpenRead(filePath))
            {
                var buffer = new byte[8192];

                regionFile.Read(buffer, 0, 8192);

                var xi = (X % width);
                if (xi < 0)
                {
                    xi += 32;
                }
                var zi = (Z % depth);
                if (zi < 0)
                {
                    zi += 32;
                }
                var tableOffset = (xi + zi * width) * 4;

                regionFile.Seek(tableOffset, SeekOrigin.Begin);

                var offsetBuffer = new byte[4];
                regionFile.Read(offsetBuffer, 0, 3);
                Array.Reverse(offsetBuffer);
                var offset = BitConverter.ToInt32(offsetBuffer, 0) << 4;

                var length = regionFile.ReadByte();

                //if (offset == 0 || length == 0) return _backEndGenerator.GenerateChunkColumn(new Vector2(X, Z));

                if (offset == 0 || length == 0)
                {
                    return(_backEndGenerator.GenerateChunkColumn(new Vector2(X, Z)));
                }

                regionFile.Seek(offset, SeekOrigin.Begin);
                var waste = new byte[4];
                regionFile.Read(waste, 0, 4);
                var compressionMode = regionFile.ReadByte();

                var nbt = new NbtFile();
                nbt.LoadFromStream(regionFile, NbtCompression.ZLib);

                var dataTag = nbt.RootTag["Level"];

                var sections = dataTag["Sections"] as NbtList;

                var chunk = new ChunkColumn
                {
                    X       = X,
                    Z       = Z,
                    BiomeId = dataTag["Biomes"].ByteArrayValue
                };

                for (var 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 (var sectionTag in sections)
                {
                    var sy      = sectionTag["Y"].ByteValue * 16;
                    var blocks  = sectionTag["Blocks"].ByteArrayValue;
                    var data    = sectionTag["Data"].ByteArrayValue;
                    var addTag  = sectionTag["Add"];
                    var adddata = new byte[2048];
                    if (addTag != null)
                    {
                        adddata = addTag.ByteArrayValue;
                    }
                    var blockLight = sectionTag["BlockLight"].ByteArrayValue;
                    var skyLight   = sectionTag["SkyLight"].ByteArrayValue;

                    for (var x = 0; x < 16; x++)
                    {
                        for (var z = 0; z < 16; z++)
                        {
                            for (var y = 0; y < 16; y++)
                            {
                                var yi = sy + y - _waterOffsetY;
                                if (yi < 0 || yi >= 256)
                                {
                                    continue;
                                }

                                var anvilIndex = y * 16 * 16 + z * 16 + x;
                                var blockId    = blocks[anvilIndex] + (Nibble4(adddata, anvilIndex) << 8);


                                var b = BlockFactory.GetBlockById((ushort)blockId);
                                b.Metadata = Nibble4(data, anvilIndex);
                                chunk.SetBlock(x, yi, z, b);
                                chunk.SetBlocklight(x, yi, z, Nibble4(blockLight, anvilIndex));
                                chunk.SetSkylight(x, yi, z, Nibble4(skyLight, anvilIndex));
                            }
                        }
                    }
                }

                var entities     = dataTag["Entities"] as NbtList;
                var tileEntities = dataTag["TileEntities"] as NbtList;

                if (tileEntities != null)
                {
                    foreach (var nbtTag in tileEntities)
                    {
                        var    blockEntityTag = (NbtCompound)nbtTag;
                        string entityId       = blockEntityTag["id"].StringValue;
                        int    x = blockEntityTag["x"].IntValue;
                        int    y = blockEntityTag["y"].IntValue - _waterOffsetY;
                        int    z = blockEntityTag["z"].IntValue;
                        blockEntityTag["y"] = new NbtInt("y", y);

                        TileEntity blockEntity = TileEntityFactory.GetBlockEntityById(entityId);
                        if (blockEntity != null)
                        {
                            blockEntityTag.Name = string.Empty;
                            chunk.SetBlockEntity(new Vector3(x, y, z), blockEntityTag);
                        }
                    }
                }

                var tileTicks = dataTag["TileTicks"] as NbtList;

                chunk.IsDirty = false;
                return(chunk);
            }
        }
Esempio n. 20
0
        public void GeneratePartialBlocksFromBlockstates()
        {
            BlockPalette blockPalette = BlockFactory.BlockPalette;

            string fileName = Path.GetTempPath() + "MissingBlocks_" + Guid.NewGuid() + ".txt";

            using (FileStream file = File.OpenWrite(fileName))
            {
                var blocks = new List <(int, string)>();

                var writer = new IndentedTextWriter(new StreamWriter(file));

                Console.WriteLine($"Directory:\n{Path.GetTempPath()}");
                Console.WriteLine($"Filename:\n{fileName}");
                Log.Warn($"Writing blocks to filename:\n{fileName}");

                writer.WriteLine($"namespace MiNET.Blocks");
                writer.WriteLine($"{{");
                writer.Indent++;

                foreach (IGrouping <string, BlockStateContainer> blockstateGrouping in blockPalette.OrderBy(record => record.Name).ThenBy(record => record.Data).GroupBy(record => record.Name))
                {
                    var currentBlockState = blockstateGrouping.First();
                    var defaultBlockState = blockstateGrouping.FirstOrDefault(bs => bs.Data == 0);

                    Log.Debug($"{currentBlockState.RuntimeId}, {currentBlockState.Name}, {currentBlockState.Data}");
                    Block blockById     = BlockFactory.GetBlockById(currentBlockState.Id);
                    bool  existingBlock = blockById.GetType() != typeof(Block) && !blockById.IsGenerated;
                    int   id            = existingBlock ? currentBlockState.Id : -1;

                    string blockClassName = CodeName(currentBlockState.Name.Replace("minecraft:", ""), true);

                    blocks.Add((blockById.Id, blockClassName));

                    writer.WriteLineNoTabs($"");

                    writer.WriteLine($"public partial class {blockClassName} {(existingBlock ? "" : ": Block")} // {blockById.Id} typeof={blockById.GetType().Name}");
                    writer.WriteLine($"{{");
                    writer.Indent++;

                    var bits = new List <BlockStateByte>();
                    foreach (var state in blockstateGrouping.First().States)
                    {
                        var q = blockstateGrouping.SelectMany(c => c.States);

                        // If this is on base, skip this property. We need this to implement common functionality.
                        Type baseType     = blockById.GetType().BaseType;
                        bool propOverride = baseType != null &&
                                            ("Block" != baseType.Name &&
                                             baseType.GetProperty(CodeName(state.Name, true)) != null);

                        switch (state)
                        {
                        case BlockStateByte blockStateByte:
                        {
                            var  values     = q.Where(s => s.Name == state.Name).Select(d => ((BlockStateByte)d).Value).Distinct().OrderBy(s => s).ToList();
                            byte defaultVal = ((BlockStateByte)defaultBlockState?.States.First(s => s.Name == state.Name))?.Value ?? 0;
                            if (values.Min() == 0 && values.Max() == 1)
                            {
                                bits.Add(blockStateByte);
                                writer.Write($"[StateBit] ");
                                writer.WriteLine($"public {(propOverride ? "override" : "")} bool {CodeName(state.Name, true)} {{ get; set; }} = {(defaultVal == 1 ? "true" : "false")};");
                            }
                            else
                            {
                                writer.Write($"[StateRange({values.Min()}, {values.Max()})] ");
                                writer.WriteLine($"public {(propOverride ? "override" : "")} byte {CodeName(state.Name, true)} {{ get; set; }} = {defaultVal};");
                            }
                            break;
                        }

                        case BlockStateInt blockStateInt:
                        {
                            var values     = q.Where(s => s.Name == state.Name).Select(d => ((BlockStateInt)d).Value).Distinct().OrderBy(s => s).ToList();
                            int defaultVal = ((BlockStateInt)defaultBlockState?.States.First(s => s.Name == state.Name))?.Value ?? 0;
                            writer.Write($"[StateRange({values.Min()}, {values.Max()})] ");
                            writer.WriteLine($"public {(propOverride ? "override" : "")} int {CodeName(state.Name, true)} {{ get; set; }} = {defaultVal};");
                            break;
                        }

                        case BlockStateString blockStateString:
                        {
                            var    values     = q.Where(s => s.Name == state.Name).Select(d => ((BlockStateString)d).Value).Distinct().ToList();
                            string defaultVal = ((BlockStateString)defaultBlockState?.States.First(s => s.Name == state.Name))?.Value ?? "";
                            if (values.Count > 1)
                            {
                                writer.WriteLine($"[StateEnum({string.Join(',', values.Select(v => $"\"{v}\""))})]");
                            }
                            writer.WriteLine($"public {(propOverride ? "override" : "")} string {CodeName(state.Name, true)} {{ get; set; }} = \"{defaultVal}\";");
                            break;
                        }

                        default:
                            throw new ArgumentOutOfRangeException(nameof(state));
                        }
                    }

                    if (id == -1 || blockById.IsGenerated)
                    {
                        writer.WriteLine($"");

                        writer.WriteLine($"public {blockClassName}() : base({currentBlockState.Id})");
                        writer.WriteLine($"{{");
                        writer.Indent++;
                        writer.WriteLine($"IsGenerated = true;");
                        writer.Indent--;
                        writer.WriteLine($"}}");
                    }

                    writer.WriteLineNoTabs($"");
                    writer.WriteLine($"public override void SetState(List<IBlockState> states)");
                    writer.WriteLine($"{{");
                    writer.Indent++;
                    writer.WriteLine($"foreach (var state in states)");
                    writer.WriteLine($"{{");
                    writer.Indent++;
                    writer.WriteLine($"switch(state)");
                    writer.WriteLine($"{{");
                    writer.Indent++;

                    foreach (var state in blockstateGrouping.First().States)
                    {
                        writer.WriteLine($"case {state.GetType().Name} s when s.Name == \"{state.Name}\":");
                        writer.Indent++;
                        writer.WriteLine($"{CodeName(state.Name, true)} = {(bits.Contains(state) ? "Convert.ToBoolean(s.Value)" : "s.Value")};");
                        writer.WriteLine($"break;");
                        writer.Indent--;
                    }

                    writer.Indent--;
                    writer.WriteLine($"}} // switch");
                    writer.Indent--;
                    writer.WriteLine($"}} // foreach");
                    writer.Indent--;
                    writer.WriteLine($"}} // method");

                    writer.WriteLineNoTabs($"");
                    writer.WriteLine($"public override BlockStateContainer GetState()");
                    writer.WriteLine($"{{");
                    writer.Indent++;
                    writer.WriteLine($"var record = new BlockStateContainer();");
                    writer.WriteLine($"record.Name = \"{blockstateGrouping.First().Name}\";");
                    writer.WriteLine($"record.Id = {blockstateGrouping.First().Id};");
                    foreach (var state in blockstateGrouping.First().States)
                    {
                        string propName = CodeName(state.Name, true);
                        writer.WriteLine($"record.States.Add(new {state.GetType().Name} {{Name = \"{state.Name}\", Value = {(bits.Contains(state) ? $"Convert.ToByte({propName})" : propName)}}});");
                    }
                    writer.WriteLine($"return record;");
                    writer.Indent--;
                    writer.WriteLine($"}} // method");

                    //writer.WriteLine($"");

                    //writer.WriteLine($"public byte GetMetadataFromState()");
                    //writer.WriteLine($"{{");
                    //writer.Indent++;

                    //writer.WriteLine($"switch(this)");
                    //writer.WriteLine($"{{");
                    //writer.Indent++;


                    //i = 0;
                    //foreach (var record in message.BlockPalette.Where(b => b.Id == enumerator.Current.Id).OrderBy(b => b.Data))
                    //{
                    //	//case { } b when b.ButtonPressedBit == 0 && b.FacingDirection == 0:
                    //	//	return 0;

                    //	writer.Write($"case {{ }} b when true");
                    //	string retVal = "";
                    //	foreach (var state in record.States.OrderBy(s => s.Name).ThenBy(s => s.Value))
                    //	{
                    //		if (state.Type == (byte) NbtTagType.Byte)
                    //		{
                    //			writer.Write($" && b.{Client.CodeName(state.Name, true)} == {state.Value}");
                    //		}
                    //		else if (state.Type == (byte) NbtTagType.Int)
                    //		{
                    //			writer.Write($" && b.{Client.CodeName(state.Name, true)} == {state.Value}");
                    //		}
                    //		else if (state.Type == (byte) NbtTagType.String)
                    //		{
                    //			writer.Write($" && b.{Client.CodeName(state.Name, true)} == \"{state.Value}\"");
                    //		}
                    //	}
                    //	writer.WriteLine($":");

                    //	writer.Indent++;
                    //	writer.WriteLine($"return { i++ };");
                    //	writer.Indent--;
                    //}

                    //writer.Indent--;
                    //writer.WriteLine($"}} // switch");

                    //writer.WriteLine($"throw new ArithmeticException(\"Invalid state. Unable to convert state to valid metadata\");");

                    //writer.Indent--;
                    //writer.WriteLine($"}} // method");

                    writer.Indent--;
                    writer.WriteLine($"}} // class");
                }

                writer.Indent--;
                writer.WriteLine($"}}");

                foreach (var block in blocks.OrderBy(tuple => tuple.Item1))
                {
                    writer.WriteLine($"else if (blockId == {block.Item1}) block = new {block.Item2}();");
                }

                writer.Flush();
            }
        }
Esempio n. 21
0
        public BiomeProvider()
        {
            //Biomes = BiomeUtils.Biomes.Where(b => b.Terrain != null).ToArray();
            Biomes = new BiomeBase[]
            {
                new BirchForestBiome(),
                new BirchForestHillsBiome(),

                /* new BirchForestHillsMBiome(),
                 * new BirchForestMBiome(),
                 * new ColdTaigaBiome(),
                 * new ColdTaigaHillsBiome(),
                 * new ColdTaigaMBiome(),*/
                new DeepOceanBiome(),
                new DesertBiome(),
                new DesertHillsBiome(),
                //    new DesertMBiome(),
                //   new ExtremeHillsBiome(),
                //    new ExtremeHillsEdgeBiome(),

                /*    new ExtremeHillsMBiome(),
                 *  new ExtremeHillsPlusBiome(),
                 *  new ExtremeHillsPlusMBiome(),
                 *  new FlowerForestBiome(),*/
                new ForestBiome(),
                new ForestHillsBiome(),
                new FrozenOceanBiome(),
                // new IceMountainsBiome(),
                new IcePlainsBiome(),
                // new IcePlainsSpikesBiome(),
                new JungleBiome(),
                new JungleEdgeBiome(),
                //  new JungleEdgeMBiome(),
                new JungleHillsBiome(),

                /*new JungleMBiome(),
                 * new MegaSpruceTaigaBiome(),
                 * new MegaTaigaBiome(),
                 * new MegaTaigaHillsBiome(),*/
                new MesaBiome(),
                //   new MesaBryceBiome(),
                new MesaPlateauBiome(),
                new MesaPlateauFBiome(),
                //   new MesaPlateauFMBiome(),
                //  new MesaPlateauMBiome(),
                new MushroomIslandBiome(),
                new MushroomIslandShoreBiome(),

                new OceanBiome(),

                new PlainsBiome(),
                //    new RedwoodTaigaHillsBiome(),
                //    new RoofedForestBiome(),
                //   new RoofedForestMBiome(),
                new SavannaBiome(),
                //   new SavannaMBiome(),
                new SavannaPlateauBiome(),
                //   new SavannaPlateauMBiome(),
                //   new SunflowerPlainsBiome(),
                new SwamplandBiome(),
                //   new SwamplandMBiome(),
                new TaigaBiome(),
                new TaigaHillsBiome(),
                //  new TaigaMBiome()

                new RiverBiome().SetEdgeBiome(true),
                new FrozenRiverBiome().SetEdgeBiome(true),

                new BeachBiome().SetEdgeBiome(true),
                new ColdBeachBiome().SetEdgeBiome(true),
                new StoneBeachBiome().SetEdgeBiome(true),
            };

            Random rnd = new Random();

            for (int i = 0; i < Biomes.Length; i++)
            {
                var b = Biomes[i];
                if (Biomes[i].Terrain != null && Biomes[i].Surface == null)
                {
                    b.Surface = new SurfaceBase(b.Config, BlockFactory.GetBlockById(b.SurfaceBlock), BlockFactory.GetBlockById(b.SoilBlock));
                }

                if (!b.Color.HasValue)
                {
                    b.Color = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256));
                }

                Biomes[i] = b;
            }

            float minTemp = float.MaxValue;
            float maxTemp = float.MinValue;
            float minRain = float.MaxValue;
            float maxRain = float.MinValue;

            float minHeight = float.MaxValue;
            float maxHeight = float.MinValue;

            for (int i = 0; i < Biomes.Length; i++)
            {
                var biome = Biomes[i];
                var min   = MathF.Min(biome.MinHeight, biome.MaxHeight);
                var max   = MathF.Max(biome.MinHeight, biome.MaxHeight);

                minHeight = Math.Min(minHeight, min);
                maxHeight = Math.Max(maxHeight, max);

                //	min = MathUtils.ConvertRange(-2f, 2f, 0f, 128f, biome.MinHeight);
                //	max = MathUtils.ConvertRange(-2f, 2f, 0f, 128f, biome.MaxHeight);

                biome.MinHeight = min;
                biome.MaxHeight = max;

                if (biome.Temperature < minTemp)
                {
                    minTemp = biome.Temperature;
                }
                if (biome.Temperature > maxTemp)
                {
                    maxTemp = biome.Temperature;
                }
                if (biome.Downfall < minRain)
                {
                    minRain = biome.Downfall;
                }
                if (biome.Downfall > maxRain)
                {
                    maxRain = biome.Downfall;
                }

                Biomes[i] = biome;
            }
            Console.WriteLine($"Temperature (min: {minTemp} max: {maxTemp}) Downfall (min:{minRain} max: {maxRain}) Height (min: {minHeight} max: {maxHeight})");
        }
Esempio n. 22
0
        public void GenesisBlock()
        {
            Block block = BlockFactory.GenesisBlock();

            Assert.IsNotNull(block);
        }
Esempio n. 23
0
        public override void HandleMcpeStartGame(McpeStartGame message)
        {
            Client.EntityId        = message.runtimeEntityId;
            Client.NetworkEntityId = message.entityIdSelf;
            Client.SpawnPoint      = message.spawn;
            Client.CurrentLocation = new PlayerLocation(Client.SpawnPoint, message.unknown1.X, message.unknown1.X, message.unknown1.Y);

            Log.Warn($"Got position from startgame packet: {Client.CurrentLocation}");

            string fileName = Path.GetTempPath() + "MissingBlocks_" + Guid.NewGuid() + ".txt";

            using (FileStream file = File.OpenWrite(fileName))
            {
                Log.Warn($"Writing new blocks to filename:\n{fileName}");

                var legacyIdMap = new Dictionary <string, int>();
                var assembly    = Assembly.GetAssembly(typeof(Block));
                using (Stream stream = assembly.GetManifestResourceStream(typeof(Block).Namespace + ".legacy_id_map.json"))
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        var result = JObject.Parse(reader.ReadToEnd());

                        foreach (var obj in result)
                        {
                            legacyIdMap.Add(obj.Key, (int)obj.Value);
                        }
                    }

                IndentedTextWriter writer = new IndentedTextWriter(new StreamWriter(file));

                writer.WriteLine($"namespace MiNET.Blocks");
                writer.WriteLine($"{{");
                writer.Indent++;

                List <(int, string)> blocks = new List <(int, string)>();

                foreach (IGrouping <string, KeyValuePair <int, Blockstate> > blockstate in message.blockstates.OrderBy(kvp => kvp.Value.Name).ThenBy(kvp => kvp.Value.Data).GroupBy(kvp => kvp.Value.Name))
                {
                    var enumerator = blockstate.GetEnumerator();
                    enumerator.MoveNext();
                    var value = enumerator.Current.Value;
                    if (value == null)
                    {
                        continue;
                    }
                    Log.Debug($"{value.RuntimeId}, {value.Name}, {value.Data}");
                    int id = BlockFactory.GetBlockIdByName(value.Name.Replace("minecraft:", ""));

                    if (id == 0 && !value.Name.Contains("air"))
                    {
                        if (legacyIdMap.TryGetValue(value.Name, out id))
                        {
                            value.Id = id;
                        }


                        string blockName = Client.CodeName(value.Name.Replace("minecraft:", ""), true);

                        blocks.Add((value.Id, blockName));

                        writer.WriteLine($"public class {blockName}: Block");
                        writer.WriteLine($"{{");
                        writer.Indent++;

                        writer.WriteLine($"public {blockName}() : base({value.Id})");
                        writer.WriteLine($"{{");
                        writer.Indent++;
                        writer.WriteLine($"Name = \"{value.Name}\";");

                        do
                        {
                            writer.WriteLine($"// runtime id: {enumerator.Current.Value.RuntimeId} 0x{enumerator.Current.Value.RuntimeId:X}, data: {enumerator.Current.Value.Data}");
                        } while (enumerator.MoveNext());

                        writer.Indent--;
                        writer.WriteLine($"}}");

                        writer.Indent--;
                        writer.WriteLine($"}}");
                    }
                }
                writer.Indent--;
                writer.WriteLine($"}}");

                foreach (var block in blocks.OrderBy(tuple => tuple.Item1))
                {
                    writer.WriteLine($"else if (blockId == {block.Item1}) block = new {block.Item2}();");
                }

                writer.Flush();
            }

            //			Log.Debug($@"
            //StartGame:
            //	entityId: {message.entityIdSelf}
            //	runtimeEntityId: {message.runtimeEntityId}
            //	spawn: {message.spawn}
            //	unknown1: {message.unknown1}
            //	dimension: {message.dimension}
            //	generator: {message.generator}
            //	gamemode: {message.gamemode}
            //	difficulty: {message.difficulty}
            //	hasAchievementsDisabled: {message.hasAchievementsDisabled}
            //	dayCycleStopTime: {message.dayCycleStopTime}
            //	eduMode: {message.eduMode}
            //	rainLevel: {message.rainLevel}
            //	lightnigLevel: {message.lightnigLevel}
            //	enableCommands: {message.enableCommands}
            //	isTexturepacksRequired: {message.isTexturepacksRequired}
            //	secret: {message.levelId}
            //	worldName: {message.worldName}
            //");

            LogGamerules(message.gamerules);


            Client.LevelInfo.LevelName = "Default";
            Client.LevelInfo.Version   = 19133;
            Client.LevelInfo.GameType  = message.gamemode;

            //ClientUtils.SaveLevel(_level);

            {
                var packet = McpeRequestChunkRadius.CreateObject();
                Client.ChunkRadius = 5;
                packet.chunkRadius = Client.ChunkRadius;

                Client.SendPacket(packet);
            }
        }
Esempio n. 24
0
        private static void ReadSection(int yoffset, NbtTag sectionTag, ChunkColumn chunk)
        {
            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 >= 256)
                        {
                            continue;
                        }

                        int anvilIndex = y * 16 * 16 + z * 16 + x;
                        int blockId    = blocks[anvilIndex] + (Nibble4(adddata, anvilIndex) << 8);

                        // Anvil to PE friendly converstion

                        Func <int, byte, byte> dataConverter = (i, b) => b;                        // Default no-op converter
                        if (Convert.ContainsKey(blockId))
                        {
                            dataConverter = Convert[blockId].Item2;
                            blockId       = Convert[blockId].Item1;
                        }
                        else
                        {
                            if (BlockFactory.GetBlockById((byte)blockId).GetType() == typeof(Block))
                            {
                                Log.Warn($"No block implemented for block ID={blockId}, Meta={data}");
                                //blockId = 57;
                            }
                        }

                        chunk.isAllAir = chunk.isAllAir && blockId == 0;
                        if (blockId > 255)
                        {
                            Log.Warn($"Failed mapping for block ID={blockId}, Meta={data}");
                            blockId = 41;
                        }

                        //if (yi == 127 && blockId != 0) blockId = 30;
                        if (yi == 0 && (blockId == 8 || blockId == 9))
                        {
                            blockId = 7;
                        }

                        chunk.SetBlock(x, yi, z, (byte)blockId);
                        byte metadata = Nibble4(data, anvilIndex);
                        metadata = dataConverter(blockId, metadata);

                        chunk.SetMetadata(x, yi, z, metadata);
                        chunk.SetBlocklight(x, yi, z, Nibble4(blockLight, anvilIndex));
                        chunk.SetSkylight(x, yi, z, Nibble4(skyLight, anvilIndex));

                        var block = BlockFactory.GetBlockById(chunk.GetBlock(x, yi, z));
                        if (block is BlockStairs || block is StoneSlab || block is WoodSlab)
                        {
                            chunk.SetSkylight(x, yi, z, 0xff);
                        }

                        if (blockId == 43 && chunk.GetMetadata(x, yi, z) == 7)
                        {
                            chunk.SetMetadata(x, yi, z, 6);
                        }
                        else if (blockId == 44 && chunk.GetMetadata(x, yi, z) == 7)
                        {
                            chunk.SetMetadata(x, yi, z, 6);
                        }
                        else if (blockId == 44 && chunk.GetMetadata(x, yi, z) == 15)
                        {
                            chunk.SetMetadata(x, yi, z, 14);
                        }
                        else if (blockId == 3 && chunk.GetMetadata(x, yi, z) == 1)
                        {
                            // Dirt Course => (Grass Path)
                            chunk.SetBlock(x, yi, z, 198);
                            chunk.SetMetadata(x, yi, z, 0);
                        }
                        else if (blockId == 3 && chunk.GetMetadata(x, yi, z) == 2)
                        {
                            // Dirt Podzol => (Podzol)
                            chunk.SetBlock(x, yi, z, 243);
                            chunk.SetMetadata(x, yi, z, 0);
                        }
                    }
                }
            }
        }
Esempio n. 25
0
 public ItemFrame() : base(389)
 {
     Block = BlockFactory.GetBlockById(199);
 }
Esempio n. 26
0
        public static Item GetItem(short id, short metadata = 0, int count = 1)
        {
            Item item = null;

            if (CustomItemFactory != null)
            {
                item = CustomItemFactory.GetItem(id, metadata, count);
            }

            if (item != null)
            {
                return(item);
            }

            if (id == 0)
            {
                item = new ItemAir();
            }
            else if (id == 256)
            {
                item = new ItemIronShovel();
            }
            else if (id == 257)
            {
                item = new ItemIronPickaxe();
            }
            else if (id == 258)
            {
                item = new ItemIronAxe();
            }
            else if (id == 259)
            {
                item = new ItemFlintAndSteel();
            }
            else if (id == 260)
            {
                item = new ItemApple();
            }
            else if (id == 261)
            {
                item = new ItemBow();
            }
            else if (id == 262)
            {
                item = new ItemArrow();
            }
            else if (id == 263)
            {
                item = new ItemCoal();
            }
            else if (id == 264)
            {
                item = new ItemDiamond();
            }
            else if (id == 265)
            {
                item = new ItemIronIngot();
            }
            else if (id == 266)
            {
                item = new ItemGoldIngot();
            }
            else if (id == 267)
            {
                item = new ItemIronSword();
            }
            else if (id == 268)
            {
                item = new ItemWoodenSword();
            }
            else if (id == 269)
            {
                item = new ItemWoodenShovel();
            }
            else if (id == 270)
            {
                item = new ItemWoodenPickaxe();
            }
            else if (id == 271)
            {
                item = new ItemWoodenAxe();
            }
            else if (id == 272)
            {
                item = new ItemStoneSword();
            }
            else if (id == 273)
            {
                item = new ItemStoneShovel();
            }
            else if (id == 274)
            {
                item = new ItemStonePickaxe();
            }
            else if (id == 275)
            {
                item = new ItemStoneAxe();
            }
            else if (id == 276)
            {
                item = new ItemDiamondSword();
            }
            else if (id == 277)
            {
                item = new ItemDiamondShovel();
            }
            else if (id == 278)
            {
                item = new ItemDiamondPickaxe();
            }
            else if (id == 279)
            {
                item = new ItemDiamondAxe();
            }
            else if (id == 280)
            {
                item = new ItemStick();
            }
            else if (id == 283)
            {
                item = new ItemGoldenSword();
            }
            else if (id == 284)
            {
                item = new ItemGoldenShovel();
            }
            else if (id == 285)
            {
                item = new ItemGoldenPickaxe();
            }
            else if (id == 286)
            {
                item = new ItemGoldenAxe();
            }
            else if (id == 290)
            {
                item = new ItemWoodenHoe();
            }
            else if (id == 291)
            {
                item = new ItemStoneHoe();
            }
            else if (id == 292)
            {
                item = new ItemIronHoe();
            }
            else if (id == 293)
            {
                item = new ItemDiamondHoe();
            }
            else if (id == 294)
            {
                item = new ItemGoldenHoe();
            }
            else if (id == 295)
            {
                item = new ItemWheatSeeds();
            }
            else if (id == 296)
            {
                item = new ItemWheat();
            }
            else if (id == 297)
            {
                item = new ItemBread();
            }
            else if (id == 298)
            {
                item = new ItemLeatherHelmet();
            }
            else if (id == 299)
            {
                item = new ItemLeatherChestplate();
            }
            else if (id == 300)
            {
                item = new ItemLeatherLeggings();
            }
            else if (id == 301)
            {
                item = new ItemLeatherBoots();
            }
            else if (id == 302)
            {
                item = new ItemChainmailHelmet();
            }
            else if (id == 303)
            {
                item = new ItemChainmailChestplate();
            }
            else if (id == 304)
            {
                item = new ItemChainmailLeggings();
            }
            else if (id == 305)
            {
                item = new ItemChainmailBoots();
            }
            else if (id == 309)
            {
                item = new ItemIronBoots();
            }
            else if (id == 308)
            {
                item = new ItemIronLeggings();
            }
            else if (id == 307)
            {
                item = new ItemIronChestplate();
            }
            else if (id == 306)
            {
                item = new ItemIronHelmet();
            }
            else if (id == 310)
            {
                item = new ItemDiamondHelmet();
            }
            else if (id == 311)
            {
                item = new ItemDiamondChestplate();
            }
            else if (id == 312)
            {
                item = new ItemDiamondLeggings();
            }
            else if (id == 313)
            {
                item = new ItemDiamondBoots();
            }
            else if (id == 314)
            {
                item = new ItemGoldHelmet();
            }
            else if (id == 315)
            {
                item = new ItemGoldChestplate();
            }
            else if (id == 316)
            {
                item = new ItemGoldLeggings();
            }
            else if (id == 317)
            {
                item = new ItemGoldBoots();
            }
            else if (id == 319)
            {
                item = new ItemRawPorkchop();
            }
            else if (id == 320)
            {
                item = new ItemCookedPorkshop();
            }
            else if (id == 321)
            {
                item = new ItemPainting();
            }
            else if (id == 322)
            {
                item = new ItemGoldenApple();
            }
            else if (id == 323)
            {
                item = new ItemSign();
            }
            else if (id == 324)
            {
                item = new ItemWoodenDoor();
            }
            else if (id == 325)
            {
                item = new ItemBucket(metadata);
            }
            else if (id == 329)
            {
                item = new ItemSaddle();
            }
            else if (id == 331)
            {
                item = new ItemRedstone();
            }
            else if (id == 332)
            {
                item = new ItemSnowball();
            }
            else if (id == 333)
            {
                item = new ItemBoat(metadata);
            }
            else if (id == 344)
            {
                item = new ItemEgg();
            }
            else if (id == 345)
            {
                item = new ItemCompass();
            }
            else if (id == 351)
            {
                item = new ItemDye();
            }
            else if (id == 352)
            {
                item = new ItemBone();
            }
            else if (id == 352)
            {
                item = new ItemSugar();
            }
            else if (id == 355)
            {
                item = new ItemBed();
            }
            else if (id == 357)
            {
                item = new ItemCookie();
            }
            else if (id == 358)
            {
                item = new ItemMap();
            }
            else if (id == 359)
            {
                item = new ItemShears();
            }
            else if (id == 360)
            {
                item = new ItemMelonSlice();
            }
            else if (id == 363)
            {
                item = new ItemBeef();
            }
            else if (id == 364)
            {
                item = new ItemCookedBeef();
            }
            else if (id == 365)
            {
                item = new ItemRawChicken();
            }
            else if (id == 366)
            {
                item = new ItemCookedChicken();
            }
            else if (id == 369)
            {
                item = new ItemBlazeRod();
            }
            else if (id == 371)
            {
                item = new ItemGoldNugget();
            }
            else if (id == 373)
            {
                item = new ItemPotion(metadata);
            }
            else if (id == 377)
            {
                item = new ItemBlazePowder();
            }
            else if (id == 380)
            {
                item = new ItemCauldron();
            }
            else if (id == 383)
            {
                item = new ItemMonsterEgg(metadata);
            }
            else if (id == 389)
            {
                item = new ItemFrame();
            }
            else if (id == 391)
            {
                item = new ItemCarrot();
            }
            else if (id == 392)
            {
                item = new ItemPotato();
            }
            else if (id == 393)
            {
                item = new ItemBakedPotato();
            }
            else if (id == 395)
            {
                item = new ItemEmptyMap();
            }
            else if (id == 395)
            {
                item = new ItemGoldenCarrot();
            }
            else if (id == 397)
            {
                item = new ItemMobHead(metadata);
            }
            else if (id == 400)
            {
                item = new ItemPumpkinPie();
            }
            else if (id == 401)
            {
                item = new ItemFireworks();
            }
            else if (id == 416)
            {
                item = new ItemHorseArmorLeather();
            }
            else if (id == 417)
            {
                item = new ItemHorseArmorIron();
            }
            else if (id == 418)
            {
                item = new ItemHorseArmorGold();
            }
            else if (id == 419)
            {
                item = new ItemHorseArmorDiamond();
            }
            else if (id == 423)
            {
                item = new ItemMuttonRaw();
            }
            else if (id == 424)
            {
                item = new ItemMuttonCooked();
            }
            else if (id == 427)
            {
                item = new ItemSpruceDoor();
            }
            else if (id == 428)
            {
                item = new ItemBirchDoor();
            }
            else if (id == 429)
            {
                item = new ItemJungleDoor();
            }
            else if (id == 430)
            {
                item = new ItemAcaciaDoor();
            }
            else if (id == 431)
            {
                item = new ItemDarkOakDoor();
            }
            else if (id == 444)
            {
                item = new ItemElytra();
            }
            else if (id == 446)
            {
                item = new ItemBanner();
            }
            else if (id == 452)
            {
                item = new ItemIronNugget();
            }
            else if (id == 454 && metadata == 0)
            {
                item = new ItemSlate();
            }
            else if (id == 454 && metadata == 1)
            {
                item = new ItemPoster();
            }
            else if (id == 454 && metadata == 2)
            {
                item = new ItemBoard();
            }
            else if (id == 458)
            {
                item = new ItemBeetrootSeeds();
            }
            else if (id == 498)
            {
                item = new ItemCamera(metadata);
            }
            else if (id <= 255)
            {
                int blockId = id;
                if (blockId < 0)
                {
                    blockId = (short)(Math.Abs(id) + 255);                               // hehe
                }
                Block block = BlockFactory.GetBlockById(blockId);
                if (CustomBlockItemFactory == null)
                {
                    item = new ItemBlock(block, metadata);
                }
                else
                {
                    item = CustomBlockItemFactory.GetBlockItem(block, metadata, count);
                }
            }
            else
            {
                item = new Item(id, metadata, count);
            }

            // This might now be a good idea if the constructor changes these
            // properties for custom items.
            item.Metadata = metadata;
            item.Count    = (byte)count;

            return(item);
        }
Esempio n. 27
0
        public override void PlaceBlock(Level world, Player player, BlockCoordinates blockCoordinates, BlockFace face, Vector3 faceCoords)
        {
            byte direction = player.GetDirection();

            var coordinates = GetNewCoordinatesFromFace(blockCoordinates, face);

            // Base block, meta sets orientation
            DoorBase block = (DoorBase)BlockFactory.GetBlockById(_blockId);

            block.Coordinates   = coordinates;
            block.Direction     = direction;
            block.UpperBlockBit = false;

            int x = blockCoordinates.X;
            int y = blockCoordinates.Y;
            int z = blockCoordinates.Z;

            int xd = 0;
            int zd = 0;

            if (direction == 0)
            {
                zd = 1;
            }
            else if (direction == 1)
            {
                xd = -1;
            }
            else if (direction == 2)
            {
                zd = -1;
            }
            else if (direction == 3)
            {
                xd = 1;
            }

            int  i1    = (world.GetBlock(x - xd, y, z - zd).IsSolid ? 1 : 0) + (world.GetBlock(x - xd, y + 1, z - zd).IsSolid ? 1 : 0);
            int  j1    = (world.GetBlock(x + xd, y, z + zd).IsSolid ? 1 : 0) + (world.GetBlock(x + xd, y + 1, z + zd).IsSolid ? 1 : 0);
            bool flag  = world.GetBlock(x - xd, y, z - zd).Id == block.Id || world.GetBlock(x - xd, y + 1, z - zd).Id == block.Id;
            bool flag1 = world.GetBlock(x + xd, y, z + zd).Id == block.Id || world.GetBlock(x + xd, y + 1, z + zd).Id == block.Id;
            bool flag2 = false;

            if (flag && !flag1)
            {
                flag2 = true;
            }
            else if (j1 > i1)
            {
                flag2 = true;
            }

            if (!block.CanPlace(world, player, blockCoordinates, face))
            {
                return;
            }

            block.DoorHingeBit = flag2;

            // The upper door block, meta marks upper and
            // sets orientation based on adjacent blocks
            DoorBase blockUpper = (DoorBase)BlockFactory.GetBlockById(_blockId);

            blockUpper.Coordinates   = coordinates + Level.Up;
            blockUpper.Direction     = direction;
            blockUpper.UpperBlockBit = true;
            blockUpper.DoorHingeBit  = flag2;

            world.SetBlock(block);
            world.SetBlock(blockUpper);

            if (player.GameMode == GameMode.Survival)
            {
                var itemInHand = player.Inventory.GetItemInHand();
                itemInHand.Count--;
                player.Inventory.SetInventorySlot(player.Inventory.InHandSlot, itemInHand);
            }
        }
Esempio n. 28
0
 public override int GetHashCode()
 {
     return(BlockFactory.Hash(this));
 }
Esempio n. 29
0
        public override void HandleMcpeUpdateBlock(McpeUpdateBlock message)
        {
            if (message.storage != 0)
            {
                Log.Warn($"UPDATEBLOCK: Unsupported block storage! {message.storage}");
                return;
            }

            if (_blockStateMap.TryGetValue(message.blockRuntimeId, out var bs))
            {
                IBlockState state = null;

                var result =
                    BlockFactory.RuntimeIdTable.FirstOrDefault(xx =>
                                                               xx.Name == bs.Name);

                if (result != null && result.Id >= 0)
                {
                    var reverseMap = MiNET.Worlds.AnvilWorldProvider.Convert.FirstOrDefault(map =>
                                                                                            map.Value.Item1 == result.Id);

                    var id = result.Id;
                    if (reverseMap.Value != null)
                    {
                        id = reverseMap.Key;
                    }

                    var res = BlockFactory.GetBlockStateID(
                        (int)id,
                        (byte)bs.Data);

                    if (AnvilWorldProvider.BlockStateMapper.TryGetValue(
                            res,
                            out var res2))
                    {
                        var t = BlockFactory.GetBlockState(res2);
                        t = ChunkProcessor.TranslateBlockState(t, id,
                                                               bs.Data);

                        state = t;
                    }
                    else
                    {
                        Log.Info(
                            $"Did not find anvil statemap: {result.Name}");
                        state = ChunkProcessor.TranslateBlockState(
                            BlockFactory.GetBlockState(result.Name),
                            id, bs.Data);
                    }
                }

                if (state == null)
                {
                    state = ChunkProcessor.TranslateBlockState(
                        BlockFactory.GetBlockState(bs.Name),
                        -1, bs.Data);
                }

                if (state != null)
                {
                    BaseClient.WorldReceiver?.SetBlockState(
                        new BlockCoordinates(message.coordinates.X, message.coordinates.Y, message.coordinates.Z),
                        state);
                }

                /*
                 * var result =
                 *      BlockFactory.RuntimeIdTable.FirstOrDefault(xx => xx.Name == bs.Name);
                 *
                 * uint res = 0;
                 * bool ss = false;
                 * if (result != null && result.Id >= 0)
                 * {
                 *      res = BlockFactory.GetBlockStateID((int) result.Id, (byte) bs.Data);
                 *      ss = true;
                 * }
                 *
                 * if (ss && AnvilWorldProvider.BlockStateMapper.TryGetValue(res, out res))
                 * {
                 *      var a = BlockFactory.GetBlockState(res);
                 *      BaseClient.WorldReceiver?.SetBlockState(
                 *              new BlockCoordinates(message.coordinates.X, message.coordinates.Y, message.coordinates.Z),
                 *              a);
                 * }
                 * else
                 * {
                 *
                 *      BaseClient.WorldReceiver?.SetBlockState(
                 *              new BlockCoordinates(message.coordinates.X, message.coordinates.Y, message.coordinates.Z),
                 *              BlockFactory.GetBlockState(bs.Name));
                 * }*/
            }
            else
            {
                Log.Warn($"Received unknown block runtime id.");
            }
        }
Esempio n. 30
0
        //explicit binding looks pretty complex and fragile since I didn't use any of packages.
        public void ConfigureDependencies(DependencyResolver dependencies)
        {
            //configure UI manager windows mapping
            var uiManager = new UIManager(_uiContainer, new Dictionary <string, UIWindowConfiguration>()
            {
                {
                    UIWindow.STRING_MAIN_MENU_WINDOW_ID, new UIWindowConfiguration(
                        () => new MainMenuWindowController(),
                        () => new MainMenuWindowModel(
                            dependencies.Resolve <IGameStateManager>(),
                            dependencies.Resolve <LevelManager>()),
                        _mainMenuViewPrefab
                        )
                },
                {
                    UIWindow.STRING_GAME_WINDOW_ID, new UIWindowConfiguration(
                        () => new GameWindowController(),
                        () => new GameWindowModel(dependencies.Resolve <IInputManager>()),
                        _gameViewPrefab
                        )
                }
            });

            var boardManager = new BoardManager();
            var blockFactory = new BlockFactory(_blockPrefab);
            var brickFactory = new BrickFactory(_brickPrefab, blockFactory);
            var gameManager  = new GameManager(brickFactory, boardManager, () =>
                                               dependencies.Resolve <IGameStateManager>().SetState(GameStateType.MainMenu));//horrible solution but there no time left
            LevelManager levelManager = new LevelManager(_levels,
                                                         new CompositeObserver <LevelData>(brickFactory, _gameLoopManager));

            //configure MonoBehaviour services
            _gameLoopManager.Init(new CompositeObserver <TickPassedParams>(gameManager));
            _inputManager.Init(new CompositeObserver <InputReceivedParams>(gameManager, _gameLoopManager));

            //configure application state machine
            var gameStateManager = new GameStateManager(new[]
            {
                new Tuple <GameStateType, Func <GameState> >(GameStateType.MainMenu,
                                                             () => new GameState(() =>
                {
                    dependencies.Resolve <IUIManager>().OpenWindow(UIWindow.STRING_MAIN_MENU_WINDOW_ID);
                }, () =>
                {
                    dependencies.Resolve <IUIManager>().CloseWindow(UIWindow.STRING_MAIN_MENU_WINDOW_ID);
                })),
                new Tuple <GameStateType, Func <GameState> >(GameStateType.Game,
                                                             () => new GameState(() =>
                {
                    dependencies.Resolve <IUIManager>().OpenWindow(UIWindow.STRING_GAME_WINDOW_ID);
                }, () =>
                {
                    dependencies.Resolve <IUIManager>().CloseWindow(UIWindow.STRING_GAME_WINDOW_ID);
                })),
            }, new CompositeObserver <GameStateType>(_gameLoopManager, gameManager));

            //bind dependencies in order to retrieve them later in runtime
            dependencies.Bind <IGameStateManager>(gameStateManager);
            dependencies.Bind <IUIManager>(uiManager);
            dependencies.Bind(levelManager);
            dependencies.Bind <IInputManager>(_inputManager);
        }
Esempio n. 31
0
        public void GenerateClassesForBlocks()
        {
            Dictionary <int, Blockstate> blockstates = new Dictionary <int, Blockstate>();

            var assembly    = Assembly.GetAssembly(typeof(Block));
            var legacyIdMap = new Dictionary <string, int>();

            using (Stream stream = assembly.GetManifestResourceStream(typeof(Block).Namespace + ".legacy_id_map.json"))
                using (StreamReader reader = new StreamReader(stream))
                {
                    var result = JObject.Parse(reader.ReadToEnd());

                    foreach (var obj in result)
                    {
                        legacyIdMap.Add(obj.Key, (int)obj.Value);
                    }
                }

            using (Stream stream = assembly.GetManifestResourceStream(typeof(Block).Namespace + ".blockstates.json"))
                using (StreamReader reader = new StreamReader(stream))
                {
                    dynamic jsonBlockstates = JArray.Parse(reader.ReadToEnd());

                    int runtimeId = 0;
                    foreach (var obj in jsonBlockstates)
                    {
                        try
                        {
                            var name = (string)obj.name;
                            if (legacyIdMap.TryGetValue(name, out var id))
                            {
                                blockstates.Add(runtimeId, new Blockstate()
                                {
                                    Id = id, Data = (short)obj.data, Name = (string)obj.name, RuntimeId = runtimeId
                                });
                                runtimeId++;
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine($"{obj}");
                            throw;
                        }
                    }
                }


            List <(int, string)> blocks = new List <(int, string)>();

            string fileName = Path.GetTempPath() + "MissingBlocks_" + Guid.NewGuid() + ".txt";

            using (FileStream file = File.OpenWrite(fileName))
            {
                Log.Warn($"Writing new blocks to filename:\n{fileName}");

                IndentedTextWriter writer = new IndentedTextWriter(new StreamWriter(file));

                writer.WriteLine($"namespace MiNET.Blocks");
                writer.WriteLine($"{{");
                writer.Indent++;


                foreach (IGrouping <string, KeyValuePair <int, Blockstate> > blockstate in blockstates.OrderBy(kvp => kvp.Value.Name).ThenBy(kvp => kvp.Value.Data).GroupBy(kvp => kvp.Value.Name))
                {
                    var enumerator = blockstate.GetEnumerator();
                    enumerator.MoveNext();
                    var value = enumerator.Current.Value;
                    if (value == null)
                    {
                        continue;
                    }
                    Log.Debug($"{value.RuntimeId}, {value.Name}, {value.Data}");
                    int id = BlockFactory.GetBlockIdByName(value.Name.Replace("minecraft:", ""));

                    if (id == 0 && !value.Name.Contains("air"))
                    {
                        string blockName = CodeName(value.Name.Replace("minecraft:", ""), true);

                        blocks.Add((value.Id, blockName));

                        writer.WriteLine($"public class {blockName}: Block");
                        writer.WriteLine($"{{");
                        writer.Indent++;

                        writer.WriteLine($"public {blockName}() : base({value.Id})");
                        writer.WriteLine($"{{");
                        writer.Indent++;

                        writer.WriteLine($"Name = \"{value.Name}\";");

                        do
                        {
                            writer.WriteLine($"// runtime id: {enumerator.Current.Value.RuntimeId} 0x{enumerator.Current.Value.RuntimeId:X}, data: {enumerator.Current.Value.Data}");
                        } while (enumerator.MoveNext());

                        writer.Indent--;
                        writer.WriteLine($"}}");

                        writer.Indent--;
                        writer.WriteLine($"}}");
                    }
                }
                writer.Indent--;
                writer.WriteLine($"}}");

                foreach (var block in blocks.OrderBy(tuple => tuple.Item1))
                {
                    writer.WriteLine($"else if (blockId == {block.Item1}) block = new {block.Item2}();");
                }

                writer.Flush();
            }
        }
Esempio n. 32
0
        public override void HandleMcpeStartGame(McpeStartGame message)
        {
            Client.EntityId        = message.runtimeEntityId;
            Client.NetworkEntityId = message.entityIdSelf;
            Client.SpawnPoint      = message.spawn;
            Client.CurrentLocation = new PlayerLocation(Client.SpawnPoint, message.rotation.X, message.rotation.X, message.rotation.Y);

            BlockPalette blockPalette = message.blockPalette;

            Client.BlockPalette = message.blockPalette;

            //var blockPalette = BlockFactory.BlockStates;
            Log.Warn($"Got position from startgame packet: {Client.CurrentLocation}");

            var settings = new JsonSerializerSettings
            {
                PreserveReferencesHandling = PreserveReferencesHandling.Arrays,
                TypeNameHandling           = TypeNameHandling.Auto,
                Formatting           = Formatting.Indented,
                DefaultValueHandling = DefaultValueHandling.Include
            };

            var fileNameItemstates = Path.GetTempPath() + "itemstates_" + Guid.NewGuid() + ".json";

            File.WriteAllText(fileNameItemstates, JsonConvert.SerializeObject(message.itemstates, settings));

            string fileName = Path.GetTempPath() + "MissingBlocks_" + Guid.NewGuid() + ".txt";

            using (FileStream file = File.OpenWrite(fileName))
            {
                var writer = new IndentedTextWriter(new StreamWriter(file));

                Log.Warn($"BlockPalette ({blockPalette.Count}) Filename:\n{fileName}");

                writer.WriteLine($"namespace MiNET.Blocks");
                writer.WriteLine($"{{");
                writer.Indent++;

                var blocks = new List <(int, string)>();

                foreach (IGrouping <string, BlockStateContainer> blockstateGrouping in blockPalette.OrderBy(record => record.Name).ThenBy(record => record.Data).ThenBy(record => record.RuntimeId).GroupBy(record => record.Name))
                {
                    BlockStateContainer currentBlockState = blockstateGrouping.First();
                    Log.Debug($"{currentBlockState.Name}, Id={currentBlockState.Id}");
                    BlockStateContainer defaultBlockState = BlockFactory.GetBlockById(currentBlockState.Id, 0)?.GetGlobalState();
                    if (defaultBlockState == null)
                    {
                        defaultBlockState = blockstateGrouping.FirstOrDefault(bs => bs.Data == 0);
                    }

                    Log.Debug($"{currentBlockState.RuntimeId}, {currentBlockState.Name}, {currentBlockState.Data}");
                    Block blockById     = BlockFactory.GetBlockById(currentBlockState.Id);
                    bool  existingBlock = blockById.GetType() != typeof(Block) && !blockById.IsGenerated;
                    int   id            = existingBlock ? currentBlockState.Id : -1;

                    string blockClassName = CodeName(currentBlockState.Name.Replace("minecraft:", ""), true);

                    blocks.Add((blockById.Id, blockClassName));
                    writer.WriteLineNoTabs($"");

                    writer.WriteLine($"public partial class {blockClassName} // {blockById.Id} typeof={blockById.GetType().Name}");
                    writer.WriteLine($"{{");
                    writer.Indent++;

                    writer.WriteLine($"public override string Name => \"{currentBlockState.Name}\";");
                    writer.WriteLineNoTabs("");

                    var bits = new List <BlockStateByte>();
                    foreach (var state in blockstateGrouping.First().States)
                    {
                        var q = blockstateGrouping.SelectMany(c => c.States);

                        // If this is on base, skip this property. We need this to implement common functionality.
                        Type baseType     = blockById.GetType().BaseType;
                        bool propOverride = baseType != null &&
                                            ("Block" != baseType.Name &&
                                             baseType.GetProperty(CodeName(state.Name, true)) != null);

                        switch (state)
                        {
                        case BlockStateByte blockStateByte:
                        {
                            var  values     = q.Where(s => s.Name == state.Name).Select(d => ((BlockStateByte)d).Value).Distinct().OrderBy(s => s).ToList();
                            byte defaultVal = ((BlockStateByte)defaultBlockState?.States.FirstOrDefault(s => s.Name.Equals(state.Name, StringComparison.OrdinalIgnoreCase)))?.Value ?? 0;
                            if (values.Min() == 0 && values.Max() == 1)
                            {
                                bits.Add(blockStateByte);
                                writer.Write($"[StateBit] ");
                                writer.WriteLine($"public{(propOverride ? " override" : "")} bool {CodeName(state.Name, true)} {{ get; set; }} = {(defaultVal == 1 ? "true" : "false")};");
                            }
                            else
                            {
                                writer.Write($"[StateRange({values.Min()}, {values.Max()})] ");
                                writer.WriteLine($"public{(propOverride ? " override" : "")} byte {CodeName(state.Name, true)} {{ get; set; }} = {defaultVal};");
                            }
                            break;
                        }

                        case BlockStateInt blockStateInt:
                        {
                            var values     = q.Where(s => s.Name == state.Name).Select(d => ((BlockStateInt)d).Value).Distinct().OrderBy(s => s).ToList();
                            int defaultVal = ((BlockStateInt)defaultBlockState?.States.FirstOrDefault(s => s.Name.Equals(state.Name, StringComparison.OrdinalIgnoreCase)))?.Value ?? 0;
                            writer.Write($"[StateRange({values.Min()}, {values.Max()})] ");
                            writer.WriteLine($"public{(propOverride ? " override" : "")} int {CodeName(state.Name, true)} {{ get; set; }} = {defaultVal};");
                            break;
                        }

                        case BlockStateString blockStateString:
                        {
                            var    values     = q.Where(s => s.Name == state.Name).Select(d => ((BlockStateString)d).Value).Distinct().ToList();
                            string defaultVal = ((BlockStateString)defaultBlockState?.States.FirstOrDefault(s => s.Name.Equals(state.Name, StringComparison.OrdinalIgnoreCase)))?.Value ?? "";
                            if (values.Count > 1)
                            {
                                writer.WriteLine($"[StateEnum({string.Join(',', values.Select(v => $"\"{v}\""))})]");
                            }
                            writer.WriteLine($"public{(propOverride ? " override" : "")} string {CodeName(state.Name, true)} {{ get; set; }} = \"{defaultVal}\";");
                            break;
                        }

                        default:
                            throw new ArgumentOutOfRangeException(nameof(state));
                        }
                    }

                    // Constructor

                    //if (id == -1 || blockById.IsGenerated)
                    //{
                    //	writer.WriteLine($"");

                    //	writer.WriteLine($"public {blockClassName}() : base({currentBlockState.Id})");
                    //	writer.WriteLine($"{{");
                    //	writer.Indent++;
                    //	writer.WriteLine($"IsGenerated = true;");
                    //	writer.WriteLine($"SetGenerated();");
                    //	writer.Indent--;
                    //	writer.WriteLine($"}}");
                    //}

                    writer.WriteLineNoTabs($"");
                    writer.WriteLine($"public override void SetState(List<IBlockState> states)");
                    writer.WriteLine($"{{");
                    writer.Indent++;
                    writer.WriteLine($"foreach (var state in states)");
                    writer.WriteLine($"{{");
                    writer.Indent++;
                    writer.WriteLine($"switch(state)");
                    writer.WriteLine($"{{");
                    writer.Indent++;

                    foreach (var state in blockstateGrouping.First().States)
                    {
                        writer.WriteLine($"case {state.GetType().Name} s when s.Name == \"{state.Name}\":");
                        writer.Indent++;
                        writer.WriteLine($"{CodeName(state.Name, true)} = {(bits.Contains(state) ? "Convert.ToBoolean(s.Value)" : "s.Value")};");
                        writer.WriteLine($"break;");
                        writer.Indent--;
                    }

                    writer.Indent--;
                    writer.WriteLine($"}} // switch");
                    writer.Indent--;
                    writer.WriteLine($"}} // foreach");
                    writer.Indent--;
                    writer.WriteLine($"}} // method");

                    writer.WriteLineNoTabs($"");
                    writer.WriteLine($"public override BlockStateContainer GetState()");
                    writer.WriteLine($"{{");
                    writer.Indent++;
                    writer.WriteLine($"var record = new BlockStateContainer();");
                    writer.WriteLine($"record.Name = \"{blockstateGrouping.First().Name}\";");
                    writer.WriteLine($"record.Id = {blockstateGrouping.First().Id};");
                    foreach (var state in blockstateGrouping.First().States)
                    {
                        string propName = CodeName(state.Name, true);
                        writer.WriteLine($"record.States.Add(new {state.GetType().Name} {{Name = \"{state.Name}\", Value = {(bits.Contains(state) ? $"Convert.ToByte({propName})" : propName)}}});");
                    }
                    writer.WriteLine($"return record;");
                    writer.Indent--;
                    writer.WriteLine($"}} // method");
                    writer.Indent--;
                    writer.WriteLine($"}} // class");
                }

                writer.WriteLine();

                foreach (var block in blocks.OrderBy(tuple => tuple.Item1))
                {
                    int clazzId = block.Item1;

                    Block blockById     = BlockFactory.GetBlockById(clazzId);
                    bool  existingBlock = blockById.GetType() != typeof(Block) && !blockById.IsGenerated;
                    if (existingBlock)
                    {
                        continue;
                    }

                    string clazzName = block.Item2;
                    string baseClazz = clazzName.EndsWith("Stairs") ? "BlockStairs" : "Block";
                    baseClazz = clazzName.EndsWith("Slab") && !clazzName.EndsWith("DoubleSlab")? "SlabBase" : baseClazz;
                    writer.WriteLine($"public partial class {clazzName} : {baseClazz} {{ " +
                                     $"public {clazzName}() : base({clazzId}) {{ IsGenerated = true; }} " +
                                     $"}}");
                }

                writer.Indent--;
                writer.WriteLine($"}}");                 // namespace

                //foreach (var block in blocks.OrderBy(tuple => tuple.Item1))
                //{
                //	// 495 => new StrippedCrimsonStem(),
                //	writer.WriteLine($"\t\t\t\t{block.Item1} => new {block.Item2}(),");
                //}

                writer.Flush();
            }

            LogGamerules(message.gamerules);

            Client.LevelInfo.LevelName = "Default";
            Client.LevelInfo.Version   = 19133;
            Client.LevelInfo.GameType  = message.gamemode;

            //ClientUtils.SaveLevel(_level);

            {
                var packet = McpeRequestChunkRadius.CreateObject();
                Client.ChunkRadius = 5;
                packet.chunkRadius = Client.ChunkRadius;

                Client.SendPacket(packet);
            }
        }