Example #1
0
        public int LoadResourcePack(IProgressReceiver progressReceiver, BedrockResourcePack resourcePack, bool replace)
        {
            int imported = 0;
            var total    = resourcePack.EntityModels.Count;

            progressReceiver?.UpdateProgress(0, total, "Loading entity models...");
            foreach (var blockmodel in resourcePack.EntityModels)
            {
                progressReceiver?.UpdateProgress(imported, total, null, blockmodel.Key.ToString());
                var key = blockmodel.Key;

                if (ContainsKey(key))
                {
                    if (replace)
                    {
                        var entry = new EntityModelEntry(blockmodel.Value);
                        Set(key, () => entry);
                    }
                }
                else
                {
                    Register(blockmodel.Key, new EntityModelEntry(blockmodel.Value));
                }

                imported++;
            }

            return(imported);
        }
Example #2
0
        private void LoadTextures(GraphicsDevice device, IProgressReceiver progressReceiver,
                                  McResourcePack resourcePack, bool isFirst)
        {
            progressReceiver.UpdateProgress(0, $"Loading textures: {resourcePack.Manifest?.Name ?? "Unknown"}");

            if (!isFirst)
            {
                Atlas.LoadResourcePackOnTop(device,
                                            ActiveResourcePacks.First().TexturesAsBitmaps.Where(x => x.Key.StartsWith("block")).ToArray(),
                                            resourcePack.TexturesAsBitmaps.Where(x => x.Key.StartsWith("block")).ToArray(),
                                            resourcePack.TextureMetas,
                                            progressReceiver);
            }
            else
            {
                Atlas.GenerateAtlas(device, resourcePack.TexturesAsBitmaps.Where(x => x.Key.StartsWith("block")).ToArray(),
                                    resourcePack.TextureMetas,
                                    progressReceiver);


                //Atlas.Atlas.Save("atlas.png", ImageFormat.Png);
            }

            //  if (!isFirst)
            {
                progressReceiver.UpdateProgress(0, $"Loading UI textures: {resourcePack.Manifest?.Name ?? "Unknown"}");
                Alex.GuiRenderer.LoadResourcePackTextures(resourcePack, progressReceiver);
            }
        }
Example #3
0
        public void LoadBedrockPacks(IProgressReceiver progressReceiver, DirectoryInfo directoryInfo)
        {
            progressReceiver?.UpdateProgress(0, "Loading bedrock .MCPack files...");

            var files = directoryInfo.EnumerateFiles("*.mcpack").ToArray();

            for (var index = 0; index < files.Length; index++)
            {
                var file = files[index];
                progressReceiver?.UpdateProgress(index * (files.Length / 100), "Loading bedrock .MCPack files...", file.Name);

                try
                {
                    using (var archive = new ZipArchive(file.Open(FileMode.Open, FileAccess.Read), ZipArchiveMode.Read))
                    {
                        MCPack pack = new MCPack(archive);
                        Packs.Add(pack);
                    }
                }
                catch (Exception ex)
                {
                    Log.Warn(ex, $"Failed to load bedrock .MCPack file: {file.Name}: {ex}");
                }
            }
        }
Example #4
0
        public static void Load(ResourceManager resourceManager, IProgressReceiver progressReceiver)
        {
            progressReceiver?.UpdateProgress(0, "Loading entity data...");

            Dictionary <long, EntityData> networkIdToData = new Dictionary <long, EntityData>();

            EntityData[] entityObjects = JsonConvert.DeserializeObject <EntityData[]>(ResourceManager.ReadStringResource("Alex.Resources.NewEntities.txt"));

            long unknownId = 0;

            for (int i = 0; i < entityObjects.Length; i++)
            {
                EntityData p            = entityObjects[i];
                var        originalName = p.Name;
                p.OriginalName = originalName;
                p.Name         = p.Name.Replace("_", "");

                long id = 0;
                progressReceiver?.UpdateProgress(i, entityObjects.Length, "Loading entity data...", p.Name);
                if (resourceManager.Registries.Entities.Entries.TryGetValue($"minecraft:{originalName}",
                                                                            out var registryEntry))
                {
                    id = registryEntry.ProtocolId;
                    networkIdToData.TryAdd(registryEntry.ProtocolId, p);
                    //networkIdToData.TryAdd(p.InternalId + 1, p);
                }
                else
                {
                    Log.Warn($"Could not resolve {p.Name}'s protocol id!");
                    id = unknownId++;
                }
            }

            _idToData = networkIdToData;
        }
Example #5
0
        public static void Load(ResourceManager resourceManager, IProgressReceiver progressReceiver)
        {
            progressReceiver?.UpdateProgress(0, "Loading entity data...");

            Dictionary <long, EntityData> networkIdToData = new Dictionary <long, EntityData>();
            Dictionary <EntityType, long> typeToId        = new Dictionary <EntityType, long>();

            EntityData[] entityObjects = JsonConvert.DeserializeObject <EntityData[]>(ResourceManager.ReadStringResource("Alex.Resources.NewEntities.txt"));

            long unknownId = 0;

            for (int i = 0; i < entityObjects.Length; i++)
            {
                EntityData p = entityObjects[i];

                long id = 0;
                progressReceiver?.UpdateProgress(100 * (i / entityObjects.Length), "Loading entity data...", p.Name);
                if (resourceManager.Registries.Entities.Entries.TryGetValue($"minecraft:{p.Name}",
                                                                            out var registryEntry))
                {
                    id = registryEntry.ProtocolId;
                    networkIdToData.TryAdd(registryEntry.ProtocolId, p);
                    //networkIdToData.TryAdd(p.InternalId + 1, p);
                }
                else
                {
                    Log.Warn($"Could not resolve {p.Name}'s protocol id!");
                    id = unknownId++;
                }

                if (EntityType.TryParse(p.Name.Replace("_", ""), true, out EntityType entType))
                {
                    typeToId.TryAdd(entType, id);
                }
                else
                {
                    Log.Warn($"Could not add entity type: {p.Name}");
                }


                /*foreach (var dd in p)
                 *              {
                 *                      EntityData data = new EntityData();
                 *                      data.Id = dd["id"].Value<long>();
                 *                      data.Name = dd["name"].Value<string>();
                 *
                 *                      data.DisplayName = dd["display_name"]?.Value<string>();
                 *
                 *                      if (dd["height"] != null) data.Height = dd["height"].Value<double>();
                 *                      if (dd["width"] != null) data.Width = dd["width"].Value<double>();
                 *
                 *                      networkIdToData.TryAdd(data.Id, data);
                 *              }*/
            }

            _idToData = networkIdToData;
            _typeToId = typeToId;
        }
Example #6
0
        private void LoadRegistries(IProgressReceiver progress)
        {
            progress.UpdateProgress(0, "Loading block model registry...");
            RegistryManager.AddRegistry <BlockModelEntry, Graphics.Models.Blocks.BlockModel>(new BlockModelRegistry());

            progress.UpdateProgress(0, "Loading blockstate registry...");
            RegistryManager.AddRegistry(new RegistryBase <BlockState>("blockstate"));

            progress.UpdateProgress(50, "Loading block registry...");
            RegistryManager.AddRegistry(new BlockRegistry());
        }
Example #7
0
        private void LoadRegistries(IProgressReceiver progress)
        {
            progress.UpdateProgress(0, "Loading block model registry...");
            RegistryManager.AddRegistry <BlockModelEntry, ResourcePackModelBase>(BlockModelRegistry = new BlockModelRegistry());

            progress.UpdateProgress(0, "Loading entity model registry...");
            RegistryManager.AddRegistry <EntityModelEntry, EntityModel>(EntityModelRegistry = new EntityModelRegistry());

            progress.UpdateProgress(0, "Loading blockstate registry...");
            RegistryManager.AddRegistry(new RegistryBase <BlockState>("blockstate"));

            progress.UpdateProgress(50, "Loading block registry...");
            RegistryManager.AddRegistry(new BlockRegistry());
        }
