Search in sources :

Example 1 with JSONObject

use of com.loohp.interactivechat.libs.org.json.simple.JSONObject in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class ModelManager method loadDirectory.

@Override
protected void loadDirectory(String namespace, ResourcePackFile root) {
    if (!root.exists() || !root.isDirectory()) {
        throw new IllegalArgumentException(root.getAbsolutePath() + " is not a directory.");
    }
    JSONParser parser = new JSONParser();
    Map<String, BlockModel> models = new HashMap<>();
    Collection<ResourcePackFile> files = root.listFilesRecursively(new String[] { "json" });
    for (ResourcePackFile file : files) {
        try {
            String key = namespace + ":" + file.getRelativePathFrom(root);
            key = key.substring(0, key.lastIndexOf("."));
            InputStreamReader reader = new InputStreamReader(new BOMInputStream(file.getInputStream()), StandardCharsets.UTF_8);
            JSONObject rootJson = (JSONObject) parser.parse(reader);
            reader.close();
            String parent = (String) rootJson.getOrDefault("parent", null);
            boolean ambientocclusion = (boolean) rootJson.getOrDefault("ambientocclusion", true);
            ModelGUILight guiLight = rootJson.containsKey("gui_light") ? ModelGUILight.fromKey((String) rootJson.get("gui_light")) : null;
            Map<ModelDisplayPosition, ModelDisplay> display = new EnumMap<>(ModelDisplayPosition.class);
            JSONObject displayJson = (JSONObject) rootJson.get("display");
            if (displayJson != null) {
                for (Object obj : displayJson.keySet()) {
                    String displayKey = obj.toString();
                    JSONArray rotationArray = (JSONArray) ((JSONObject) displayJson.get(displayKey)).get("rotation");
                    JSONArray translationArray = (JSONArray) ((JSONObject) displayJson.get(displayKey)).get("translation");
                    JSONArray scaleArray = (JSONArray) ((JSONObject) displayJson.get(displayKey)).get("scale");
                    Coordinates3D rotation;
                    if (rotationArray == null) {
                        rotation = new Coordinates3D(0, 0, 0);
                    } else {
                        rotation = new Coordinates3D(((Number) rotationArray.get(0)).doubleValue(), ((Number) rotationArray.get(1)).doubleValue(), ((Number) rotationArray.get(2)).doubleValue());
                    }
                    Coordinates3D translation;
                    if (translationArray == null) {
                        translation = new Coordinates3D(0, 0, 0);
                    } else {
                        translation = new Coordinates3D(((Number) translationArray.get(0)).doubleValue(), ((Number) translationArray.get(1)).doubleValue(), ((Number) translationArray.get(2)).doubleValue());
                    }
                    Coordinates3D scale;
                    if (scaleArray == null) {
                        scale = new Coordinates3D(1, 1, 1);
                    } else {
                        scale = new Coordinates3D(((Number) scaleArray.get(0)).doubleValue(), ((Number) scaleArray.get(1)).doubleValue(), ((Number) scaleArray.get(2)).doubleValue());
                    }
                    ModelDisplayPosition displayPos = ModelDisplayPosition.fromKey(displayKey);
                    display.put(displayPos, new ModelDisplay(displayPos, rotation, translation, scale));
                }
            }
            Map<String, String> texture = new HashMap<>();
            JSONObject textureJson = (JSONObject) rootJson.get("textures");
            if (textureJson != null) {
                for (Object obj : textureJson.keySet()) {
                    String textureKey = obj.toString();
                    texture.put(textureKey, textureJson.get(textureKey).toString());
                }
            }
            List<ModelElement> elements = new ArrayList<>();
            JSONArray elementsArray = (JSONArray) rootJson.get("elements");
            if (elementsArray != null) {
                for (Object obj : elementsArray) {
                    JSONObject elementJson = (JSONObject) obj;
                    JSONArray fromArray = (JSONArray) elementJson.get("from");
                    JSONArray toArray = (JSONArray) elementJson.get("to");
                    Coordinates3D from = new Coordinates3D(((Number) fromArray.get(0)).doubleValue(), ((Number) fromArray.get(1)).doubleValue(), ((Number) fromArray.get(2)).doubleValue());
                    Coordinates3D to = new Coordinates3D(((Number) toArray.get(0)).doubleValue(), ((Number) toArray.get(1)).doubleValue(), ((Number) toArray.get(2)).doubleValue());
                    ModelElementRotation rotation;
                    JSONObject rotationJson = (JSONObject) elementJson.get("rotation");
                    if (rotationJson == null) {
                        rotation = null;
                    } else {
                        Coordinates3D origin;
                        JSONArray originArray = (JSONArray) rotationJson.get("origin");
                        if (originArray == null) {
                            origin = new Coordinates3D(0, 0, 0);
                        } else {
                            origin = new Coordinates3D(((Number) originArray.get(0)).doubleValue(), ((Number) originArray.get(1)).doubleValue(), ((Number) originArray.get(2)).doubleValue());
                        }
                        ModelAxis axis = ModelAxis.valueOf(rotationJson.get("axis").toString().toUpperCase());
                        double angle = ((Number) rotationJson.get("angle")).doubleValue();
                        boolean rescale = (boolean) rotationJson.getOrDefault("rescale", false);
                        rotation = new ModelElementRotation(origin, axis, angle, rescale);
                    }
                    boolean shade = (boolean) elementJson.getOrDefault("shade", true);
                    Map<ModelFaceSide, ModelFace> face = new EnumMap<>(ModelFaceSide.class);
                    JSONObject facesJson = (JSONObject) elementJson.get("faces");
                    if (facesJson != null) {
                        for (Object obj1 : facesJson.keySet()) {
                            String faceKey = obj1.toString();
                            ModelFaceSide side = ModelFaceSide.fromKey(faceKey);
                            JSONObject faceJson = (JSONObject) facesJson.get(faceKey);
                            TextureUV uv;
                            JSONArray uvArray = (JSONArray) faceJson.get("uv");
                            if (uvArray == null) {
                                uv = null;
                            } else {
                                uv = new TextureUV(((Number) uvArray.get(0)).doubleValue(), ((Number) uvArray.get(1)).doubleValue(), ((Number) uvArray.get(2)).doubleValue(), ((Number) uvArray.get(3)).doubleValue());
                            }
                            String faceTexture = (String) faceJson.get("texture");
                            Object cullfaceObj = faceJson.get("cullface");
                            ModelFaceSide cullface = null;
                            if (cullfaceObj != null && cullfaceObj instanceof String) {
                                cullface = ModelFaceSide.fromKey((String) cullfaceObj);
                            }
                            if (cullface == null) {
                                cullface = side;
                            }
                            int faceRotation = ((Number) faceJson.getOrDefault("rotation", 0)).intValue();
                            int faceTintindex = ((Number) faceJson.getOrDefault("tintindex", -1)).intValue();
                            face.put(side, new ModelFace(side, uv, faceTexture, cullface, faceRotation, faceTintindex));
                        }
                    }
                    elements.add(new ModelElement(from, to, rotation, shade, face));
                }
            }
            List<ModelOverride> overrides = new ArrayList<>();
            JSONArray overridesArray = (JSONArray) rootJson.get("overrides");
            if (overridesArray != null) {
                for (Object obj : overridesArray) {
                    JSONObject overrideJson = (JSONObject) obj;
                    JSONObject predicateJson = (JSONObject) overrideJson.get("predicate");
                    Map<ModelOverrideType, Float> predicates = new EnumMap<>(ModelOverrideType.class);
                    for (Object obj1 : predicateJson.keySet()) {
                        String predicateTypeKey = obj1.toString();
                        ModelOverrideType type = ModelOverrideType.fromKey(predicateTypeKey);
                        Object value = predicateJson.get(predicateTypeKey);
                        predicates.put(type, ((Number) value).floatValue());
                    }
                    String model = (String) overrideJson.get("model");
                    overrides.add(new ModelOverride(predicates, model));
                }
            }
            Collections.reverse(overrides);
            models.put(key, new BlockModel(this, parent, ambientocclusion, guiLight, display, texture, elements, overrides));
        } catch (Exception e) {
            new ResourceLoadingException("Unable to load block model " + file.getAbsolutePath(), e).printStackTrace();
        }
    }
    this.models.putAll(models);
}
Also used : ModelDisplayPosition(com.loohp.interactivechatdiscordsrvaddon.resources.models.ModelDisplay.ModelDisplayPosition) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) BOMInputStream(com.loohp.interactivechat.libs.org.apache.commons.io.input.BOMInputStream) ResourceLoadingException(com.loohp.interactivechatdiscordsrvaddon.resources.ResourceLoadingException) ModelOverrideType(com.loohp.interactivechatdiscordsrvaddon.resources.models.ModelOverride.ModelOverrideType) EnumMap(java.util.EnumMap) InputStreamReader(java.io.InputStreamReader) JSONArray(com.loohp.interactivechat.libs.org.json.simple.JSONArray) ModelFaceSide(com.loohp.interactivechatdiscordsrvaddon.resources.models.ModelFace.ModelFaceSide) ResourceLoadingException(com.loohp.interactivechatdiscordsrvaddon.resources.ResourceLoadingException) ModelElementRotation(com.loohp.interactivechatdiscordsrvaddon.resources.models.ModelElement.ModelElementRotation) JSONObject(com.loohp.interactivechat.libs.org.json.simple.JSONObject) JSONParser(com.loohp.interactivechat.libs.org.json.simple.parser.JSONParser) ResourcePackFile(com.loohp.interactivechatdiscordsrvaddon.resources.ResourcePackFile) JSONObject(com.loohp.interactivechat.libs.org.json.simple.JSONObject)

