Skip to content

Instantly share code, notes, and snippets.

@tterrag1098
Created January 20, 2016 00:44
Show Gist options
  • Save tterrag1098/96bcca56c0ad56b36130 to your computer and use it in GitHub Desktop.
Save tterrag1098/96bcca56c0ad56b36130 to your computer and use it in GitHub Desktop.
public void download(final ImageType type) {
if (locations.get(type) == MISSING_TEXTURE) {
TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager();
final String filepath = "creations/" + owner.user_id + "/" + type.name() + "/" + owner.id;
final ResourceLocation res = new ResourceLocation(CTBMod.DOMAIN, filepath);
ITextureObject texture = texturemanager.getTexture(res);
if (texture == null) {
downloadExecutor.execute(new Runnable() {
@Override
@SneakyThrows
public void run() {
String url = parent.links.get(type);
File cacheJPG = new File(DataCache.cacheFolder, filepath + ".jpg");
File cachePNG = new File(DataCache.cacheFolder, filepath + ".png");
if (!(cacheJPG.exists() || cachePNG.exists())) {
File outputFile = cacheJPG;
try {
InputStream in = new URL(url).openStream();
try {
byte[] buf = new byte[4096];
int n = 0;
while (n < buf.length) {
int read = in.read(buf, n, buf.length - n);
if (read <= 0)
break;
n += read;
}
if (n < 8) {
throw new IOException("File too small for an image");
}
if (PNGDecoder.checkSignature(buf)) {
outputFile = cachePNG;
}
outputFile.getParentFile().mkdirs();
outputFile.createNewFile();
FileOutputStream fos = new FileOutputStream(outputFile);
try {
do {
fos.write(buf, 0, n);
n = in.read(buf);
} while (n > 0);
} finally {
fos.close();
}
} finally {
in.close();
}
} catch (IOException e) {
throw new RuntimeException(String.format("Could not save image %s to %s.", outputFile.getName(), outputFile.getAbsolutePath()), e);
}
}
final File cache = cacheJPG.exists() ? cacheJPG : cachePNG;
// Do this on the main thread with GL context
Minecraft.getMinecraft().addScheduledTask(new Runnable() {
@Override
@SneakyThrows
public void run() {
Texture image = Texture.loadTexture(cache.toURI().toURL());
RescaledTexture texture = new RescaledTexture(image);
Minecraft.getMinecraft().getTextureManager().loadTexture(res, texture);
// Don't populate size and location data until after the texture is loaded
sizes.put(type, Size.create(image));
locations.put(type, res);
}
});
}
});
} else if (texture instanceof RescaledTexture) {
// Grab cached size data
sizes.put(type, ((RescaledTexture) texture).getSize());
locations.put(type, res);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment