Ejemplo n.º 1
0
        public void GetModidFromPath()
        {
            string path1 = @"C:\Dev\ForgeModGenerator\ForgeModGenerator\mods\TestMod\src\main\resources\assets\testmod";
            string path2 = @"testmod:entity/something/either";
            string path3 = @"testmod:entity.something.either";
            string path5 = @"\ForgeModGenerator\ForgeModGenerator\mods\TestMod";

            string resultModid1 = Models.McMod.GetModidFromPath(path1);
            string resultModid2 = Models.McMod.GetModidFromPath(path2);
            string resultModid3 = Models.McMod.GetModidFromPath(path3);
            string resultModid5 = Models.McMod.GetModidFromPath(path5);

            Assert.AreEqual("testmod", resultModid1);
            Assert.AreEqual("testmod", resultModid2);
            Assert.AreEqual("testmod", resultModid3);
            Assert.AreEqual(null, resultModid5);

            // IMPORTANT: to run this tests, make sure you have TestMod in /mods/ folder
            if (Directory.Exists(ModPaths.ModRootFolder("TestMod")))
            {
                string modPath       = @"C:\Dev\ForgeModGenerator\ForgeModGenerator\mods\TestMod";
                string modPathResult = Models.McMod.GetModidFromPath(modPath);
                Assert.AreEqual("testmod", modPathResult);

                string modPath1       = @"C:\Dev\ForgeModGenerator\ForgeModGenerator\mods\TestMod\src\main\resources";
                string modPath1Result = Models.McMod.GetModidFromPath(modPath1);
                Assert.AreEqual("testmod", modPath1Result);
            }
        }
        public BlockBasesCodeGenerator(Mod mod) : base(mod)
        {
            string sourceFolder = Path.Combine(ModPaths.SourceCodeRootFolder(Modname, Organization));

            ScriptFilePaths = new string[] {
                Path.Combine(sourceFolder, SourceCodeLocator.BlockBase.RelativePath),
                Path.Combine(sourceFolder, SourceCodeLocator.OreBase.RelativePath)
            };
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            string soundsPath = ModPaths.SoundsFolder(ModName, Modid);
            ICollection <SoundEvent> folders = new Collection <SoundEvent>();
            JObject item = JObject.Load(reader);

            serializer.Converters.Add(new SoundEventConverter());
            foreach (KeyValuePair <string, JToken> property in item)
            {
                SoundEvent soundEvent = item.GetValue(property.Key).ToObject <SoundEvent>(serializer);
                soundEvent.EventName = property.Key;
                soundEvent.SetInfo(soundsPath);

                for (int i = soundEvent.Files.Count - 1; i >= 0; i--)
                {
                    Sound  sound       = soundEvent.Files[i];
                    string soundName   = sound.Name;
                    int    modidLength = sound.Name.IndexOf(":") + 1;
                    if (modidLength != -1)
                    {
                        soundName = sound.Name.Remove(0, modidLength);
                    }
                    try
                    {
                        sound.SetInfo(Path.Combine(soundsPath, $"{soundName}.ogg"));
                    }
                    catch (Exception)
                    {
                        soundEvent.Files.RemoveAt(i); // if file doesn't exist, sound can't be loaded
                    }
                    sound.IsDirty = false;
                }
                soundEvent.IsDirty = false;
                folders.Add(soundEvent);
            }
            if (objectType.IsAssignableFrom(typeof(WpfObservableFolder <SoundEvent>)))
            {
                return(new WpfObservableFolder <SoundEvent>(soundsPath, folders));
            }
            else if (objectType.IsAssignableFrom(typeof(ObservableCollection <SoundEvent>)))
            {
                return(new ObservableCollection <SoundEvent>(folders));
            }
            else if (objectType.IsAssignableFrom(typeof(WpfObservableRangeCollection <SoundEvent>)))
            {
                return(new WpfObservableRangeCollection <SoundEvent>(folders));
            }
            else if (objectType.IsAssignableFrom(typeof(ObservableRangeCollection <SoundEvent>)))
            {
                return(new ObservableRangeCollection <SoundEvent>(folders));
            }
            else if (objectType.IsAssignableFrom(typeof(List <SoundEvent>)))
            {
                return(folders.ToList());
            }
            return(folders);
        }