Example 2 with JSONObject

use of com.loohp.interactivechat.libs.org.json.simple.JSONObject in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class TextureManager method loadDirectory.

@SuppressWarnings("unchecked")
@Override
protected void loadDirectory(String namespace, ResourcePackFile root) {
    if (!root.exists() || !root.isDirectory()) {
        throw new IllegalArgumentException(root.getAbsolutePath() + " is not a directory.");
    }
    JSONParser parser = new JSONParser();
    Map<String, TextureResource> textures = new HashMap<>();
    Collection<ResourcePackFile> files = root.listFilesRecursively();
    for (ResourcePackFile file : files) {
        try {
            String key = namespace + ":" + file.getRelativePathFrom(root);
            String extension = "";
            if (key.lastIndexOf(".") >= 0) {
                extension = key.substring(key.lastIndexOf(".") + 1);
                key = key.substring(0, key.lastIndexOf("."));
            }
            if (extension.equalsIgnoreCase("png")) {
                textures.put(key, new TextureResource(this, key, file, true));
            } else if (extension.equalsIgnoreCase("mcmeta")) {
                InputStreamReader reader = new InputStreamReader(new BOMInputStream(file.getInputStream()), StandardCharsets.UTF_8);
                JSONObject rootJson = (JSONObject) parser.parse(reader);
                reader.close();
                TextureAnimation animation = null;
                if (rootJson.containsKey("animation")) {
                    JSONObject animationJson = (JSONObject) rootJson.get("animation");
                    boolean interpolate = (boolean) animationJson.getOrDefault("interpolate", false);
                    int width = ((Number) animationJson.getOrDefault("width", -1)).intValue();
                    int height = ((Number) animationJson.getOrDefault("height", -1)).intValue();
                    int frametime = ((Number) animationJson.getOrDefault("frametime", -1)).intValue();
                    JSONArray framesArray = ((JSONArray) animationJson.getOrDefault("frames", new JSONArray()));
                    List<TextureAnimationFrames> frames = new ArrayList<>();
                    for (Object obj : framesArray) {
                        if (obj instanceof Number) {
                            frames.add(new TextureAnimationFrames(((Number) obj).intValue(), frametime));
                        } else if (obj instanceof JSONObject) {
                            JSONObject frameJson = (JSONObject) obj;
                            frames.add(new TextureAnimationFrames(((Number) frameJson.get("index")).intValue(), ((Number) frameJson.get("time")).intValue()));
                        }
                    }
                    animation = new TextureAnimation(interpolate, width, height, frametime, frames);
                }
                TextureProperties properties = null;
                if (rootJson.containsKey("texture")) {
                    JSONObject propertiesJson = (JSONObject) rootJson.get("texture");
                    boolean blur = (boolean) propertiesJson.getOrDefault("blur", false);
                    boolean clamp = (boolean) propertiesJson.getOrDefault("clamp", false);
                    int[] mipmaps = ((JSONArray) propertiesJson.getOrDefault("mipmaps", new JSONArray())).stream().mapToInt(each -> ((Number) each).intValue()).toArray();
                    properties = new TextureProperties(blur, clamp, mipmaps);
                }
                textures.put(key + "." + extension, new TextureMeta(this, key + "." + extension, file, animation, properties));
            } else {
                textures.put(key + "." + extension, new TextureResource(this, key, file));
            }
        } catch (Exception e) {
            new ResourceLoadingException("Unable to load block model " + file.getAbsolutePath(), e).printStackTrace();
        }
    }
    this.textures.putAll(textures);
}
Also used : InputStreamReader(java.io.InputStreamReader) HashMap(java.util.HashMap) JSONArray(com.loohp.interactivechat.libs.org.json.simple.JSONArray) TextureAnimationFrames(com.loohp.interactivechatdiscordsrvaddon.resources.textures.TextureAnimation.TextureAnimationFrames) ResourceLoadingException(com.loohp.interactivechatdiscordsrvaddon.resources.ResourceLoadingException) BOMInputStream(com.loohp.interactivechat.libs.org.apache.commons.io.input.BOMInputStream) JSONObject(com.loohp.interactivechat.libs.org.json.simple.JSONObject) ResourceLoadingException(com.loohp.interactivechatdiscordsrvaddon.resources.ResourceLoadingException) JSONParser(com.loohp.interactivechat.libs.org.json.simple.parser.JSONParser) ResourcePackFile(com.loohp.interactivechatdiscordsrvaddon.resources.ResourcePackFile) ArrayList(java.util.ArrayList) List(java.util.List) JSONObject(com.loohp.interactivechat.libs.org.json.simple.JSONObject)

