use of net.minecraftforge.common.crafting.JsonContext in project Wizardry by TeamWizardry.
the class FireRecipeLoader method processRecipes.
public void processRecipes(Map<Ingredient, FireRecipe> recipes) {
Wizardry.logger.info("<<========================================================================>>");
Wizardry.logger.info("> Starting fire recipe loading.");
JsonContext context = new JsonContext("minecraft");
LinkedList<File> recipeFiles = new LinkedList<>();
Stack<File> toProcess = new Stack<>();
toProcess.push(directory);
while (!toProcess.isEmpty()) {
File file = toProcess.pop();
if (file.isDirectory()) {
File[] children = file.listFiles();
if (children != null)
for (File child : children) toProcess.push(child);
} else if (file.isFile())
if (file.getName().endsWith(".json"))
recipeFiles.add(file);
}
for (File file : recipeFiles) {
try {
if (!file.exists()) {
Wizardry.logger.error(" > SOMETHING WENT WRONG! " + file.getPath() + " can NOT be found. Ignoring file...");
continue;
}
JsonElement element;
try {
element = new JsonParser().parse(new FileReader(file));
} catch (FileNotFoundException e) {
Wizardry.logger.error(" > SOMETHING WENT WRONG! " + file.getPath() + " can NOT be found. Ignoring file...");
continue;
}
if (element == null) {
Wizardry.logger.error(" > SOMETHING WENT WRONG! Could not parse " + file.getPath() + ". Ignoring file...");
continue;
}
if (!element.isJsonObject()) {
Wizardry.logger.error(" > WARNING! " + file.getPath() + " does NOT contain a JsonObject. Ignoring file...: " + element.toString());
continue;
}
JsonObject fileObject = element.getAsJsonObject();
int duration = 200;
if (!fileObject.has("input")) {
Wizardry.logger.error(" > WARNING! " + file.getPath() + " does NOT provide an initial input item. Ignoring file...: " + element.toString());
continue;
}
JsonElement inputObject = fileObject.get("input");
Ingredient input = CraftingHelper.getIngredient(inputObject, context);
if (input == Ingredient.EMPTY) {
Wizardry.logger.error(" > WARNING! " + file.getPath() + " does NOT provide a valid input. Ignoring file...: " + element.toString());
continue;
}
if (!fileObject.has("output")) {
Wizardry.logger.error(" > WARNING! " + file.getPath() + " does NOT specify a recipe output. Ignoring file...: " + element.toString());
continue;
}
if (!fileObject.get("output").isJsonObject()) {
Wizardry.logger.error(" > WARNING! " + file.getPath() + " does NOT provide a valid output. Ignoring file...: " + element.toString());
continue;
}
JsonObject outputObject = fileObject.get("output").getAsJsonObject();
ItemStack output = CraftingHelper.getItemStack(outputObject, context);
if (output.isEmpty()) {
Wizardry.logger.error(" > WARNING! " + file.getPath() + " does NOT provide a valid output. Ignoring file...: " + element.toString());
continue;
}
if (fileObject.has("duration")) {
if (!fileObject.get("duration").isJsonPrimitive() || !fileObject.getAsJsonPrimitive("duration").isNumber()) {
Wizardry.logger.error(" > WARNING! " + file.getPath() + " does NOT give duration as a number. Ignoring file...:" + element.toString());
continue;
}
duration = fileObject.get("duration").getAsInt();
}
recipes.put(input, new FireRecipe(output, duration));
} catch (JsonParseException jsonException) {
Wizardry.logger.error(" > WARNING! Skipping " + file.getPath() + " due to error: ", jsonException);
}
}
Wizardry.logger.info("> Finished fire recipe loading.");
Wizardry.logger.info("<<========================================================================>>");
}
use of net.minecraftforge.common.crafting.JsonContext in project BaseMetals by MinecraftModDevelopmentMods.
the class ConfigVariedOutput method parse.
@Override
public IRecipe parse(final JsonContext context, final JsonObject json) {
String confKey = JsonUtils.getString(json, "config_key");
int resAmount = 0;
switch(confKey) {
case "gear":
resAmount = Options.gearQuantity();
break;
case "plate":
resAmount = Options.plateQuantity();
break;
default:
BaseMetals.logger.error("Unknown quantity config value {}, setting to 1", confKey);
resAmount = 1;
}
// load the data here, map the ingredients, setup the primer and return the ShapedOreRecipe :)
final Map<Character, Ingredient> ingMap = Maps.newHashMap();
JsonUtils.getJsonObject(json, "key").entrySet().stream().filter(ent -> ent.getKey().length() == 1 && !ent.getKey().isEmpty()).forEach(ent -> ingMap.put(ent.getKey().toCharArray()[0], CraftingHelper.getIngredient(ent.getValue(), context)));
ingMap.put(' ', Ingredient.EMPTY);
JsonArray patternJ = JsonUtils.getJsonArray(json, "pattern");
if (patternJ.size() == 0) {
throw new JsonSyntaxException("Invalid pattern: empty pattern not allows");
}
final String[] pattern = new String[patternJ.size()];
for (int x = 0; x < pattern.length; ++x) {
final String line = JsonUtils.getString(patternJ.get(x), "pattern[" + x + "]");
if (x > 0 && pattern[0].length() != line.length()) {
throw new JsonSyntaxException("Invalid pattern: each row must be the same width");
}
pattern[x] = line;
}
final ShapedPrimer primer = new ShapedPrimer();
primer.width = pattern[0].length();
primer.height = pattern.length;
primer.mirrored = true;
primer.input = NonNullList.withSize(primer.width * primer.height, Ingredient.EMPTY);
final Set<Character> keys = Sets.newHashSet(ingMap.keySet());
keys.remove(' ');
int x = 0;
for (final String line : pattern) {
for (final char chr : line.toCharArray()) {
final Ingredient ing = ingMap.get(chr);
if (ing == null) {
throw new JsonSyntaxException("Pattern references symbol '" + chr + "' but it's not defined in the key");
}
primer.input.set(x++, ing);
keys.remove(chr);
}
}
if (!keys.isEmpty()) {
throw new JsonSyntaxException("Key defines symbols that aren't used in pattern: " + keys);
}
final String group = JsonUtils.getString(json, "group", "");
final ItemStack result = CraftingHelper.getItemStack(JsonUtils.getJsonObject(json, "result"), context);
result.setCount(resAmount);
return new ShapedOreRecipe(group.isEmpty() ? null : new ResourceLocation(group), result, primer);
}
use of net.minecraftforge.common.crafting.JsonContext in project BuildCraft by BuildCraft.
the class BCSiliconRecipes method registerRecipes.
@SubscribeEvent
public static void registerRecipes(RegistryEvent.Register<IRecipe> event) {
Loader.instance().getActiveModList().forEach((mod) -> {
JsonContext ctx = new JsonContext(mod.getModId());
CraftingHelper.findFiles(mod, "assets/" + mod.getModId() + "/assembly_recipes", null, (root, file) -> {
String path = root.relativize(file).toString();
if (!FilenameUtils.getExtension(file.toString()).equals("json"))
return true;
String name = FilenameUtils.removeExtension(path).replaceAll("\\\\", "/");
ResourceLocation key = new ResourceLocation(mod.getModId(), name);
BufferedReader reader = null;
try {
reader = Files.newBufferedReader(file);
JsonObject json = JsonUtils.fromJson(GSON, reader, JsonObject.class);
if (json == null || json.isJsonNull())
throw new JsonSyntaxException("Json is null (empty file?)");
ItemStack output = CraftingHelper.getItemStack(json.getAsJsonObject("result"), ctx);
long powercost = json.get("MJ").getAsLong() * MjAPI.MJ;
ArrayList<IngredientStack> ingredients = new ArrayList<>();
json.getAsJsonArray("components").forEach(element -> {
JsonObject object = element.getAsJsonObject();
ingredients.add(new IngredientStack(CraftingHelper.getIngredient(object.get("ingredient"), ctx), JsonUtils.getInt(object, "amount", 1)));
});
AssemblyRecipeRegistry.REGISTRY.put(key, new AssemblyRecipeBasic(key, powercost, ImmutableSet.copyOf(ingredients), output));
} catch (IOException e) {
BCLog.logger.error("Couldn't read recipe {} from {}", key, file, e);
return false;
} finally {
IOUtils.closeQuietly(reader);
}
return true;
});
CraftingHelper.findFiles(mod, "assets/" + mod.getModId() + "/integration_recipes", null, (root, file) -> {
String path = root.relativize(file).toString();
if (!FilenameUtils.getExtension(file.toString()).equals("json"))
return true;
String name = FilenameUtils.removeExtension(path).replaceAll("\\\\", "/");
ResourceLocation key = new ResourceLocation(mod.getModId(), name);
BufferedReader reader = null;
try {
reader = Files.newBufferedReader(file);
JsonObject json = JsonUtils.fromJson(GSON, reader, JsonObject.class);
if (json == null || json.isJsonNull())
throw new JsonSyntaxException("Json is null (empty file?)");
ItemStack output = CraftingHelper.getItemStack(json.getAsJsonObject("result"), ctx);
IngredientStack centerStack = IngredientStack.of(CraftingHelper.getIngredient(json.getAsJsonObject("centerStack"), ctx));
long powercost = json.get("MJ").getAsLong() * MjAPI.MJ;
ArrayList<IngredientStack> ingredients = new ArrayList<>();
json.getAsJsonArray("components").forEach(element -> {
JsonObject object = element.getAsJsonObject();
ingredients.add(new IngredientStack(CraftingHelper.getIngredient(object.get("ingredient"), ctx), JsonUtils.getInt(object, "amount", 1)));
});
IntegrationRecipeRegistry.INSTANCE.addRecipe(new IntegrationRecipeBasic(key, powercost, centerStack, ingredients, output));
} catch (IOException e) {
BCLog.logger.error("Couldn't read recipe {} from {}", key, file, e);
return false;
} finally {
IOUtils.closeQuietly(reader);
}
return true;
});
});
}
use of net.minecraftforge.common.crafting.JsonContext in project Gaspunk by Ladysnake.
the class GasRecipeDeserializer method loadRecipes.
private static void loadRecipes(ModContainer container) {
Loader.instance().setActiveModContainer(container);
JsonContext context = new JsonContext(container.getModId());
CraftingHelper.findFiles(container, "assets/" + container.getModId() + "/gaspunk_recipes", p -> true, (root, file) -> loadRecipes(root, file, context), true, true);
}
use of net.minecraftforge.common.crafting.JsonContext in project Gaspunk by Ladysnake.
the class GasRecipeDeserializer method loadRecipes.
@SubscribeEvent
public static void loadRecipes(RegistryEvent.Register<IRecipe> event) {
ModContainer gaspunkContainer = Loader.instance().activeModContainer();
Loader.instance().getActiveModList().forEach(GasRecipeDeserializer::loadRecipes);
Loader.instance().setActiveModContainer(gaspunkContainer);
File configFolder = new File(Loader.instance().getConfigDir(), GasPunk.MOD_ID + "/custom_recipes");
// if the config folder was just created or couldn't be created, no need to search it
try {
if (!configFolder.mkdirs() && configFolder.exists()) {
JsonContext context = new JsonContext(GasPunk.MOD_ID);
try {
Files.walk(configFolder.toPath()).forEach(path -> loadRecipes(configFolder.toPath(), path, context));
} catch (IOException e) {
e.printStackTrace();
}
} else if (configFolder.exists()) {
JsonObject recipe = new JsonObject();
recipe.addProperty("result", "gaspunk:colored_smoke_red");
JsonObject input = new JsonObject();
input.addProperty("item", "minecraft:water_bucket");
recipe.add("input", input);
JsonObject ingredient = new JsonObject();
ingredient.addProperty("type", "forge:ore_dict");
ingredient.addProperty("ore", "dustRedstone");
recipe.add("ingredient", ingredient);
recipe.addProperty("result", "gaspunk:colored_smoke_red");
Files.write(configFolder.toPath().resolve("_example.json"), GSON.toJson(recipe).getBytes(), StandardOpenOption.CREATE_NEW);
}
} catch (IOException e) {
GasPunk.LOGGER.error("Error while loading gas recipes from config", e);
}
}
Aggregations