Ejemplo n.º 4
0
        public void Compile(McMod mcMod)
        {
            string           modPath = ModPaths.ModRootFolder(mcMod.ModInfo.Name);
            ProcessStartInfo psi     = new ProcessStartInfo {
                FileName  = "CMD.EXE",
                Arguments = $"/K cd \"{modPath}\" & gradlew build"
            };

            Process.Start(psi);
        }
        public ProxyCodeGenerator(Mod mod) : base(mod)
        {
            string sourcePath = ModPaths.SourceCodeRootFolder(Modname, Organization);

            ScriptFilePaths = new string[] {
                Path.Combine(sourcePath, SourceCodeLocator.CommonProxyInterface.RelativePath),
                Path.Combine(sourcePath, SourceCodeLocator.ClientProxy.RelativePath),
                Path.Combine(sourcePath, SourceCodeLocator.ServerProxy.RelativePath)
            };
        }
        protected override void RemoveModel(Block model)
        {
            base.RemoveModel(model);
            string blockstatePath =
                Path.Combine(ModPaths.Blockstates(SessionContext.SelectedMod.ModInfo.Name, SessionContext.SelectedMod.Modid), model.Name + ".json");

            if (File.Exists(blockstatePath))
            {
                File.Delete(blockstatePath);
            }
        }
Ejemplo n.º 7
0
        public override void Setup(McMod mcMod)
        {
            string           modPath = ModPaths.ModRootFolder(mcMod.ModInfo.Name);
            ProcessStartInfo psi     = new ProcessStartInfo {
                FileName  = "CMD.EXE",
                Arguments = $"/K cd \"{modPath}\" & gradlew setupDecompWorkspace"
            };

            Process.Start(psi);
            psi.Arguments = $"/K cd \"{modPath}\" & gradlew idea";
            Process.Start(psi);
        }
Ejemplo n.º 8
0
        public static MCItemLocator[] GetAllModItems(string modname, string modid)
        {
            List <MCItemLocator> locators = new List <MCItemLocator>(128);
            string defaultIconsPath       = ModPaths.TexturesFolder(modname, modid);

            foreach (FileInfo item in IOHelper.EnumerateFileInfos(defaultIconsPath, "*.png"))
            {
                string        locatorName = modid + ":" + Path.GetFileNameWithoutExtension(item.Name);
                MCItemLocator newLocator  = new MCItemLocator(locatorName, Path.Combine(defaultIconsPath, item.Name));
                locators.Add(newLocator);
            }
            return(locators.ToArray());
        }
Ejemplo n.º 9
0
        public void TestClassLocator()
        {
            ClassLocator locator = new ClassLocator("someFolder.SomeClassName");

            Assert.AreEqual("SomeClassName", locator.ClassName);
            Assert.AreEqual("someFolder.SomeClassName", locator.ImportFullName);
            Assert.AreEqual("someFolder/SomeClassName.java", locator.RelativePath);

            string sourcePath        = ModPaths.SourceCodeRootFolder("TestMod", "testorg");
            string armorBasePath     = Path.Combine(sourcePath, SourceCodeLocator.ArmorBase.RelativePath);
            string armorBaseFileName = Path.GetFileNameWithoutExtension(armorBasePath);

            Assert.AreEqual(armorBaseFileName, SourceCodeLocator.ArmorBase.ClassName);
        }
Ejemplo n.º 10
0
        public ItemBasesCodeGenerator(Mod mod) : base(mod)
        {
            string sourceFolder = Path.Combine(ModPaths.SourceCodeRootFolder(Modname, Organization));

            ScriptFilePaths = new string[] {
                Path.Combine(sourceFolder, SourceCodeLocator.ItemBase.RelativePath),
                Path.Combine(sourceFolder, SourceCodeLocator.BowBase.RelativePath),
                Path.Combine(sourceFolder, SourceCodeLocator.FoodBase.RelativePath),
                Path.Combine(sourceFolder, SourceCodeLocator.ArmorBase.RelativePath),
                Path.Combine(sourceFolder, SourceCodeLocator.SwordBase.RelativePath),
                Path.Combine(sourceFolder, SourceCodeLocator.SpadeBase.RelativePath),
                Path.Combine(sourceFolder, SourceCodeLocator.PickaxeBase.RelativePath),
                Path.Combine(sourceFolder, SourceCodeLocator.HoeBase.RelativePath),
                Path.Combine(sourceFolder, SourceCodeLocator.AxeBase.RelativePath),
            };
        }