Example 3 with JSONObject

use of com.loohp.interactivechat.libs.org.json.simple.JSONObject in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class FontManager method loadDirectory.

@Override
protected void loadDirectory(String namespace, ResourcePackFile root) {
    if (!root.exists() || !root.isDirectory()) {
        throw new IllegalArgumentException(root.getAbsolutePath() + " is not a directory.");
    }
    Map<String, ResourcePackFile> fileList = files.get(namespace);
    if (fileList == null) {
        files.put(namespace, fileList = new HashMap<>());
    }
    JSONParser parser = new JSONParser();
    Map<String, FontProvider> fonts = new HashMap<>(this.fonts);
    Collection<ResourcePackFile> files = root.listFilesRecursively();
    for (ResourcePackFile file : files) {
        fileList.put(file.getName(), file);
    }
    for (ResourcePackFile file : files) {
        if (file.getName().endsWith(".json")) {
            try {
                String key = namespace + ":" + file.getName();
                key = key.substring(0, key.lastIndexOf("."));
                InputStreamReader reader = new InputStreamReader(new BOMInputStream(file.getInputStream()), StandardCharsets.UTF_8);
                JSONObject rootJson = (JSONObject) parser.parse(reader);
                reader.close();
                List<MinecraftFont> providedFonts = new ArrayList<>();
                int index = -1;
                for (Object obj : (JSONArray) rootJson.get("providers")) {
                    index++;
                    JSONObject fontJson = (JSONObject) obj;
                    try {
                        switch(fontJson.get("type").toString()) {
                            case "bitmap":
                                String resourceLocation = fontJson.get("file").toString();
                                int height = ((Number) fontJson.getOrDefault("height", 8)).intValue();
                                int ascent = ((Number) fontJson.get("ascent")).intValue();
                                List<String> chars = (List<String>) ((JSONArray) fontJson.get("chars")).stream().map(each -> each.toString()).collect(Collectors.toList());
                                providedFonts.add(new BitmapFont(manager, null, resourceLocation, height, ascent, chars));
                                break;
                            case "legacy_unicode":
                                String template = fontJson.get("template").toString();
                                DataInputStream sizesInput = new DataInputStream(new BufferedInputStream(getFontResource(fontJson.get("sizes").toString()).getFile().getInputStream()));
                                Int2ObjectOpenHashMap<GlyphSize> sizes = new Int2ObjectOpenHashMap<>();
                                for (int i = 0; ; i++) {
                                    try {
                                        byte b = sizesInput.readByte();
                                        byte start = (byte) ((b >> 4) & 15);
                                        byte end = (byte) (b & 15);
                                        sizes.put(i, new GlyphSize(start, end));
                                    } catch (EOFException e) {
                                        break;
                                    }
                                }
                                sizesInput.close();
                                providedFonts.add(new LegacyUnicodeFont(manager, null, sizes, template));
                                break;
                            case "ttf":
                                resourceLocation = fontJson.get("file").toString();
                                JSONArray shiftArray = (JSONArray) fontJson.get("shift");
                                float leftShift = ((Number) shiftArray.get(0)).floatValue();
                                float downShift = ((Number) shiftArray.get(1)).floatValue();
                                AffineTransform shift = AffineTransform.getTranslateInstance(-leftShift, downShift);
                                float size = ((Number) fontJson.get("size")).floatValue();
                                float oversample = ((Number) fontJson.get("oversample")).floatValue();
                                String skip = fontJson.getOrDefault("skip", "").toString();
                                providedFonts.add(new TrueTypeFont(manager, null, resourceLocation, shift, size, oversample, skip));
                                break;
                        }
                    } catch (Exception e) {
                        new ResourceLoadingException("Unable to load font provider " + index + " in " + file.getAbsolutePath(), e).printStackTrace();
                    }
                }
                FontProvider existingProvider = fonts.get(key);
                if (existingProvider == null) {
                    providedFonts.add(new BackingEmptyFont(manager, null));
                    FontProvider provider = new FontProvider(key, providedFonts);
                    for (MinecraftFont mcFont : provider.getProviders()) {
                        mcFont.setProvider(provider);
                    }
                    fonts.put(key, provider);
                } else {
                    for (MinecraftFont mcFont : providedFonts) {
                        mcFont.setProvider(existingProvider);
                    }
                    existingProvider.prependProviders(providedFonts);
                }
            } catch (Exception e) {
                new ResourceLoadingException("Unable to load font " + file.getAbsolutePath(), e).printStackTrace();
            }
        }
    }
    this.fonts.clear();
    this.fonts.putAll(fonts);
}
Also used : HashMap(java.util.HashMap) Int2ObjectOpenHashMap(it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap) ArrayList(java.util.ArrayList) BOMInputStream(com.loohp.interactivechat.libs.org.apache.commons.io.input.BOMInputStream) ResourceLoadingException(com.loohp.interactivechatdiscordsrvaddon.resources.ResourceLoadingException) BufferedInputStream(java.io.BufferedInputStream) EOFException(java.io.EOFException) ArrayList(java.util.ArrayList) List(java.util.List) Int2ObjectOpenHashMap(it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap) InputStreamReader(java.io.InputStreamReader) GlyphSize(com.loohp.interactivechatdiscordsrvaddon.resources.fonts.LegacyUnicodeFont.GlyphSize) JSONArray(com.loohp.interactivechat.libs.org.json.simple.JSONArray) DataInputStream(java.io.DataInputStream) ResourceLoadingException(com.loohp.interactivechatdiscordsrvaddon.resources.ResourceLoadingException) EOFException(java.io.EOFException) JSONObject(com.loohp.interactivechat.libs.org.json.simple.JSONObject) AffineTransform(java.awt.geom.AffineTransform) ResourcePackFile(com.loohp.interactivechatdiscordsrvaddon.resources.ResourcePackFile) JSONParser(com.loohp.interactivechat.libs.org.json.simple.parser.JSONParser) JSONObject(com.loohp.interactivechat.libs.org.json.simple.JSONObject)