Example #8
0
        public int LoadResourcePack(IProgressReceiver progressReceiver, McResourcePack resourcePack)
        {
            int imported = 0;
            var total    = resourcePack.BlockModels.Count;

            progressReceiver?.UpdateProgress(0, total, "Loading block models...");

            foreach (var blockmodel in resourcePack.BlockModels.Where(x => x.Value.Elements.Length > 0))
            {
                progressReceiver?.UpdateProgress(imported, total, null, blockmodel.Key.ToString());
                Register(blockmodel.Key, new BlockModelEntry(blockmodel.Value));
                imported++;
            }

            return(imported);
        }
Example #9
0
        private McResourcePack LoadResourcePack(IProgressReceiver progressReceiver, Stream stream, bool useModelResolver = false, McResourcePack.McResourcePackPreloadCallback preloadCallback = null)
        {
            Stopwatch sw = Stopwatch.StartNew();

            Log.Info($"Loading resource pack...");

            McResourcePack resourcePack = null;

            using (var archive = new ZipArchive(stream, ZipArchiveMode.Read, false))
            {
                resourcePack = new McResourcePack(archive, preloadCallback, (percentage, file) =>
                {
                    progressReceiver?.UpdateProgress(percentage, null, file);
                });
            }

            sw.Stop();

            Log.Info($"Loaded {resourcePack.BlockModels.Count} block models from resourcepack");
            Log.Info($"Loaded {resourcePack.ItemModels.Count} item models from resourcepack");
            Log.Info($"Resource pack loading took: {sw.ElapsedMilliseconds}ms");

            var language = resourcePack.Languages.Values.FirstOrDefault(x => x.Namespace.Equals("minecraft"));

            if (language != null)
            {
                foreach (var translation in language)
                {
                    ChatParser.TranslationRules[translation.Key] = translation.Value;
                }
            }

            return(resourcePack);
        }
Example #10
0
        private ResourcePack LoadResourcePack(IProgressReceiver progressReceiver, IFilesystem fs, McResourcePack.McResourcePackPreloadCallback preloadCallback = null)
        {
            Stopwatch sw = Stopwatch.StartNew();

            Log.Info($"Loading resource pack ({fs.Name})...");

            try
            {
                var manifest = ResourcePackLib.ResourcePack.GetManifest(fs);

                if (manifest == null || manifest.Type == ResourcePackType.Java)
                {
                    McResourcePack resourcePack = new McResourcePack(
                        fs, preloadCallback, (percentage, file) =>
                    {
                        progressReceiver?.UpdateProgress(percentage, null, file);
                    });

                    sw.Stop();

                    Log.Info($"Loaded {resourcePack.BlockModels.Count} block models from resourcepack");
                    Log.Info($"Loaded {resourcePack.ItemModels.Count} item models from resourcepack");
                    Log.Info($"Loading resourcepack took: {sw.ElapsedMilliseconds}ms");

                    return(resourcePack);
                }
                else if (manifest.Type == ResourcePackType.Bedrock)
                {
                    BedrockResourcePack brp = new BedrockResourcePack(
                        fs, (percentage, file) =>
                    {
                        progressReceiver?.UpdateProgress(percentage, null, file);
                    });

                    return(brp);
                }
            }
            catch (Exception ex)
            {
                Log.Warn(ex, $"Failed to load.");
            }

            return(null);
        }
Example #11
0
        internal static int LoadResources(IRegistryManager registryManager, ResourceManager resources, McResourcePack resourcePack, bool replace,
                                          bool reportMissing = false, IProgressReceiver progressReceiver = null)
        {
            var raw = ResourceManager.ReadStringResource("Alex.Resources.runtimeidtable.json");

            RuntimeIdTable = TableEntry.FromJson(raw);

            var blockEntries = resources.Registries.Blocks.Entries;

            progressReceiver?.UpdateProgress(0, "Loading block registry...");
            for (int i = 0; i < blockEntries.Count; i++)
            {
                var kv = blockEntries.ElementAt(i);

                progressReceiver?.UpdateProgress(i * (100 / blockEntries.Count), "Loading block registry...",
                                                 kv.Key);

                ProtocolIdToBlockName.TryAdd(kv.Value.ProtocolId, kv.Key);
            }

            progressReceiver?.UpdateProgress(0, "Loading block models...");

            if (resourcePack.TryGetBlockModel("cube_all", out ResourcePackLib.Json.Models.Blocks.BlockModel cube))
            {
                cube.Textures["all"] = "no_texture";
                CubeModel            = cube;

                UnknownBlockModel = new ResourcePackBlockModel(resources, new BlockStateModel[]
                {
                    new BlockStateModel()
                    {
                        Model     = CubeModel,
                        ModelName = "Unknown model",
                    }
                });

                AirState.Model = UnknownBlockModel;
            }

            RegisterBuiltinBlocks();

            return(LoadModels(registryManager, resources, resourcePack, replace, reportMissing, progressReceiver));
        }
Example #12
0
        public void LoadProfiles(IProgressReceiver progressReceiver)
        {
            IPlayerProfileService profileService = ServiceProvider.GetRequiredService <IPlayerProfileService>();
            IStorageSystem        storage        = ServiceProvider.GetRequiredService <IStorageSystem>();

            progressReceiver.UpdateProgress(0, StatusMessage);
            if (storage.TryReadJson(ProfilesFile, out ProfilesFileFormat saveFile))
            //if (File.Exists(ProfilesFile))
            {
                progressReceiver.UpdateProgress(50, StatusMessage);

                //	ProfilesFileFormat saveFile = null;
                SavedProfile[] profiles = null;


                progressReceiver.UpdateProgress(50, StatusMessage);

                if (saveFile != null)
                {
                    profiles = saveFile.Profiles;

                    if (!string.IsNullOrWhiteSpace(saveFile.SelectedProfile))
                    {
                        progressReceiver.UpdateProgress(75, StatusMessage);

                        foreach (var profile in profiles)
                        {
                            //profile.Profile.Type = profile.Type;// == ProfileType.Bedrock;
                            if (profile.Profile.Uuid.Equals(saveFile.SelectedProfile))
                            {
                                progressReceiver.UpdateProgress(90, StatusMessage);
                                LastUsedProfile = profile;
                                //profileService.TryAuthenticateAsync(profile.Profile);
                                //profileService.CurrentProfile = profile;
                                break;
                            }
                        }
                    }

                    progressReceiver.UpdateProgress(99, StatusMessage);
                    foreach (var profile in profiles)
                    {
                        Profiles.Add(profile.Profile.Uuid, profile);
                    }
                }
                else
                {
                    Log.Warn($"Profiles file not found.");
                }
            }
            else
            {
                storage.TryWriteJson(ProfilesFile, new ProfilesFileFormat());
                //	File.WriteAllText(ProfilesFile, JsonConvert.SerializeObject(new ProfilesFileFormat(), Formatting.Indented));
            }

            progressReceiver.UpdateProgress(100, StatusMessage);
        }
Example #13
0
        internal static int LoadBlockstates(IRegistryManager registryManager, ResourceManager resources, bool replace,
                                            bool reportMissing = false, IProgressReceiver progressReceiver = null)
        {
            //RuntimeIdTable = TableEntry.FromJson(raw);

            progressReceiver?.UpdateProgress(0, "Loading block models...");

            RegisterBuiltinBlocks();

            return(LoadModels(registryManager, resources, replace, reportMissing, progressReceiver));
        }