Ejemplo n.º 11
0
        private void CreateBlockstateJson(Block block)
        {
            string jsonPath = Path.Combine(ModPaths.Blockstates(McMod.ModInfo.Name, McMod.Modid), block.Name.ToLower() + ".json");
            string jsonText = $@"
{{
    ""forge_marker"": 1,
    ""defaults"": {{ ""textures"": {{ ""all"": ""{block.TextureName}"" }} }},
	""variants"": {{
                ""normal"": {{ ""model"": ""cube_all"" }},
                ""inventory"": {{ 
                                ""model"": ""cube_all"",
                                ""textures"": {{ ""all"": ""{block.InventoryTextureName}"" }}
                }}
    }}
}}
";              // TODO: Do not hard-code json

            File.WriteAllText(jsonPath, jsonText);
        }
Ejemplo n.º 12
0
        internal static void LoadMods()
        {
            Log.Info($"Stardew Valley v{Game1.version}");
            Log.Info($"Stardew Farmhand v{Constants.Version}");

            ApiEvents.OnModError += ApiEvents_OnModError;
            var currentDomain = AppDomain.CurrentDomain;

            currentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve;

            Log.Success("Initializing Mappings");
            GlobalRouteManager.InitialiseMappings();
            Log.Success("Mappings Initialized");

            Log.Info("Loading Mods...");
            try
            {
                Log.Verbose("Loading Farmhand Mods");
                Log.Verbose("Loading Mod Manifests");
                LoadModManifests();
                Log.Verbose("Validating Mod Manifests");
                ValidateModManifests();
                Log.Verbose("Resolving Mod Dependencies");
                ResolveDependencies();
                Log.Verbose("Importing Mod DLLs, Settings, and Content");
                LoadFinalMods();

                var modsPath = ModPaths.First();
                ExtensibilityManager.LoadMods(modsPath);
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                Log.Error(ex.StackTrace);
            }

            var numModsLoaded = ModRegistry.GetRegisteredItems().Count(n => n.ModState == ModState.Loaded);

            Log.Info($"{numModsLoaded} Mods Loaded!");

            Game1.version += $"Stardew Farmhand v{Constants.Version}: {numModsLoaded} mods loaded";
        }
Ejemplo n.º 13
0
        public ClassLocator(string importFullName)
        {
            ImportFullName = importFullName;
            int    organizationDotIndex = ImportFullName.IndexOf('.');
            int    modnameDotIndex      = ImportFullName.IndexOf('.', organizationDotIndex + 1);
            int    nextDotIndex         = ImportFullName.IndexOf('.', modnameDotIndex + 1);
            string organization         = ImportFullName.Substring(organizationDotIndex + 1, modnameDotIndex - organizationDotIndex - 1);
            string modname = ImportFullName.Substring(modnameDotIndex + 1, nextDotIndex - modnameDotIndex - 1).ToLower();

            ImportRelativeName = ImportFullName.Substring(nextDotIndex + 1, ImportFullName.Length - nextDotIndex - 1);

            RelativePath = ImportRelativeName.Replace('.', '/') + ".java";
            FullPath     = Path.Combine(ModPaths.SourceCodeRootFolder(modname, organization), RelativePath);

            int lastRelativeDotIndex = ImportRelativeName.LastIndexOf('.');

            ClassName = ImportRelativeName.Substring(lastRelativeDotIndex + 1, ImportRelativeName.Length - lastRelativeDotIndex - 1);
            int lastDotIndex = ImportFullName.LastIndexOf('.');

            PackageName = ImportFullName.Substring(0, lastDotIndex).ToLower();
        }