Example 4 with JSONObject

use of com.loohp.interactivechat.libs.org.json.simple.JSONObject in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class ResourceDownloadManager method ensureData.

private void ensureData() {
    if (data == null || assetIndex == null) {
        data = HTTPRequestUtils.getJSONResponse(ASSETS_DATA_URL.replace("%s", minecraftVersion));
        JSONObject client = (JSONObject) data.get("client-entries");
        assetIndex = HTTPRequestUtils.getJSONResponse(client.get("asset-index").toString());
    }
}
Also used : JSONObject(com.loohp.interactivechat.libs.org.json.simple.JSONObject)

Example 5 with JSONObject

use of com.loohp.interactivechat.libs.org.json.simple.JSONObject in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class ResourceDownloadManager method downloadLanguages.

public synchronized void downloadLanguages(TriConsumer<TaskType, String, Double> progressListener) {
    ensureData();
    JSONObject json = (JSONObject) assetIndex.get("objects");
    Map<String, String> langEntries = new LinkedHashMap<>();
    for (Object obj : json.keySet()) {
        String key = (String) obj;
        if (key.startsWith("minecraft/lang/")) {
            langEntries.put(key, ((JSONObject) json.get(key)).get("hash").toString());
        }
    }
    File assetsFolder = new File(packFolder, "assets");
    assetsFolder.mkdirs();
    int size = langEntries.size();
    int i = 0;
    for (Entry<String, String> entry : langEntries.entrySet()) {
        String name = entry.getKey();
        String hash = entry.getValue();
        double percentage = ((double) ++i / (double) size) * 100;
        progressListener.accept(TaskType.DOWNLOAD, "assets/" + name, percentage);
        File file = name.isEmpty() || name.equals("/") ? assetsFolder : new File(assetsFolder, name);
        file.getParentFile().mkdirs();
        if (file.exists()) {
            file.delete();
        }
        HTTPRequestUtils.download(file, MOJANG_RESOURCES_URL + hash.substring(0, 2) + "/" + hash);
    }
    progressListener.accept(TaskType.DONE, "", 100.0);
}
Also used : JSONObject(com.loohp.interactivechat.libs.org.json.simple.JSONObject) JSONObject(com.loohp.interactivechat.libs.org.json.simple.JSONObject) File(java.io.File) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