Example #14
0
        private void GetTextures(McResourcePack resourcePack,
                                 Dictionary <ResourceLocation, ImageEntry> textures,
                                 IProgressReceiver progressReceiver)
        {
            progressReceiver.UpdateProgress(0, "Processing blockstate textures...");
            int blockstatesProcessed = 0;
            int totalStates          = resourcePack.BlockStates.Count;

            foreach (var kv in resourcePack.BlockStates)
            {
                progressReceiver.UpdateProgress(
                    (int)(100D * ((double)blockstatesProcessed / (double)totalStates)), null, kv.Key);

                var state = kv.Value;

                foreach (var variant in state.Variants)
                {
                    foreach (var va in variant.Value)
                    {
                        ProcessBlockStateModel(resourcePack, textures, va);
                    }
                }


                foreach (var part in state.Parts)
                {
                    if (part.Apply == null)
                    {
                        continue;
                    }

                    foreach (var applied in part.Apply)
                    {
                        ProcessBlockStateModel(resourcePack, textures, applied);
                    }
                }

                blockstatesProcessed++;
                // state.
            }
        }
Example #15
0
        public static byte[] ReadResource(string resource, IProgressReceiver progressReceiver = null)
        {
            progressReceiver?.UpdateProgress(0, null, $"Loading resource: {resource}");
            using (MemoryStream ms = new MemoryStream())
            {
                byte[] buffer = new byte[128];
                using (var reader = Assembly.GetEntryAssembly().GetManifestResourceStream(resource))
                {
                    int count;

                    while ((count = reader.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        ms.Write(buffer, 0, count);
                        progressReceiver?.UpdateProgress((int)ms.Length, (int)reader.Length, null, $"Loading resource: {resource}");
                    }
                }

                return(ms.ToArray());
            }

            //return fontStream.ReadAllBytes();
        }
Example #16
0
        public void GetTextures(McResourcePack resourcePack,
                                Dictionary <ResourceLocation, ImageEntry> textures,
                                IProgressReceiver progressReceiver)
        {
            /*List<ResourceLocation> texturePaths = new List<ResourceLocation>();
             * foreach (var model in resourcePack.BlockModels)
             * {
             *      foreach (var texture in model.Value.Textures)
             *      {
             *              if (!texturePaths.Contains(texture.Value))
             *                      texturePaths.Add(texture.Value);
             *      }
             *     // model.Value.Textures
             * }*/

            int done = 0;
            //    var items = resourcePack.Textures.Where(x => texturePaths.Contains(x.Key)).ToArray();
            var texturePaths = resourcePack.Textures.Where(x => x.Key.Path.Contains("block/")).ToArray();

            foreach (var path in texturePaths)
            {
                progressReceiver?.UpdateProgress(done++, texturePaths.Length, "Resolving textures...", path.ToString());

                if (resourcePack.TryGetBitmap(path.Key, out var texture))
                {
                    TextureMeta meta = null;
                    resourcePack.TryGetTextureMeta(path.Key, out meta);
                    //var entry = new ImageEntry(texture.Value.Value, meta);

                    if (textures.ContainsKey(path.Key))
                    {
                        if (meta != null)
                        {
                            textures[path.Key].Meta = meta;
                        }

                        if (texture != null)
                        {
                            textures[path.Key].Image = texture;
                        }

                        //textures[texture.Key] = entry;
                    }
                    else
                    {
                        textures.Add(path.Key, new ImageEntry(texture, meta));
                    }
                }
            }
        }
Example #17
0
        private void LoadTextures(GraphicsDevice device, IProgressReceiver progressReceiver,
                                  McResourcePack resourcePack, bool isFirst)
        {
            progressReceiver.UpdateProgress(0, $"Loading textures: {resourcePack.Manifest?.Name ?? "Unknown"}");

            if (!isFirst)
            {
                //        Atlas.LoadResourcePackOnTop(device,
                //            ActiveResourcePacks.First(),
                //            resourcePack,
                //           progressReceiver);
            }
            else
            {
                Atlas.LoadResourcePack(device, resourcePack, progressReceiver);
            }

            //  if (!isFirst)
            {
                progressReceiver.UpdateProgress(0, $"Loading UI textures: {resourcePack.Manifest?.Name ?? "Unknown"}");
                Alex.GuiRenderer.LoadResourcePackTextures(resourcePack, progressReceiver);
            }
        }
Example #18
0
        private int Process(ref Bitmap bmp, KeyValuePair <string, Bitmap>[] data, ref int xi, ref int yi, ref int xOffset, ref int yRemaining, int total, int processed, IDictionary <string, TextureInfo> locations, IProgressReceiver progressReceiver)
        {
            int done  = processed;
            var count = 0;

            foreach (var bm in data.OrderByDescending(x => x.Value.Height))
            {
                string key = bm.Key;
                count++;

                double percentage = 100D * ((double)processed / (double)total);
                progressReceiver.UpdateProgress((int)percentage, "Stitching textures...", key);

                var sourceRegion = new System.Drawing.Rectangle(0, 0, bm.Value.Width, bm.Value.Height);
                var targetRegion = new System.Drawing.Rectangle(xi, yi, bm.Value.Width, bm.Value.Height);

                TextureUtils.CopyRegionIntoImage(bm.Value, sourceRegion, ref bmp, targetRegion);

                if (!locations.ContainsKey(key))
                {
                    locations.Add(key, new TextureInfo(new Vector2(xi, yi), bm.Value.Width, bm.Value.Height));
                }

                if (bm.Value.Height > TextureHeight)
                {
                    xOffset    = xi;
                    yRemaining = bm.Value.Height;
                }
                xi += bm.Value.Width;

                if (count == AtlasWidth / TextureWidth)
                {
                    yi         += TextureHeight;
                    xi          = 0;
                    yRemaining -= TextureHeight;

                    count = 0;
                }

                done++;
            }

            return(done);
        }
Example #19
0
        private int Process(ref Image <Rgba32> target, KeyValuePair <ResourceLocation, Image <Rgba32> >[] data, ref int xi, ref int yi, ref int xOffset, ref int yRemaining, int total, int processed, IDictionary <ResourceLocation, TextureInfo> locations, IProgressReceiver progressReceiver, bool animated)
        {
            int done  = processed;
            var count = 0;

            foreach (var bm in data.OrderByDescending(x => x.Value.Height))
            {
                var key = bm.Key;
                count++;

                // double percentage = 100D * ((double)processed / (double)total);
                progressReceiver.UpdateProgress(processed, total, null, key.ToString());

                var sourceRegion = new System.Drawing.Rectangle(0, 0, bm.Value.Width, bm.Value.Height);
                var targetRegion = new System.Drawing.Rectangle(xi, yi, bm.Value.Width, bm.Value.Height);

                TextureUtils.CopyRegionIntoImage(bm.Value, sourceRegion, ref target, targetRegion);

                if (!locations.ContainsKey(key))
                {
                    locations.Add(key, new TextureInfo(new Vector2(target.Width, target.Height), new Vector2(xi, yi), bm.Value.Width / 16, bm.Value.Height / 16, animated, true));
                }

                if (bm.Value.Height > TextureHeight)
                {
                    xOffset    = xi;
                    yRemaining = bm.Value.Height;
                }
                xi += bm.Value.Width;

                if (count == target.Width / TextureWidth)
                {
                    yi         += TextureHeight;
                    xi          = 0;
                    yRemaining -= TextureHeight;

                    count = 0;
                }

                done++;
            }

            return(done);
        }
Example #20
0
        private void InitializeGame(IProgressReceiver progressReceiver)
        {
            progressReceiver.UpdateProgress(0, "Initializing...");
            API.Extensions.Init(GraphicsDevice);
            MCPacketFactory.Load();
            //ConfigureServices();

            var eventDispatcher = Services.GetRequiredService <IEventDispatcher>() as EventDispatcher;

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                eventDispatcher.LoadFrom(assembly);
            }

            //var options = Services.GetService<IOptionsProvider>();

            //	Log.Info($"Loading resources...");
            if (!Resources.CheckResources(GraphicsDevice, progressReceiver,
                                          OnResourcePackPreLoadCompleted))
            {
                Console.WriteLine("Press enter to exit...");
                Console.ReadLine();
                Exit();
                return;
            }

            var profileManager = Services.GetService <ProfileManager>();

            profileManager.LoadProfiles(progressReceiver);

            //GuiRenderer.LoadResourcePack(Resources.ResourcePack, null);
            AnvilWorldProvider.LoadBlockConverter();

            PluginManager.EnablePlugins();

            var storage = Services.GetRequiredService <IStorageSystem>();

            if (storage.TryReadJson("skin.json", out EntityModel model))
            {
                PlayerModel = model;
            }

            if (storage.TryReadBytes("skin.png", out byte[] skinBytes))
Example #21
0
        private McResourcePack LoadResourcePack(IProgressReceiver progressReceiver, IFilesystem fs, McResourcePack.McResourcePackPreloadCallback preloadCallback = null)
        {
            Stopwatch sw = Stopwatch.StartNew();

            Log.Info($"Loading resource pack...");

            McResourcePack resourcePack = null;

            resourcePack = new McResourcePack(
                fs, preloadCallback, (percentage, file) =>
            {
                progressReceiver?.UpdateProgress(percentage, null, file);
            });

            sw.Stop();

            Log.Info($"Loaded {resourcePack.BlockModels.Count} block models from resourcepack");
            Log.Info($"Loaded {resourcePack.ItemModels.Count} item models from resourcepack");
            Log.Info($"Loading resourcepack took: {sw.ElapsedMilliseconds}ms");

            return(resourcePack);
        }
Example #22
0
        public static void Init(IRegistryManager registryManager, ResourceManager resources, IProgressReceiver progressReceiver = null)
        {
            ResourceManager = resources;
            // ResourcePack = resourcePack;

            var otherRaw = ResourceManager.ReadStringResource("Alex.Resources.items3.json");

            SecItemEntries = JsonConvert.DeserializeObject <SecondItemEntry[]>(otherRaw);

            var raw = ResourceManager.ReadStringResource("Alex.Resources.items2.json");

            ItemEntries = JsonConvert.DeserializeObject <ItemEntry[]>(raw);


            var ii     = resources.Registries.Items.Entries;
            var blocks = resources.Registries.Blocks.Entries;

            // LoadModels();

            ConcurrentDictionary <ResourceLocation, Func <Item> > items = new ConcurrentDictionary <ResourceLocation, Func <Item> >();

            // for(int i = 0; i < blocks.Count; i++)
            // List<ResourceLocation> addedCurrently = n
            int done = 0;

            Parallel.ForEach(
                blocks, e =>
            {
                try
                {
                    var entry = e;
                    progressReceiver?.UpdateProgress(done, blocks.Count, $"Processing block items...", entry.Key);

                    Item item;

                    /*if (blockRegistry.TryGet(entry.Key, out var blockState))
                     * {
                     *      item = new ItemBlock(blockState.Value);
                     * }*/
                    var bs = BlockFactory.GetBlockState(entry.Key);

                    if (!(bs.Block is Air) && bs != null)
                    {
                        item = new ItemBlock(bs);
                        //  Log.Info($"Registered block item: {entry.Key}");
                    }
                    else
                    {
                        return;
                    }

                    /*var minetItem = MiNET.Items.ItemFactory.GetItem(entry.Key.Replace("minecraft:", ""));
                     *
                     * if (minetItem != null)
                     * {
                     *      if (Enum.TryParse<ItemType>(minetItem.ItemType.ToString(), out ItemType t))
                     *      {
                     *              item.ItemType = t;
                     *      }
                     *
                     *      SetItemMaterial(item, minetItem.ItemMaterial);
                     *      // item.Material = minetItem.ItemMaterial;
                     *
                     *      item.Meta = minetItem.Metadata;
                     *      item.Id = minetItem.Id;
                     * }*/

                    item.Name        = entry.Key;
                    item.DisplayName = entry.Key;

                    var data = ItemEntries.FirstOrDefault(
                        x => x.name.Equals(entry.Key.Substring(10), StringComparison.OrdinalIgnoreCase));

                    if (data != null)
                    {
                        item.MaxStackSize = data.stackSize;
                        item.DisplayName  = data.displayName;
                    }


                    string ns   = ResourceLocation.DefaultNamespace;
                    string path = entry.Key;

                    if (entry.Key.Contains(':'))
                    {
                        var index = entry.Key.IndexOf(':');
                        ns        = entry.Key.Substring(0, index);
                        path      = entry.Key.Substring(index + 1);
                    }


                    var resourceLocation = new ResourceLocation(ns, $"block/{path}");

                    ResourcePackModelBase model = null;

                    if (!ResourceManager.TryGetBlockModel(resourceLocation, out model))
                    {
                        /*foreach (var it in ResourcePack.ItemModels)
                         * {
                         *      if (it.Key.Path.Equals(key.Path, StringComparison.OrdinalIgnoreCase))
                         *      {
                         *              model = it.Value;
                         *
                         *              break;
                         *      }
                         * }*/
                    }

                    if (model == null)
                    {
                        Log.Debug($"Missing item render definition for block {entry.Key}, using default.");
                        //  model = new ResourcePackItem() {Display = _defaultDisplayElements};
                    }
                    else
                    {
                        item.Renderer = new ItemBlockModelRenderer(bs, model, bs.Block.Animated ? resources.Atlas.GetAtlas(0) : resources.Atlas.GetStillAtlas());
                        item.Renderer.Cache(resources);


                        if (!items.TryAdd(entry.Key, () => { return(item.Clone()); }))
                        {
                            // items[entry.Key] = () => { return item.Clone(); };
                        }
                    }
                }
                finally
                {
                    done++;
                }
            });

            int i = 0;

            Parallel.ForEach(
                ii, (entry) =>
            {
                // var entry = ii.ElementAt(i);
                progressReceiver?.UpdateProgress(i++, ii.Count, $"Processing items...", entry.Key);
                var resourceLocation = new ResourceLocation(entry.Key);
                resourceLocation     = new ResourceLocation(resourceLocation.Namespace, $"item/{resourceLocation.Path}");

                if (items.ContainsKey(resourceLocation))
                {
                    return;
                }

                Item item;

                /*if (blockRegistry.TryGet(entry.Key, out var blockState))
                 * {
                 *      item = new ItemBlock(blockState.Value);
                 * }*/
                /*   if (blocks.ContainsKey(entry.Key) && blockRegistry.TryGet(entry.Key, out var registryEntry))
                 * {
                 *         item = new ItemBlock(registryEntry.Value);
                 * }
                 * else
                 * {*/
                item = new Item();
                // }

                var minetItem = MiNET.Items.ItemFactory.GetItem(resourceLocation.Path);

                if (minetItem != null)
                {
                    if (Enum.TryParse <ItemType>(minetItem.ItemType.ToString(), out ItemType t))
                    {
                        item.ItemType = t;
                    }

                    SetItemMaterial(item, minetItem.ItemMaterial);

                    // item.Material = minetItem.ItemMaterial;
                    item.Meta = minetItem.Metadata;
                    item.Id   = minetItem.Id;
                }

                item.Name        = entry.Key;
                item.DisplayName = entry.Key;

                var data = ItemEntries.FirstOrDefault(
                    x => x.name.Equals(resourceLocation.Path, StringComparison.OrdinalIgnoreCase));

                if (data != null)
                {
                    item.MaxStackSize = data.stackSize;
                    item.DisplayName  = data.displayName;
                }

                ItemModelRenderer renderer;
                if (!ItemRenderers.TryGetValue(resourceLocation, out renderer))
                {
                    if (ResourceManager.TryGetItemModel(resourceLocation, out var model))
                    {
                        renderer = new ItemModelRenderer(model);
                        renderer.Cache(ResourceManager);

                        ItemRenderers.TryAdd(resourceLocation, renderer);
                    }

                    if (renderer == null)
                    {
                        var r = ItemRenderers.FirstOrDefault(
                            x => x.Key.Path.Equals(resourceLocation.Path, StringComparison.OrdinalIgnoreCase));

                        if (r.Value != null)
                        {
                            renderer = r.Value;
                        }
                    }

                    //  if (ResourcePack.ItemModels.TryGetValue(resourceLocation, out var itemModel)) { }
                }

                if (renderer != null)
                {
                    item.Renderer = renderer;
                }

                if (item.Renderer == null)
                {
                    Log.Warn($"Could not find item model renderer for: {resourceLocation}");
                }

                if (!items.TryAdd(resourceLocation, () => { return(item.Clone()); }))
                {
                    //var oldItem = items[resourceLocation];
                    //  items[resourceLocation] = () => { return item.Clone(); };
                }
            });

            Items = new ReadOnlyDictionary <ResourceLocation, Func <Item> >(items);
        }
Example #23
0
        private void InitializeGame(IProgressReceiver progressReceiver)
        {
            progressReceiver.UpdateProgress(0, "Initializing...");

            API.Extensions.Init(GraphicsDevice);
            MCPacketFactory.Load();
            //ConfigureServices();

            //var options = Services.GetService<IOptionsProvider>();

            //	Log.Info($"Loading resources...");
            if (!Resources.CheckResources(GraphicsDevice, progressReceiver, OnResourcePackPreLoadCompleted))
            {
                Console.WriteLine("Press enter to exit...");
                Console.ReadLine();
                Exit();

                return;
            }

            var profileManager = Services.GetService <ProfileManager>();

            profileManager.LoadProfiles(progressReceiver);

            //GuiRenderer.LoadResourcePack(Resources.ResourcePack, null);
            AnvilWorldProvider.LoadBlockConverter();

            PluginManager.EnablePlugins();

            var storage = Services.GetRequiredService <IStorageSystem>();

            if (storage.TryReadString("skin.json", out var str, Encoding.UTF8))
            {
                Dictionary <string, EntityModel> models = new Dictionary <string, EntityModel>();
                BedrockResourcePack.LoadEntityModel(str, models);
                models = BedrockResourcePack.ProcessEntityModels(models);

                if (models.Count > 0)
                {
                    if (models.TryGetValue("geometry.humanoid.custom", out var entityModel) || models.TryGetValue(
                            "geometry.humanoid.customSlim", out entityModel))
                    {
                        PlayerModel = entityModel;
                        Log.Info($"Player model loaded...");
                    }
                }
            }

            if (PlayerModel == null)
            {
                if (ModelFactory.TryGetModel("geometry.humanoid.customSlim", out var model))
                {
                    //model.Name = "geometry.humanoid.customSlim";
                    PlayerModel = model;
                }
            }

            if (PlayerModel != null)
            {
                //Log.Info($"Player model loaded...");
            }

            if (storage.TryReadBytes("skin.png", out byte[] skinBytes))
Example #24
0
        public bool CheckResources(GraphicsDevice device, IProgressReceiver progressReceiver, McResourcePack.McResourcePackPreloadCallback preloadCallback)
        {
            PreloadCallback = preloadCallback;
            byte[] defaultResources;
            byte[] defaultBedrock;

            if (!CheckRequiredPaths(progressReceiver, out defaultResources, out defaultBedrock))
            {
                return(false);
            }

            Log.Info($"Loading registries...");
            progressReceiver?.UpdateProgress(0, "Loading registries...");
            Registries = JsonConvert.DeserializeObject <Registries>(ReadStringResource("Alex.Resources.registries.json"));
            progressReceiver?.UpdateProgress(100, "Loading registries...");

            Log.Info($"Loading vanilla resources...");
            using (MemoryStream stream = new MemoryStream(defaultResources))
            {
                var vanilla = LoadResourcePack(progressReceiver, stream, false, preloadCallback);
                vanilla.Manifest.Name = "Vanilla";

                ActiveResourcePacks.AddFirst(vanilla);
            }

            var bedrockPath = Path.Combine("assets", "bedrock");

            DirectoryInfo directory;

            if (!Storage.TryGetDirectory(bedrockPath, out directory))
            {
                Log.Warn($"The bedrock resources required to play this game are not set-up correctly!");
                Console.ReadLine();
                Environment.Exit(1);
                return(false);
            }

            /*if (!directories.Any(x => x.Name.Equals("models")))
             * {
             *                  Log.Warn($"Please make sure to extract the MC:Bedrock resource pack into \"{directory.FullName}\"");
             *  Console.ReadLine();
             *  Environment.Exit(1);
             *                  return false;
             * }*/

            if (directory.GetFileSystemInfos().Length == 0)
            {
                Log.Info($"Extracting required resources...");
                progressReceiver?.UpdateProgress(50, "Extracting resources...");

                byte[] zipped = defaultBedrock;    //ReadResource("Alex.Resources.resources.zip");
                using (MemoryStream ms = new MemoryStream(zipped))
                {
                    using (ZipArchive archive = new ZipArchive(ms, ZipArchiveMode.Read))
                    {
                        archive.ExtractToDirectory(directory.FullName);
                    }
                }
            }

            var directories = directory.GetDirectories();

            /*  if (!directories.Any(x => x.Name.Equals("definitions")))
             * {
             *                    Log.Warn($"The required definition files are not found. Any questions can be asked on Discord.");
             *    Console.ReadLine();
             *                    Environment.Exit(1);
             *    return false;
             * }*/
            //report(ResourcePack.AsciiFont);

            Log.Info($"Loading bedrock resources...");
            BedrockResourcePack = new BedrockResourcePack(directory);

            EntityFactory.LoadModels(this, device, true, progressReceiver);


            Log.Info($"Loading known entity data...");
            EntityFactory.Load(this, progressReceiver);

            Storage.TryGetDirectory(Path.Combine("assets", "resourcepacks"), out DirectoryInfo root);
            ResourcePackDirectory = root;

            LoadRegistries(progressReceiver);

            LoadResourcePacks(device, progressReceiver, Options.AlexOptions.ResourceOptions.LoadedResourcesPacks.Value);

            ItemFactory.Init(RegistryManager, this, ResourcePack, progressReceiver);

            if (Storage.TryGetDirectory(Path.Combine("assets", "bedrockpacks"), out DirectoryInfo info))
            {
                SkinPackDirectory = info;
                LoadBedrockPacks(progressReceiver, info);
            }
            else
            {
                if (Storage.TryCreateDirectory(Path.Combine("assets", "bedrockpacks")))
                {
                    if (Storage.TryGetDirectory(Path.Combine("assets", "bedrockpacks"), out var dirInfo))
                    {
                        SkinPackDirectory = dirInfo;
                    }
                }
            }

            Options.AlexOptions.ResourceOptions.LoadedResourcesPacks.Bind(ResourcePacksChanged);
            _hasInit = true;

            return(true);
        }
Example #25
0
        public static void Init(IRegistryManager registryManager, ResourceManager resources, McResourcePack resourcePack, IProgressReceiver progressReceiver = null)
        {
            var blockRegistry = registryManager.GetRegistry <Block>();

            ResourceManager = resources;
            ResourcePack    = resourcePack;

            var otherRaw = ResourceManager.ReadStringResource("Alex.Resources.items3.json");

            SecItemEntries = JsonConvert.DeserializeObject <SecondItemEntry[]>(otherRaw);

            var raw = ResourceManager.ReadStringResource("Alex.Resources.items2.json");

            ItemEntries = JsonConvert.DeserializeObject <ItemEntry[]>(raw);


            var ii     = resources.Registries.Items.Entries;
            var blocks = resources.Registries.Blocks.Entries;

            LoadModels();

            Dictionary <ResourceLocation, Func <Item> > items = new Dictionary <ResourceLocation, Func <Item> >();

            for (int i = 0; i < blocks.Count; i++)
            {
                var entry = blocks.ElementAt(i);
                progressReceiver?.UpdateProgress((int)(100D * ((double)i / (double)blocks.Count)), $"Processing block items...", entry.Key);

                Item item;

                /*if (blockRegistry.TryGet(entry.Key, out var blockState))
                 * {
                 *      item = new ItemBlock(blockState.Value);
                 * }*/
                var bs = BlockFactory.GetBlockState(entry.Key);
                if (!(bs.Block is Air))
                {
                    item = new ItemBlock(bs);
                    //  Log.Info($"Registered block item: {entry.Key}");
                }
                else
                {
                    continue;
                }

                var minetItem = MiNET.Items.ItemFactory.GetItem(entry.Key.Replace("minecraft:", ""));
                if (minetItem != null)
                {
                    if (Enum.TryParse <ItemType>(minetItem.ItemType.ToString(), out ItemType t))
                    {
                        item.ItemType = t;
                    }

                    SetItemMaterial(item, minetItem.ItemMaterial);
                    // item.Material = minetItem.ItemMaterial;

                    item.Meta = minetItem.Metadata;
                    item.Id   = minetItem.Id;
                }

                item.Name        = entry.Key;
                item.DisplayName = entry.Key;

                var data = ItemEntries.FirstOrDefault(x =>
                                                      x.name.Equals(entry.Key.Substring(10), StringComparison.InvariantCultureIgnoreCase));
                if (data != null)
                {
                    item.MaxStackSize = data.stackSize;
                    item.DisplayName  = data.displayName;
                }

                string ns   = ResourceLocation.DefaultNamespace;
                string path = entry.Key;
                if (entry.Key.Contains(':'))
                {
                    var index = entry.Key.IndexOf(':');
                    ns   = entry.Key.Substring(0, index);
                    path = entry.Key.Substring(index + 1);
                }

                var key = new ResourceLocation(ns, $"block/{path}");

                ResourcePackModelBase model;
                if (!(ResourcePack.ItemModels.TryGetValue(key, out model)))
                {
                    foreach (var it in ResourcePack.ItemModels)
                    {
                        if (it.Key.Path.Equals(key.Path, StringComparison.InvariantCultureIgnoreCase))
                        {
                            model = it.Value;
                            break;
                        }
                    }
                }

                if (model != null)
                {
                    item.Renderer = new ItemBlockModelRenderer(bs, model, resourcePack, resources);
                    item.Renderer.Cache(resourcePack);
                }
                else
                {
                    Log.Warn($"Could not find block model renderer for: {key.ToString()}");
                }

                items.TryAdd(entry.Key, () =>
                {
                    return(item.Clone());
                });
            }

            for (int i = 0; i < ii.Count; i++)
            {
                var entry = ii.ElementAt(i);
                progressReceiver?.UpdateProgress(i * (100 / ii.Count), $"Processing items...", entry.Key);

                Item item;

                /*if (blockRegistry.TryGet(entry.Key, out var blockState))
                 * {
                 *      item = new ItemBlock(blockState.Value);
                 * }*/
                /*   if (blocks.ContainsKey(entry.Key) && blockRegistry.TryGet(entry.Key, out var registryEntry))
                 * {
                 *         item = new ItemBlock(registryEntry.Value);
                 * }
                 * else
                 * {*/
                item = new Item();
                // }

                var minetItem = MiNET.Items.ItemFactory.GetItem(entry.Key.Replace("minecraft:", ""));
                if (minetItem != null)
                {
                    if (Enum.TryParse <ItemType>(minetItem.ItemType.ToString(), out ItemType t))
                    {
                        item.ItemType = t;
                    }

                    SetItemMaterial(item, minetItem.ItemMaterial);

                    // item.Material = minetItem.ItemMaterial;
                    item.Meta = minetItem.Metadata;
                    item.Id   = minetItem.Id;
                }

                item.Name        = entry.Key;
                item.DisplayName = entry.Key;

                var data = ItemEntries.FirstOrDefault(x =>
                                                      x.name.Equals(entry.Key.Substring(10), StringComparison.InvariantCultureIgnoreCase));
                if (data != null)
                {
                    item.MaxStackSize = data.stackSize;
                    item.DisplayName  = data.displayName;
                }

                string ns   = ResourceLocation.DefaultNamespace;
                string path = entry.Key;
                if (entry.Key.Contains(':'))
                {
                    var index = entry.Key.IndexOf(':');
                    ns   = entry.Key.Substring(0, index);
                    path = entry.Key.Substring(index + 1);
                }

                var key = new ResourceLocation(ns, $"item/{path}");

                foreach (var it in ResourcePack.ItemModels)
                {
                    if (it.Key.Path.Equals(key.Path, StringComparison.InvariantCultureIgnoreCase))
                    {
                        //Log.Info($"Model found: {entry.Key} = {it.Key}");
                        ItemModelRenderer renderer;
                        if (ItemRenderers.TryGetValue(it.Key, out renderer))
                        {
                        }
                        else if (ItemRenderers.TryGetValue(key, out renderer))

                        {
                        }

                        if (renderer != null)
                        {
                            //Log.Debug($"Found renderer for {entry.Key}, textures: {it.Value.Textures.Count}");
                            item.Renderer = renderer;
                            break;
                        }
                    }
                }

                if (item.Renderer == null)
                {
                    Log.Warn($"Could not find item model renderer for: {key.ToString()}");
                }

                items.TryAdd(key, () => { return(item.Clone()); });
            }

            Items = new ReadOnlyDictionary <ResourceLocation, Func <Item> >(items);
        }
Example #26
0
        public bool CheckUpdate(IProgressReceiver progressReceiver, out string path)
        {
            path = String.Empty;
            progressReceiver?.UpdateProgress(0, "Checking for resource updates...");

            using var httpClient = new HttpClient(new HttpClientHandler
            {
                AllowAutoRedirect = true,
            });

            try
            {
                //  string assetsZipSavePath = String.Empty;

                string currentVersion;
                if (TryGetStoredAssetVersion(out currentVersion))
                {
                    path = Path.Combine("assets", $"bedrock-{currentVersion}.zip");

                    if (!Storage.Exists(path))
                    {
                        currentVersion = null;
                    }
                }

                try
                {
                    var zipDownloadHeaders = httpClient.Send(
                        new HttpRequestMessage(HttpMethod.Get, DownloadURL), HttpCompletionOption.ResponseHeadersRead);

                    var fileName = zipDownloadHeaders.Content?.Headers?.ContentDisposition?.FileName
                                   ?? zipDownloadHeaders.RequestMessage?.RequestUri?.LocalPath;

                    var versionMatch = ExtractVersionFromFilename.Match(fileName);

                    if (versionMatch.Success)
                    {
                        var latestVersion = versionMatch.Groups["version"].Value;

                        if (latestVersion != currentVersion ||
                            (!string.IsNullOrWhiteSpace(path) && !Storage.Exists(path)))
                        {
                            if (Storage.Exists(path))
                            {
                                Storage.Delete(path);
                            }

                            progressReceiver?.UpdateProgress(
                                0, "Downloading latest bedrock assets...", "This could take a while...");

                            /* zipDownloadHeaders = await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get,
                             *   zipDownloadHeaders.Headers.Location), HttpCompletionOption.ResponseContentRead);
                             * var content = await zipDownloadHeaders.Content.ReadAsByteArrayAsync();*/
                            Stopwatch sw = new Stopwatch();
                            WebClient wc = new WebClient();

                            wc.DownloadProgressChanged += (sender, args) =>
                            {
                                var downloadSpeed =
                                    $"Download speed: {PlayingState.GetBytesReadable((long) (Convert.ToDouble(args.BytesReceived) / sw.Elapsed.TotalSeconds), 2)}/s";

                                progressReceiver?.UpdateProgress(
                                    args.ProgressPercentage, $"Downloading latest bedrock assets...", downloadSpeed);
                            };

                            bool   complete    = false;
                            string archivePath = string.Empty;
                            wc.DownloadDataCompleted += (sender, args) =>
                            {
                                var content = args.Result;

                                archivePath = Path.Combine("assets", $"bedrock-{latestVersion}.zip");

                                // save locally

                                Storage.TryWriteString(CurrentBedrockVersionStorageKey, latestVersion);

                                Storage.TryWriteBytes(archivePath, content);

                                complete = true;
                            };

                            wc.DownloadDataAsync(zipDownloadHeaders.RequestMessage.RequestUri);
                            sw.Restart();

                            SpinWait.SpinUntil(() => complete);

                            path = archivePath;

                            return(true);
                        }
                    }

                    return(false);
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Failed to download bedrock assets...");

                    return(false);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to fetch latest bedrock assets pack.");
                throw;
            }
        }
Example #27
0
        private static int LoadModels(IRegistryManager registryManager, ResourceManager resources,
                                      McResourcePack resourcePack, bool replace,
                                      bool reportMissing, IProgressReceiver progressReceiver)
        {
            long idCounter          = 0;
            var  blockRegistry      = registryManager.GetRegistry <Block>();
            var  blockModelRegistry = registryManager.GetRegistry <BlockModel>();

            var data           = BlockData.FromJson(ResourceManager.ReadStringResource("Alex.Resources.NewBlocks.json"));
            int total          = data.Count;
            int done           = 0;
            int importCounter  = 0;
            int multipartBased = 0;

            uint c = 0;

            foreach (var entry in data)
            {
                double percentage = 100D * ((double)done / (double)total);
                progressReceiver.UpdateProgress((int)percentage, $"Importing block models...", entry.Key);

                var variantMap   = new BlockStateVariantMapper();
                var defaultState = new BlockState
                {
                    Name          = entry.Key,
                    VariantMapper = variantMap
                };

                if (entry.Value.Properties != null)
                {
                    foreach (var property in entry.Value.Properties)
                    {
                        //	if (property.Key.Equals("waterlogged"))
                        //		continue;

                        defaultState = (BlockState)defaultState.WithPropertyNoResolve(property.Key,
                                                                                      property.Value.FirstOrDefault(), false);
                    }
                }

                foreach (var s in entry.Value.States)
                {
                    var id = s.ID;

                    BlockState variantState = (BlockState)(defaultState).CloneSilent();
                    variantState.ID   = id;
                    variantState.Name = entry.Key;

                    if (s.Properties != null)
                    {
                        foreach (var property in s.Properties)
                        {
                            //if (property.Key.Equals("waterlogged"))
                            //		continue;

                            variantState =
                                (Blocks.State.BlockState)variantState.WithPropertyNoResolve(property.Key,
                                                                                            property.Value, false);
                        }
                    }

                    if (!replace && RegisteredBlockStates.TryGetValue(id, out BlockState st))
                    {
                        Log.Warn(
                            $"Duplicate blockstate id (Existing: {st.Name}[{st.ToString()}] | New: {entry.Key}[{variantState.ToString()}]) ");
                        continue;
                    }


                    var cachedBlockModel = GetOrCacheModel(resources, resourcePack, variantState, id, replace);
                    if (cachedBlockModel == null)
                    {
                        if (reportMissing)
                        {
                            Log.Warn($"Missing blockmodel for blockstate {entry.Key}[{variantState.ToString()}]");
                        }

                        cachedBlockModel = UnknownBlockModel;
                    }

                    if (variantState.IsMultiPart)
                    {
                        multipartBased++;
                    }

                    string displayName = entry.Key;
                    IRegistryEntry <Block> registryEntry;

                    if (!blockRegistry.TryGet(entry.Key, out registryEntry))
                    {
                        registryEntry = new UnknownBlock(id);
                        displayName   = $"(MISSING) {displayName}";

                        registryEntry = registryEntry.WithLocation(entry.Key);                         // = entry.Key;
                    }
                    else
                    {
                        registryEntry = registryEntry.WithLocation(entry.Key);
                    }

                    var block = registryEntry.Value;

                    variantState.Model   = cachedBlockModel;
                    variantState.Default = s.Default;

                    if (string.IsNullOrWhiteSpace(block.DisplayName) ||
                        !block.DisplayName.Contains("minet", StringComparison.InvariantCultureIgnoreCase))
                    {
                        block.DisplayName = displayName;
                    }

                    variantState.Block = block;
                    block.BlockState   = variantState;

                    if (variantMap.TryAdd(variantState))
                    {
                        if (!RegisteredBlockStates.TryAdd(variantState.ID, variantState))
                        {
                            if (replace)
                            {
                                RegisteredBlockStates[variantState.ID] = variantState;
                                importCounter++;
                            }
                            else
                            {
                                Log.Warn(
                                    $"Failed to add blockstate (variant), key already exists! ({variantState.ID} - {variantState.Name})");
                            }
                        }
                        else
                        {
                            importCounter++;
                        }
                    }
                    else
                    {
                        Log.Warn(
                            $"Could not add variant to variant map: {variantState.Name}[{variantState.ToString()}]");
                    }
                }

                if (!BlockStateByName.TryAdd(defaultState.Name, variantMap))
                {
                    if (replace)
                    {
                        BlockStateByName[defaultState.Name] = variantMap;
                    }
                    else
                    {
                        Log.Warn($"Failed to add blockstate, key already exists! ({defaultState.Name})");
                    }
                }

                done++;
            }

            Log.Info($"Got {multipartBased} multi-part blockstate variants!");
            return(importCounter);
        }
Example #28
0
        public static void LoadModels(ResourceManager resourceManager, GraphicsDevice graphics, bool replaceModels, IProgressReceiver progressReceiver = null)
        {
            var entityDefinitions = resourceManager.BedrockResourcePack.EntityDefinitions;
            int done  = 0;
            int total = entityDefinitions.Count;

            foreach (var def in entityDefinitions)
            {
                double percentage = 100D * ((double)done / (double)total);
                progressReceiver?.UpdateProgress((int)percentage, $"Importing entity definitions...", def.Key.ToString());

                try
                {
                    if (def.Value.Textures == null)
                    {
                        continue;
                    }
                    if (def.Value.Geometry == null)
                    {
                        continue;
                    }
                    if (def.Value.Textures.Count == 0)
                    {
                        continue;
                    }
                    if (def.Value.Geometry.Count == 0)
                    {
                        continue;
                    }

                    var    geometry = def.Value.Geometry;
                    string modelKey;
                    if (!geometry.TryGetValue("default", out modelKey) && !geometry.TryGetValue(new ResourceLocation(def.Value.Identifier).Path, out modelKey))
                    {
                        modelKey = geometry.FirstOrDefault().Value;
                    }

                    EntityModel model;
                    if (ModelFactory.TryGetModel(modelKey, out model) && model != null)
                    {
                        Add(resourceManager, graphics, def.Value, model, def.Value.Identifier);
                        Add(resourceManager, graphics, def.Value, model, def.Key.ToString());
                    }
                    else if (ModelFactory.TryGetModel(modelKey + ".v1.8", out model) && model != null)
                    {
                        Add(resourceManager, graphics, def.Value, model, def.Value.Identifier);
                        Add(resourceManager, graphics, def.Value, model, def.Key.ToString());
                    }

                    /*if ((resourceManager.BedrockResourcePack.EntityModels.TryGetValue(def.Value.Geometry["default"],
                     *                              out model)) && model != null)
                     *                  {
                     *                          Add(resourceManager, graphics, def.Value, model, def.Value.Filename);
                     *                          Add(resourceManager, graphics, def.Value, model, def.Key);
                     *                  }
                     *                  else if ((resourceManager.BedrockResourcePack.EntityModels.TryGetValue(def.Value.Geometry["default"] + ".v1.8",
                     *                                   out model)) && model != null)
                     *                  {
                     *                          Add(resourceManager, graphics, def.Value, model, def.Value.Filename);
                     *                          Add(resourceManager, graphics, def.Value, model, def.Key);
                     *                  }*/
                }
                catch (Exception ex)
                {
                    Log.Warn(ex, $"Failed to load model {def.Key}!");
                }
                finally
                {
                    done++;
                }
            }

            Log.Info($"Registered {(Assembly.GetExecutingAssembly().GetTypes().Count(t => t.Namespace == "Alex.Entities.Models"))} entity models");
            Log.Info($"Registered {_registeredRenderers.Count} entity model renderers");
        }
Example #29
0
        private PooledTexture2D[] ProcessFrames(GraphicsDevice device, IProgressReceiver progressReceiver,
                                                IDictionary <ResourceLocation, ImageEntry> blockTextures)
        {
            Dictionary <ResourceLocation, Image <Rgba32>[]> blockFrames =
                new Dictionary <ResourceLocation, Image <Rgba32>[]>();

            foreach (var other in blockTextures.Where(
                         x => x.Value.Image.Height != x.Value.Image.Width))
            {
                if (!blockFrames.TryGetValue(other.Key, out _))
                {
                    blockFrames.Add(other.Key, GetFrames(other.Value, TextureWidth, TextureHeight));
                }
            }

            var animatedFrameInfo = new Dictionary <ResourceLocation, TextureInfo>();

            GenerateAtlasInternal(
                blockFrames.Select(x => new KeyValuePair <ResourceLocation, Image <Rgba32> >(x.Key, x.Value[0])).ToArray(),
                progressReceiver, animatedFrameInfo, true, out var animatedFrame);

            AnimatedAtlasSize       = new Vector2(animatedFrame.Width, animatedFrame.Height);
            _animatedAtlasLocations = animatedFrameInfo;


            var frameCount = blockFrames.Max(x => x.Value.Length);

            while (frameCount % 2 != 0)
            {
                frameCount++;
            }

            var frames = new Image <Rgba32> [frameCount];

            frames[0] = animatedFrame;

            for (int i = 1; i < frames.Length; i++)
            {
                //  double percentage = 100D * ((double) i / (double) frames.Length);
                progressReceiver.UpdateProgress(i, frames.Length, $"Animating frame {i + 1} / {frames.Length}...");

                var target = (i > 0 ? frames[i - 1] : animatedFrame).CloneAs <Rgba32>();            //new Bitmap(animatedFrame);

                // System.Drawing.Rectangle destination;

                foreach (var animated in blockFrames)
                {
                    progressReceiver.UpdateProgress(i, frames.Length, null, animated.Key.ToString());

                    if (animatedFrameInfo.TryGetValue(animated.Key, out var textureInfo))
                    {
                        //((i % 3 == 0 ? i - 1 : i) / 6)

                        var destination = new System.Drawing.Rectangle(
                            (int)textureInfo.Position.X, (int)textureInfo.Position.Y, textureInfo.Width * 16,
                            textureInfo.Height * 16);

                        var sourceRegion = new System.Drawing.Rectangle(0, 0, textureInfo.Width * 16, textureInfo.Height * 16);

                        var index = i % animated.Value.Length;

                        var   indexOffset        = 0;
                        bool  shouldInterpolate  = false;
                        float interpolationValue = 0.5f;

                        if (blockTextures.TryGetValue(animated.Key, out var imageEntry) && imageEntry.Meta != null)
                        {
                            var meta = imageEntry.Meta;

                            if (meta.Animation != null)
                            {
                                if (meta.Animation.Interpolate)
                                {
                                    int extraFrames = (frames.Length - animated.Value.Length);

                                    var interpolationFrames = (int)Math.Floor(
                                        ((double)extraFrames / (double)animated.Value.Length));

                                    var remainder = i % interpolationFrames;

                                    if (remainder != 0)
                                    {
                                        shouldInterpolate  = true;
                                        interpolationValue = (1f / interpolationFrames) * remainder;

                                        indexOffset = -remainder;
                                        //   index -= remainder;
                                    }
                                }

                                if (meta.Animation.Frames != null)
                                {
                                    var entry = meta.Animation.Frames[(i + indexOffset) % meta.Animation.Frames.Length];

                                    if (entry.Integer.HasValue)
                                    {
                                        index = (int)entry.Integer.Value;
                                    }
                                    else if (entry.FrameClass != null)
                                    {
                                        index = (int)entry.FrameClass.Index;
                                    }
                                }
                                else
                                {
                                    index = (i + indexOffset) % animated.Value.Length;
                                }
                            }
                        }

                        //TextureUtils.ClearRegion(ref target, destination);

                        if (shouldInterpolate)
                        {
                            TextureUtils.CopyRegionIntoImage(
                                ((i + indexOffset >= 0) ? frames[(i + indexOffset) % frames.Length] : animatedFrame),
                                destination, ref target, destination, clear: true);
                        }

                        var texture = animated.Value[index];

                        TextureUtils.CopyRegionIntoImage(
                            texture, sourceRegion, ref target, destination, shouldInterpolate, interpolationValue,
                            clear: !shouldInterpolate);
                    }
                }

                frames[i] = target;
            }

            return(frames.Select(
                       (x, index) =>
            {
                var a = GetMipMappedTexture2D(device, x);
                //totalSize += a.MemoryUsage;

                return a;
            }).ToArray());
        }
Example #30
0
        private void InitializeGame(IProgressReceiver progressReceiver)
        {
            progressReceiver.UpdateProgress(0, "Initializing...");
            API.Extensions.Init(GraphicsDevice);
            MCPacketFactory.Load();

            //ConfigureServices();

            var eventDispatcher = Services.GetRequiredService <IEventDispatcher>() as EventDispatcher;

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                eventDispatcher.LoadFrom(assembly);
            }

            var options = Services.GetService <IOptionsProvider>();

            string pluginDirectoryPaths = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);

            var pluginDir = options.AlexOptions.ResourceOptions.PluginDirectory;

            if (!string.IsNullOrWhiteSpace(pluginDir))
            {
                pluginDirectoryPaths = pluginDir;
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(LaunchSettings.WorkDir) && Directory.Exists(LaunchSettings.WorkDir))
                {
                    pluginDirectoryPaths = LaunchSettings.WorkDir;
                }
            }

            foreach (string dirPath in pluginDirectoryPaths.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
            {
                string directory = dirPath;
                if (!Path.IsPathRooted(directory))
                {
                    directory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), dirPath);
                }

                PluginManager.DiscoverPlugins(directory);
            }


            var profileManager = Services.GetService <ProfileManager>();

            //	Log.Info($"Loading resources...");
            if (!Resources.CheckResources(GraphicsDevice, progressReceiver,
                                          OnResourcePackPreLoadCompleted))
            {
                Console.WriteLine("Press enter to exit...");
                Console.ReadLine();
                Exit();
                return;
            }

            profileManager.LoadProfiles(progressReceiver);

            //GuiRenderer.LoadResourcePack(Resources.ResourcePack, null);
            AnvilWorldProvider.LoadBlockConverter();

            PluginManager.EnablePlugins();

            if (LaunchSettings.ModelDebugging)
            {
                GameStateManager.SetActiveState <ModelDebugState>();
            }
            else
            {
                GameStateManager.SetActiveState <TitleState>("title");
                //	var player = new Player(GraphicsDevice, InputManager, null, null, new Skin(),  null, PlayerIndex.One, null);
                //	player.Inventory.IsPeInventory = true;

                /*Random rnd = new Random();
                 * for (int i = 0; i < player.Inventory.SlotCount; i++)
                 * {
                 *      player.Inventory[i] = new ItemBlock(BlockFactory.AllBlockstates.ElementAt(rnd.Next() % BlockFactory.AllBlockstates.Count).Value)
                 *      {
                 *              Count = rnd.Next(1, 64)
                 *      };
                 * }*/
                //GuiManager.ShowDialog(new GuiPlayerInventoryDialog(player, player.Inventory));
            }

            GameStateManager.RemoveState("splash");
        }