Ejemplo n.º 14
0
        public override McMod ReadJson(JsonReader reader, Type objectType, McMod existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            JObject item = JObject.Load(reader);

            if (!item.HasValues)
            {
                return(null);
            }
            string    organization   = item.GetValue(nameof(McMod.Organization), StringComparison.OrdinalIgnoreCase).ToObject <string>();
            string    modname        = item.GetValue(nameof(McMod.Name), StringComparison.OrdinalIgnoreCase).ToObject <string>();
            string    modInfoPath    = ModPaths.McModInfoFile(modname);
            string    modInfoContent = File.ReadAllText(modInfoPath);
            McModInfo modInfo        = JsonConvert.DeserializeObject <McModInfo>(modInfoContent, new JsonSerializerSettings {
                Converters = serializer.Converters
            });
            ForgeVersion forgeVersion = item.GetValue(nameof(McMod.ForgeVersion), StringComparison.OrdinalIgnoreCase).ToObject <ForgeVersion>(serializer);

            ModSide side = ModSide.ClientServer;

            if (item.TryGetValue(nameof(McMod.Side), StringComparison.OrdinalIgnoreCase, out JToken sideValue))
            {
                side = sideValue.ToObject <ModSide>();
            }

            LaunchSetup launchSetup = LaunchSetup.Client;

            if (item.TryGetValue(nameof(McMod.LaunchSetup), StringComparison.OrdinalIgnoreCase, out JToken launchValue))
            {
                launchSetup = launchValue.ToObject <LaunchSetup>();
            }

            WorkspaceSetup workspaceSetup = null;

            if (item.TryGetValue(nameof(McMod.WorkspaceSetup), StringComparison.OrdinalIgnoreCase, out JToken workspaceValue))
            {
                workspaceSetup = workspaceValue.ToObject <WorkspaceSetup>(serializer);
            }
            return(new McMod(modInfo, organization, forgeVersion, side, launchSetup, workspaceSetup));
        }
Ejemplo n.º 15
0
        protected void CreateRecipe(object sender, ItemEditedEventArgs <RecipeCreator> e)
        {
            if (e.Result)
            {
                if (e.ActualItem.Validate().IsValid)
                {
                    Recipe recipe = e.ActualItem.Create();
                    string json   = RecipeSerializer.Serialize(recipe, true);
                    string path   = Path.Combine(ModPaths.RecipesFolder(SessionContext.SelectedMod.ModInfo.Name, SessionContext.SelectedMod.Modid), recipe.Name + ".json");
                    if (File.Exists(path))
                    {
                        throw new IOException($"File {path} already exists");
                    }
                    File.AppendAllText(path, json);
                }
            }
            FileInfo tempFile = new FileInfo(tempFilePath);

            if (tempFile.Exists)
            {
                tempFile.Delete();
            }
        }
Ejemplo n.º 16
0
        /// <summary> Ignore LanuchSetup and run server for this mod </summary>
        public void RunServer(McMod mcMod)
        {
            string   modPath  = ModPaths.ModRootFolder(mcMod.ModInfo.Name);
            string   eulaPath = Path.Combine(modPath, "run", "eula.txt");
            FileInfo eulaFile = new FileInfo(eulaPath);

            if (!eulaFile.Exists)
            {
                eulaFile.Directory.Create();
                string eulaMessage =
                    $@"#By changing the setting below to TRUE you are indicating your agreement to our EULA (https://account.mojang.com/documents/minecraft_eula).
#{DateTime.UtcNow}
eula = true";
                File.WriteAllText(eulaPath, eulaMessage);
            }

            ProcessStartInfo psi = new ProcessStartInfo {
                FileName  = "CMD.EXE",
                Arguments = $"/K cd \"{modPath}\" & gradlew runServer"
            };

            Process.Start(psi);
        }