JSONObject (com.loohp.interactivechat.libs.org.json.simple.JSONObject)21 JSONParser (com.loohp.interactivechat.libs.org.json.simple.parser.JSONParser)11 InputStreamReader (java.io.InputStreamReader)7 BufferedImage (java.awt.image.BufferedImage)6 HashMap (java.util.HashMap)6 BOMInputStream (com.loohp.interactivechat.libs.org.apache.commons.io.input.BOMInputStream)5 File (java.io.File)5 ArrayList (java.util.ArrayList)5 JSONArray (com.loohp.interactivechat.libs.org.json.simple.JSONArray)4 ResourceLoadingException (com.loohp.interactivechatdiscordsrvaddon.resources.ResourceLoadingException)4 ResourcePackFile (com.loohp.interactivechatdiscordsrvaddon.resources.ResourcePackFile)4 IOException (java.io.IOException)4 ICPlayer (com.loohp.interactivechat.objectholders.ICPlayer)3 OfflineICPlayer (com.loohp.interactivechat.objectholders.OfflineICPlayer)3 ModelOverrideType (com.loohp.interactivechatdiscordsrvaddon.resources.models.ModelOverride.ModelOverrideType)3 LinkedHashMap (java.util.LinkedHashMap)3 Gson (com.google.gson.Gson)2 GsonBuilder (com.google.gson.GsonBuilder)2 JsonParser (com.google.gson.JsonParser)2 XMaterial (com.loohp.interactivechat.libs.com.cryptomorin.xseries.XMaterial)2