Ejemplo n.º 17
0
        // Token: 0x0600100B RID: 4107 RVA: 0x0006883C File Offset: 0x00066A3C
        public static ModInfo LoadFromFile(string path, bool debugInfo)
        {
            ModInfo modInfo = ModXmlLoader.Deserialize <ModInfo>(path, false);

            if (modInfo == null)
            {
                InternalModding.Assemblies.MLog.Error("Could not load " + new FileInfo(path));
                return(null);
            }
            modInfo.Directory = new FileInfo(path).Directory.FullName;
            for (int i = 0; i < modInfo.Events.Count; i++)
            {
                ModInfo.EventInfo eventInfo = modInfo.Events[i];
                if (!eventInfo.Validate("Event"))
                {
                    InternalModding.Assemblies.MLog.Error("Not loading the mod manifest.");
                    return(null);
                }
                if (!string.IsNullOrEmpty(eventInfo.Path))
                {
                    modInfo.Events[i] = ModXmlLoader.Deserialize <ModInfo.EventInfo>(ModPaths.GetFilePath(modInfo, eventInfo.Path, false), false);
                    if (modInfo.Events[i] == null)
                    {
                        InternalModding.Assemblies.MLog.Error("Not loading the mod manifest.");
                        return(null);
                    }
                }
            }
            foreach (ModInfo.EventInfo eventInfo2 in modInfo.Events)
            {
                //eventInfo2.CreateProperties();
            }
            if (modInfo.IdFromFileSpecified)
            {
                modInfo.Id = new Guid(modInfo.IdFromFile);
            }
            else
            {
                modInfo.Id = Guid.NewGuid();
                InternalModding.Assemblies.MLog.Info(string.Concat(new object[]
                {
                    "Generated an ID for ",
                    modInfo.Name,
                    " (",
                    modInfo.Id,
                    "), writing it to the file."
                }));
                ModInfo.WriteIdElement(modInfo);
            }
            if (!modInfo.Validate())
            {
                InternalModding.Assemblies.MLog.Error("There was an error loading the mod manifest: " + path);
                return(null);
            }
            modInfo.Description = modInfo.Description.Trim();
            foreach (ModInfo.AssemblyInfo assemblyInfo in modInfo.Assemblies)
            {
                assemblyInfo.Path = ModPaths.GetFilePath(modInfo, assemblyInfo.Path, false);
            }
            foreach (ModInfo.BlockInfo blockInfo in modInfo.Blocks)
            {
                blockInfo.Path = ModPaths.GetFilePath(modInfo, blockInfo.Path, false);
            }
            foreach (ModInfo.EntityInfo entityInfo in modInfo.Entities)
            {
                entityInfo.Path = ModPaths.GetFilePath(modInfo, entityInfo.Path, false);
            }
            if (modInfo.ResourceChoices.Resources == null)
            {
                modInfo.ResourceChoices.Resources = new ModInfo.ResourceInfo[0];
                //modInfo.ResourceChoices.ResourceTypes = new ModResource.ResourceType[0];
            }
            for (int j = 0; j < modInfo.ResourceChoices.Resources.Length; j++)
            {
                ModInfo.ResourceInfo resourceInfo = modInfo.ResourceChoices.Resources[j];
                resourceInfo.Path = ModPaths.GetFilePath(modInfo, resourceInfo.Path, true);
                //resourceInfo.Type = modInfo.ResourceChoices.ResourceTypes[j];
            }
            return(modInfo);
        }
        protected override Block ParseModelFromJavaField(string line)
        {
            if (string.IsNullOrEmpty(line))
            {
                return(null);
            }

            Block block = new Block();

            System.Globalization.CultureInfo invariancy = System.Globalization.CultureInfo.InvariantCulture;
            string[] args = Array.Empty <string>();

            int    startIndex = line.IndexOf("new ") + "new ".Length;
            int    endIndex   = line.IndexOf("(", startIndex);
            string type       = line.Substring(startIndex, endIndex - startIndex);

            block.Type = type == "OreBase" ? BlockType.Ore : BlockType.Hard;

            string soundType = GetParenthesesContentFor(line, "setSoundType");

            block.SoundType = soundType.Replace("\"", "");

            string hardness = GetParenthesesContentFor(line, "setHardness");

            block.Hardness = float.Parse(hardness.RemoveEnding(), invariancy);

            string resistance = GetParenthesesContentFor(line, "setResistance");

            block.Resistance = float.Parse(resistance.RemoveEnding(), invariancy);

            string collidable = GetParenthesesContentFor(line, "setCollidable");

            block.ShouldMakeCollision = bool.Parse(collidable);

            args               = SplitParenthesesContentFor(line, type);
            block.Name         = args[0].Replace("\"", "");
            block.MaterialType = args[1];

            args = SplitParenthesesContentFor(line, "setBlockHarvestLevel", endIndex);
            block.HarvestLevelTool = ReflectionHelper.ParseEnum <HarvestToolType>(args[0].Replace("\"", ""));
            block.HarvestLevel     = int.Parse(args[1]);

            string lightLevel      = GetParenthesesContentFor(line, "setLightLevel");
            float  lightLevelFloat = float.Parse(lightLevel.RemoveEnding(), invariancy);

            lightLevelFloat  = lightLevelFloat > 0 ? lightLevelFloat * 15 : 0;
            block.LightLevel = (int)(lightLevelFloat);

            if (type == "OreBase")
            {
                string dropItem = GetParenthesesContentFor(line, "setDropItem");
                block.DropItem = dropItem;
            }

            string blockstatesPath = ModPaths.Blockstates(SessionContext.SelectedMod.ModInfo.Name, SessionContext.SelectedMod.ModInfo.Modid);
            string blockJsonPath   = Path.Combine(blockstatesPath, block.Name.ToLower() + ".json");

            if (File.Exists(blockJsonPath))
            {
                string jsonContent = File.ReadAllText(blockJsonPath);
                string keyword     = "\"all\":";
                startIndex = jsonContent.IndexOf(keyword, 1) + keyword.Length;
                startIndex = jsonContent.IndexOf("\"", startIndex) + 1;
                endIndex   = jsonContent.IndexOf("\"", startIndex);
                string textureName = jsonContent.Substring(startIndex, endIndex - startIndex);
                block.TextureName = textureName;

                startIndex = jsonContent.IndexOf(keyword, endIndex) + keyword.Length;
                startIndex = jsonContent.IndexOf("\"", startIndex) + 1;
                endIndex   = jsonContent.IndexOf("\"", startIndex);
                string inventoryTextureName = jsonContent.Substring(startIndex, endIndex - startIndex);
                block.InventoryTextureName = inventoryTextureName;
            }

            block.IsDirty           = false;
            block.ValidateProperty += ValidateModel;
            return(block);
        }
Ejemplo n.º 19
0
        protected override Item ParseModelFromJavaField(string line)
        {
            Item item = new Item();

            int    startIndex = line.IndexOf("new ") + 4;
            int    endIndex   = line.IndexOf("(", startIndex);
            string type       = line.Substring(startIndex, endIndex - startIndex);

            item.Type = (ItemType)System.Enum.Parse(typeof(ItemType), type.Replace("Base", ""), true);

            startIndex = line.IndexOf("\"", endIndex) + 1;
            endIndex   = line.IndexOf("\"", startIndex);
            string name = line.Substring(startIndex, endIndex - startIndex);

            item.Name = name;

            if (item.Type != ItemType.Item)
            {
                startIndex = line.IndexOf(" ", endIndex) + 1;
                endIndex   = line.IndexOf(")", startIndex);
                string material = line.Substring(startIndex, endIndex - startIndex);
                item.Material = material;
            }
            if (item.Type == ItemType.Armor)
            {
                startIndex = line.IndexOf("EntityEquipmentSlot", endIndex) + "EntityEquipmentSlot".Length + 1;
                endIndex   = line.IndexOf(")", startIndex);
                string armorType = line.Substring(startIndex, endIndex - startIndex);
                switch (armorType)
                {
                case "HEAD":
                    item.ArmorType = ArmorType.Helmet;
                    break;

                case "CHEST":
                    item.ArmorType = ArmorType.Chestplate;
                    break;

                case "LEGS":
                    item.ArmorType = ArmorType.Leggings;
                    break;

                case "FEET":
                    item.ArmorType = ArmorType.Boots;
                    break;

                default:
                    item.ArmorType = ArmorType.None;
                    break;
                }
            }
            if (item.Type == ItemType.Item)
            {
                startIndex = line.IndexOf(" ", endIndex) + 1;
                endIndex   = line.IndexOf(")", startIndex);
                string stackSize = line.Substring(startIndex, endIndex - startIndex);
                item.StackSize = int.Parse(stackSize, System.Globalization.CultureInfo.InvariantCulture);
            }
            else
            {
                item.StackSize = 1;
            }

            string modelsItemPath = ModPaths.ModelsItemFolder(SessionContext.SelectedMod.ModInfo.Name, SessionContext.SelectedMod.Organization);
            string itemJsonPath   = Path.Combine(modelsItemPath, name.ToLower() + ".json");

            if (File.Exists(itemJsonPath))
            {
                string jsonContent = File.ReadAllText(itemJsonPath);
                startIndex = jsonContent.IndexOf(SessionContext.SelectedMod.ModInfo.Modid, 1);
                endIndex   = jsonContent.IndexOf("\"", startIndex);
                string textureName = jsonContent.Substring(startIndex, endIndex - startIndex);
                item.TextureName = textureName;
            }

            item.IsDirty = false;
            return(item);
        }
        protected override CodeCompileUnit CreateTargetCodeUnit()
        {
            CodeCompileUnit unit = CreateDefaultTargetCodeUnit(ScriptLocator.ClassName, "Item");

            unit.Namespaces[0].Imports.Add(NewImport($"{SourceRootPackageName}.{SourceCodeLocator.ItemBase(Modname, Organization).ImportRelativeName}"));
            unit.Namespaces[0].Imports.Add(NewImport($"{SourceRootPackageName}.{SourceCodeLocator.Materials(Modname, Organization).ImportRelativeName}"));
            unit.Namespaces[0].Imports.Add(NewImport($"{SourceRootPackageName}.{SourceCodeLocator.Hook(Modname, Organization).ImportRelativeName}"));
            unit.Namespaces[0].Imports.Add(NewImport($"{SourceRootPackageName}.{SourceCodeLocator.ItemBase(Modname, Organization).ImportRelativeName}"));
            unit.Namespaces[0].Imports.Add(NewImport($"{SourceRootPackageName}.{SourceCodeLocator.ArmorBase(Modname, Organization).ImportRelativeName}"));
            unit.Namespaces[0].Imports.Add(NewImport($"{SourceRootPackageName}.{SourceCodeLocator.BowBase(Modname, Organization).ImportRelativeName}"));
            unit.Namespaces[0].Imports.Add(NewImport($"{SourceRootPackageName}.{SourceCodeLocator.AxeBase(Modname, Organization).ImportRelativeName}"));
            unit.Namespaces[0].Imports.Add(NewImport($"{SourceRootPackageName}.{SourceCodeLocator.HoeBase(Modname, Organization).ImportRelativeName}"));
            unit.Namespaces[0].Imports.Add(NewImport($"{SourceRootPackageName}.{SourceCodeLocator.PickaxeBase(Modname, Organization).ImportRelativeName}"));
            unit.Namespaces[0].Imports.Add(NewImport($"{SourceRootPackageName}.{SourceCodeLocator.SpadeBase(Modname, Organization).ImportRelativeName}"));
            unit.Namespaces[0].Imports.Add(NewImport($"{SourceRootPackageName}.{SourceCodeLocator.SwordBase(Modname, Organization).ImportRelativeName}"));
            unit.Namespaces[0].Imports.Add(NewImport($"java.util.ArrayList"));
            unit.Namespaces[0].Imports.Add(NewImport($"java.util.List"));
            unit.Namespaces[0].Imports.Add(NewImport($"net.minecraft.item.Item"));
            unit.Namespaces[0].Imports.Add(NewImport($"net.minecraft.item.Item.ToolMaterial"));
            unit.Namespaces[0].Imports.Add(NewImport($"net.minecraft.item.ItemArmor.ArmorMaterial"));
            unit.Namespaces[0].Imports.Add(NewImport($"net.minecraft.block.material.Material"));
            unit.Namespaces[0].Imports.Add(NewImport($"net.minecraft.init.SoundEvents"));
            unit.Namespaces[0].Imports.Add(NewImport($"net.minecraft.inventory.EntityEquipmentSlot"));
            unit.Namespaces[0].Imports.Add(NewImport($"net.minecraft.item.Item"));
            unit.Namespaces[0].Imports.Add(NewImport($"net.minecraft.item.ItemAxe"));
            unit.Namespaces[0].Imports.Add(NewImport($"net.minecraft.item.ItemHoe"));
            unit.Namespaces[0].Imports.Add(NewImport($"net.minecraft.item.ItemPickaxe"));
            unit.Namespaces[0].Imports.Add(NewImport($"net.minecraft.item.ItemSpade"));
            unit.Namespaces[0].Imports.Add(NewImport($"net.minecraft.item.ItemSword"));
            unit.Namespaces[0].Types[0].Members.Add(NewFieldGlobal("Item", "MODLOGO", NewObject("ItemBase", NewPrimitive("modlogo"))));
            foreach (Item item in Elements)
            {
                string newObjectType            = $"{item.Type.ToString()}Base";
                string baseObjectType           = null;
                List <CodeExpression> arguments = new List <CodeExpression>(2)
                {
                    NewPrimitive(item.Name.ToLower())
                };
                switch (item.Type)
                {
                case ItemType.Item:
                    baseObjectType = "Item";
                    arguments.Add(NewPrimitive(item.StackSize));
                    break;

                case ItemType.Hoe:
                    baseObjectType = "ItemHoe";
                    arguments.Add(NewPrimitive(item.Material));
                    break;

                case ItemType.Axe:
                    baseObjectType = "ItemAxe";
                    arguments.Add(NewPrimitive(item.Material));
                    break;

                case ItemType.Sword:
                    baseObjectType = "ItemSword";
                    arguments.Add(NewPrimitive(item.Material));
                    break;

                case ItemType.Spade:
                    baseObjectType = "ItemSpade";
                    arguments.Add(NewPrimitive(item.Material));
                    break;

                case ItemType.Pickaxe:
                    baseObjectType = "ItemPickaxe";
                    arguments.Add(NewPrimitive(item.Material));
                    break;

                case ItemType.Armor:
                    baseObjectType = "Item";
                    arguments.Add(NewPrimitive(item.Material));
                    switch (item.ArmorType)
                    {
                    case ArmorType.Helmet:
                        arguments.Add(NewPrimitive(1));
                        arguments.Add(NewSnippetExpression("EntityEquipmentSlot.HEAD"));
                        break;

                    case ArmorType.Chestplate:
                        arguments.Add(NewPrimitive(1));
                        arguments.Add(NewSnippetExpression("EntityEquipmentSlot.CHEST"));
                        break;

                    case ArmorType.Leggings:
                        arguments.Add(NewPrimitive(2));
                        arguments.Add(NewSnippetExpression("EntityEquipmentSlot.LEGS"));
                        break;

                    case ArmorType.Boots:
                        arguments.Add(NewPrimitive(1));
                        arguments.Add(NewSnippetExpression("EntityEquipmentSlot.FEET"));
                        break;

                    default:
                        throw new NotImplementedException($"{item.ArmorType} was not implemented");
                    }
                    break;

                default:
                    throw new NotImplementedException($"{item.Type} was not implemented");
                }
                CodeMemberField field = NewFieldGlobal(baseObjectType, item.Name.ToUpper(), NewObject(newObjectType, arguments.ToArray()));
                unit.Namespaces[0].Types[0].Members.Add(field);
                string jsonPath = Path.Combine(ModPaths.ModelsItemFolder(McMod.ModInfo.Name, McMod.Modid), item.Name.ToLower() + ".json");
                string parent   = item.Type == ItemType.Armor ? "generated" : "handheld";
                string jsonText = $@"
{{
    ""parent"": ""item/{parent}"",
    ""textures"": {{
                    ""layer0"": ""{McMod.Modid}:{item.TextureName}""
    }}
}}
";
                // TODO: Do not hard-code json
                File.WriteAllText(jsonPath, jsonText);
            }
            return(unit);
        }
Ejemplo n.º 21
0
 public string GetWorkshopPath()
 {
     return(ModPaths.FirstOrDefault(modPath => modPath.IndexOf("steamapps\\workshop\\content\\268500\\", StringComparison.OrdinalIgnoreCase) != -1));
 }
        // Token: 0x06000D55 RID: 3413 RVA: 0x0005AF34 File Offset: 0x00059134
        public static string ResolveScriptAssembly(string codeDir, ModContainer mod)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(codeDir);

            if (!directoryInfo.Exists)
            {
                MLog.Error("Code directory " + codeDir + " does not exist!");
                return(string.Empty);
            }
            string assemblyPath = ModPaths.GetAssemblyPath(mod, directoryInfo.Name);

            if (File.Exists(assemblyPath))
            {
                return(assemblyPath);
            }
            CompilerParameters compilerParameters = new CompilerParameters
            {
                GenerateExecutable = false,
                GenerateInMemory   = false,
                OutputAssembly     = assemblyPath
            };

            compilerParameters.ReferencedAssemblies.AddRange((from a in AppDomain.CurrentDomain.GetAssemblies().Where(delegate(Assembly a)
            {
                bool result;
                try
                {
                    result = !string.IsNullOrEmpty(a.Location);
                }
                catch (NotSupportedException)
                {
                    result = false;
                }
                return(result);
            })
                                                              select a.Location).ToArray <string>());
            string[] array = (from f in directoryInfo.GetFiles("*.cs", SearchOption.AllDirectories)
                              select f.FullName).ToArray <string>();
            if (array.Length == 0)
            {
                MLog.Error("Code directory " + codeDir + " does not contain any source files!");
            }
            CSharpCompiler.CodeCompiler codeCompiler    = new CSharpCompiler.CodeCompiler();
            CompilerResults             compilerResults = codeCompiler.CompileAssemblyFromFileBatch(compilerParameters, array);

            foreach (object obj in compilerResults.Errors)
            {
                CompilerError compilerError = (CompilerError)obj;
                string        message       = compilerError.ToString();
                if (compilerError.IsWarning)
                {
                    MLog.Warn(message);
                }
                else
                {
                    MLog.Error(message);
                }
            }
            if (compilerResults.Errors.HasErrors)
            {
                MLog.Error("There were errors compiling the ScriptAssembly at " + codeDir + "!");
            }
            return(assemblyPath);
        }