diff --git a/src/main/java/eu/crushedpixel/replaymod/ReplayMod.java b/src/main/java/eu/crushedpixel/replaymod/ReplayMod.java index c6cfd652..17b64ae8 100755 --- a/src/main/java/eu/crushedpixel/replaymod/ReplayMod.java +++ b/src/main/java/eu/crushedpixel/replaymod/ReplayMod.java @@ -1,17 +1,18 @@ package eu.crushedpixel.replaymod; -import java.io.File; -import java.io.IOException; - -import javax.swing.JOptionPane; - +import eu.crushedpixel.replaymod.api.client.ApiClient; +import eu.crushedpixel.replaymod.chat.ChatMessageHandler; +import eu.crushedpixel.replaymod.events.*; +import eu.crushedpixel.replaymod.recording.ConnectionEventHandler; import eu.crushedpixel.replaymod.registry.FileCopyHandler; -import org.apache.commons.io.FilenameUtils; - +import eu.crushedpixel.replaymod.registry.KeybindRegistry; +import eu.crushedpixel.replaymod.renderer.SafeEntityRenderer; +import eu.crushedpixel.replaymod.replay.ReplaySender; +import eu.crushedpixel.replaymod.settings.ReplaySettings; +import eu.crushedpixel.replaymod.utils.ReplayFileIO; import net.minecraft.client.Minecraft; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Configuration; -import net.minecraftforge.common.config.Property; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; @@ -19,114 +20,95 @@ import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; -import eu.crushedpixel.replaymod.api.client.ApiClient; -import eu.crushedpixel.replaymod.api.client.ApiException; -import eu.crushedpixel.replaymod.events.GuiEventHandler; -import eu.crushedpixel.replaymod.events.GuiReplayOverlay; -import eu.crushedpixel.replaymod.events.KeyInputHandler; -import eu.crushedpixel.replaymod.events.RecordingHandler; -import eu.crushedpixel.replaymod.events.TickAndRenderListener; -import eu.crushedpixel.replaymod.gui.GuiReplaySaving; -import eu.crushedpixel.replaymod.online.authentication.AuthenticationHandler; -import eu.crushedpixel.replaymod.recording.ConnectionEventHandler; -import eu.crushedpixel.replaymod.registry.KeybindRegistry; -import eu.crushedpixel.replaymod.registry.LightingHandler; -import eu.crushedpixel.replaymod.renderer.SafeEntityRenderer; -import eu.crushedpixel.replaymod.settings.ReplaySettings; -import eu.crushedpixel.replaymod.utils.ReplayFileIO; +import org.apache.commons.io.FilenameUtils; + +import java.io.File; @Mod(modid = ReplayMod.MODID, version = ReplayMod.VERSION) -public class ReplayMod -{ +public class ReplayMod { - //TODO: Set ReplayHandler replaying to false when replay is exited - //TODO: Hide Titles upon hurrying - //TODO: Override Enchantment Rendering for items when replaying (to adjust speed of animation) + //TODO: Set ReplayHandler replaying to false when replay is exited + //TODO: Hide Titles upon hurrying + //TODO: Override Enchantment Rendering for items when replaying (to adjust speed of animation) - //TODO: Show the player whether he has already uploaded a replay + //TODO: Show the player whether he has already uploaded a replay - //TODO: Hinting to the b/v key feature + //TODO: Hinting to the b/v key feature - //XXX - //Known Bugs - // - //Keyframes have problems with Linear Paths - //Rain isn't working - //Incompatible with Shaders Mod - // - // + //XXX + //Known Bugs + // + //Keyframes have problems with Linear Paths + //Rain isn't working + //Incompatible with Shaders Mod + // + // - public static final String MODID = "replaymod"; - public static final String VERSION = "0.0.1"; + public static final String MODID = "replaymod"; + public static final String VERSION = "0.0.1"; + public static final ApiClient apiClient = new ApiClient(); + private static final Minecraft mc = Minecraft.getMinecraft(); + public static GuiReplayOverlay overlay = new GuiReplayOverlay(); + public static ReplaySettings replaySettings; + public static Configuration config; + public static boolean firstMainMenu = true; + public static RecordingHandler recordingHandler; + public static ChatMessageHandler chatMessageHandler = new ChatMessageHandler(); + public static ReplaySender replaySender; + public static int TP_DISTANCE_LIMIT = 128; + public static FileCopyHandler fileCopyHandler; - private static final Minecraft mc = Minecraft.getMinecraft(); + // The instance of your mod that Forge uses. + @Instance(value = "ReplayModID") + public static ReplayMod instance; - public static GuiReplayOverlay overlay = new GuiReplayOverlay(); + @EventHandler + public void preInit(FMLPreInitializationEvent event) { + config = new Configuration(event.getSuggestedConfigurationFile()); + config.load(); - public static ReplaySettings replaySettings; - public static Configuration config; + replaySettings = new ReplaySettings(); + replaySettings.readValues(); - public static boolean firstMainMenu = true; + fileCopyHandler = new FileCopyHandler(); + fileCopyHandler.start(); + } - public static RecordingHandler recordingHandler; + @EventHandler + public void init(FMLInitializationEvent event) { + FMLCommonHandler.instance().bus().register(new ConnectionEventHandler()); + MinecraftForge.EVENT_BUS.register(new GuiEventHandler()); - public static int TP_DISTANCE_LIMIT = 128; + FMLCommonHandler.instance().bus().register(new KeyInputHandler()); - public static final ApiClient apiClient = new ApiClient(); + recordingHandler = new RecordingHandler(); + FMLCommonHandler.instance().bus().register(recordingHandler); + MinecraftForge.EVENT_BUS.register(recordingHandler); + } - public static FileCopyHandler fileCopyHandler; + @EventHandler + public void postInit(FMLPostInitializationEvent event) { + overlay = new GuiReplayOverlay(); + FMLCommonHandler.instance().bus().register(overlay); + MinecraftForge.EVENT_BUS.register(overlay); - // The instance of your mod that Forge uses. - @Instance(value = "ReplayModID") - public static ReplayMod instance; + TickAndRenderListener tarl = new TickAndRenderListener(); + FMLCommonHandler.instance().bus().register(tarl); + MinecraftForge.EVENT_BUS.register(tarl); - @EventHandler - public void preInit(FMLPreInitializationEvent event) { - config = new Configuration(event.getSuggestedConfigurationFile()); - config.load(); + KeybindRegistry.initialize(); - replaySettings = new ReplaySettings(); - replaySettings.readValues(); + try { + mc.entityRenderer = new SafeEntityRenderer(mc, mc.entityRenderer); + } catch(Exception e) { + e.printStackTrace(); + } - fileCopyHandler = new FileCopyHandler(); - fileCopyHandler.start(); - } + //clean up replay_recordings folder + removeTmcprFiles(); - @EventHandler - public void init(FMLInitializationEvent event) { - FMLCommonHandler.instance().bus().register(new ConnectionEventHandler()); - MinecraftForge.EVENT_BUS.register(new GuiEventHandler()); - - FMLCommonHandler.instance().bus().register(new KeyInputHandler()); - - recordingHandler = new RecordingHandler(); - FMLCommonHandler.instance().bus().register(recordingHandler); - MinecraftForge.EVENT_BUS.register(recordingHandler); - } - - @EventHandler - public void postInit(FMLPostInitializationEvent event) { - overlay = new GuiReplayOverlay(); - FMLCommonHandler.instance().bus().register(overlay); - MinecraftForge.EVENT_BUS.register(overlay); - - TickAndRenderListener tarl = new TickAndRenderListener(); - FMLCommonHandler.instance().bus().register(tarl); - MinecraftForge.EVENT_BUS.register(tarl); - - KeybindRegistry.initialize(); - - try { - mc.entityRenderer = new SafeEntityRenderer(mc, mc.entityRenderer); - } catch(Exception e) { - e.printStackTrace(); - } - - //clean up replay_recordings folder - removeTmcprFiles(); - - - boolean auth = false; + /* + boolean auth = false; try { auth = AuthenticationHandler.hasDonated(Minecraft.getMinecraft().getSession().getPlayerID()); } catch(Exception e) { @@ -138,16 +120,16 @@ public class ReplayMod JOptionPane.showMessageDialog(null, "It seems like you didn't donate, so you can't use the Replay Mod yet."); FMLCommonHandler.instance().exitJava(0, false); } + */ + } - } + private void removeTmcprFiles() { + File folder = ReplayFileIO.getReplayFolder(); - private void removeTmcprFiles() { - File folder = ReplayFileIO.getReplayFolder(); - - for(File f : folder.listFiles()) { - if(("."+FilenameUtils.getExtension(f.getAbsolutePath())).equals(ConnectionEventHandler.TEMP_FILE_EXTENSION)) { - f.delete(); - } - } - } + for(File f : folder.listFiles()) { + if(("." + FilenameUtils.getExtension(f.getAbsolutePath())).equals(ConnectionEventHandler.TEMP_FILE_EXTENSION)) { + f.delete(); + } + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/api/client/ApiClient.java b/src/main/java/eu/crushedpixel/replaymod/api/client/ApiClient.java index efcb2ea1..916810fe 100755 --- a/src/main/java/eu/crushedpixel/replaymod/api/client/ApiClient.java +++ b/src/main/java/eu/crushedpixel/replaymod/api/client/ApiClient.java @@ -1,5 +1,12 @@ package eu.crushedpixel.replaymod.api.client; +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import eu.crushedpixel.replaymod.api.client.holders.*; +import eu.crushedpixel.replaymod.utils.StreamTools; +import org.apache.commons.io.FileUtils; + import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -9,143 +16,129 @@ import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.List; -import org.apache.commons.io.FileUtils; - -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; - -import eu.crushedpixel.replaymod.api.client.holders.ApiError; -import eu.crushedpixel.replaymod.api.client.holders.AuthKey; -import eu.crushedpixel.replaymod.api.client.holders.Donated; -import eu.crushedpixel.replaymod.api.client.holders.FileInfo; -import eu.crushedpixel.replaymod.api.client.holders.SearchResult; -import eu.crushedpixel.replaymod.api.client.holders.Success; -import eu.crushedpixel.replaymod.api.client.holders.UserFiles; -import eu.crushedpixel.replaymod.utils.StreamTools; - public class ApiClient { - private static Gson gson = new Gson(); - private static JsonParser jsonParser = new JsonParser(); + private static final Gson gson = new Gson(); + private static final JsonParser jsonParser = new JsonParser(); - public AuthKey getLogin(String username, String password) throws IOException, ApiException { - QueryBuilder builder = new QueryBuilder(ApiMethods.login); - builder.put("user", username); - builder.put("pw", password); - AuthKey auth = invokeAndReturn(builder, AuthKey.class); - return auth; - } + public AuthKey getLogin(String username, String password) throws IOException, ApiException { + QueryBuilder builder = new QueryBuilder(ApiMethods.login); + builder.put("user", username); + builder.put("pw", password); + AuthKey auth = invokeAndReturn(builder, AuthKey.class); + return auth; + } - public boolean logout(String auth) throws IOException, ApiException { - QueryBuilder builder = new QueryBuilder(ApiMethods.logout); - builder.put("auth", auth); - Success succ = invokeAndReturn(builder, Success.class); - return succ.isSuccess(); - } + public boolean logout(String auth) throws IOException, ApiException { + QueryBuilder builder = new QueryBuilder(ApiMethods.logout); + builder.put("auth", auth); + Success succ = invokeAndReturn(builder, Success.class); + return succ.isSuccess(); + } - public boolean hasDonated(String uuid) throws IOException, ApiException { - QueryBuilder builder = new QueryBuilder(ApiMethods.check_auth); - builder.put("uuid", uuid); - Donated succ = invokeAndReturn(builder, Donated.class); - return succ.hasDonated(); - } - - public UserFiles getUserFiles(String auth, String user) throws IOException, ApiException { - QueryBuilder builder = new QueryBuilder(ApiMethods.replay_files); - builder.put("auth", auth); - builder.put("user", user); - UserFiles files = invokeAndReturn(builder, UserFiles.class); - return files; - } + public boolean hasDonated(String uuid) throws IOException, ApiException { + QueryBuilder builder = new QueryBuilder(ApiMethods.check_auth); + builder.put("uuid", uuid); + Donated succ = invokeAndReturn(builder, Donated.class); + return succ.hasDonated(); + } - public FileInfo[] getFileInfo(String auth, List ids) throws IOException, ApiException { - QueryBuilder builder = new QueryBuilder(ApiMethods.replay_files); - builder.put("auth", auth); - builder.put("ids", buildListString(ids)); - FileInfo[] info = invokeAndReturn(builder, FileInfo[].class); - return info; - } - - public FileInfo[] searchFiles(SearchQuery query) throws IOException, ApiException { - StringBuilder sb = new StringBuilder(); + public UserFiles getUserFiles(String auth, String user) throws IOException, ApiException { + QueryBuilder builder = new QueryBuilder(ApiMethods.replay_files); + builder.put("auth", auth); + builder.put("user", user); + UserFiles files = invokeAndReturn(builder, UserFiles.class); + return files; + } - // build base url - sb.append(QueryBuilder.API_BASE_URL); - sb.append("search"); - sb.append(query.buildQuery()); - - FileInfo[] info = invokeAndReturn(sb.toString(), SearchResult.class).getResults(); - return info; - } - - public void downloadThumbnail(int file, File target) throws IOException { - QueryBuilder builder = new QueryBuilder(ApiMethods.get_thumbnail); - builder.put("id", file); - URL url = new URL(builder.toString()); - FileUtils.copyURLToFile(url, target); - } + public FileInfo[] getFileInfo(String auth, List ids) throws IOException, ApiException { + QueryBuilder builder = new QueryBuilder(ApiMethods.replay_files); + builder.put("auth", auth); + builder.put("ids", buildListString(ids)); + FileInfo[] info = invokeAndReturn(builder, FileInfo[].class); + return info; + } - public void downloadFile(String auth, int file, File target) throws IOException { - QueryBuilder builder = new QueryBuilder(ApiMethods.download_file); - builder.put("auth", auth); - builder.put("id", file); - String url = builder.toString(); - URL website = new URL(url); - HttpURLConnection con = (HttpURLConnection)website.openConnection(); - InputStream is = con.getInputStream(); + public FileInfo[] searchFiles(SearchQuery query) throws IOException, ApiException { + StringBuilder sb = new StringBuilder(); - if(con.getResponseCode() == 200) { - Files.copy(is, target.toPath(), StandardCopyOption.REPLACE_EXISTING); - } else { - JsonElement element = jsonParser.parse(StreamTools.readStreamtoString(is)); - try { - ApiError err = gson.fromJson(element, ApiError.class); - if(err.getDesc() != null) { - throw new ApiException(err); - } - } catch(Exception e) {} - } - } + // build base url + sb.append(QueryBuilder.API_BASE_URL); + sb.append("search"); + sb.append(query.buildQuery()); - public void rateFile(String auth, int file, boolean like) throws IOException, ApiException { - QueryBuilder builder = new QueryBuilder(ApiMethods.rate_file); - builder.put("auth", auth); - builder.put("id", file); - builder.put("like", like); - invokeAndReturn(builder, Success.class); - } + FileInfo[] info = invokeAndReturn(sb.toString(), SearchResult.class).getResults(); + return info; + } - public void removeFile(String auth, int file) throws IOException, ApiException { - QueryBuilder builder = new QueryBuilder(ApiMethods.remove_file); - builder.put("auth", auth); - builder.put("id", file); - invokeAndReturn(builder, Success.class); - } + public void downloadThumbnail(int file, File target) throws IOException { + QueryBuilder builder = new QueryBuilder(ApiMethods.get_thumbnail); + builder.put("id", file); + URL url = new URL(builder.toString()); + FileUtils.copyURLToFile(url, target); + } - private T invokeAndReturn(QueryBuilder builder, Class classOfT) throws IOException, ApiException { - return invokeAndReturn(builder.toString(), classOfT); - } - - private T invokeAndReturn(String url, Class classOfT) throws IOException, ApiException { - JsonElement ele = GsonApiClient.invokeJson(url); - return gson.fromJson(ele, classOfT); - } + public void downloadFile(String auth, int file, File target) throws IOException { + QueryBuilder builder = new QueryBuilder(ApiMethods.download_file); + builder.put("auth", auth); + builder.put("id", file); + String url = builder.toString(); + URL website = new URL(url); + HttpURLConnection con = (HttpURLConnection) website.openConnection(); + InputStream is = con.getInputStream(); - @SuppressWarnings("rawtypes") - private String buildListString(List idList) { - if(idList == null) return null; + if(con.getResponseCode() == 200) { + Files.copy(is, target.toPath(), StandardCopyOption.REPLACE_EXISTING); + } else { + JsonElement element = jsonParser.parse(StreamTools.readStreamtoString(is)); + try { + ApiError err = gson.fromJson(element, ApiError.class); + if(err.getDesc() != null) { + throw new ApiException(err); + } + } catch(Exception e) { + } + } + } - String ids = ""; - Integer x=0; - for(Object id : idList) { - x++; - ids += id.toString(); - if(x != idList.size()) { - ids += ","; - } - } + public void rateFile(String auth, int file, boolean like) throws IOException, ApiException { + QueryBuilder builder = new QueryBuilder(ApiMethods.rate_file); + builder.put("auth", auth); + builder.put("id", file); + builder.put("like", like); + invokeAndReturn(builder, Success.class); + } - return ids; - } + public void removeFile(String auth, int file) throws IOException, ApiException { + QueryBuilder builder = new QueryBuilder(ApiMethods.remove_file); + builder.put("auth", auth); + builder.put("id", file); + invokeAndReturn(builder, Success.class); + } + + private T invokeAndReturn(QueryBuilder builder, Class classOfT) throws IOException, ApiException { + return invokeAndReturn(builder.toString(), classOfT); + } + + private T invokeAndReturn(String url, Class classOfT) throws IOException, ApiException { + JsonElement ele = GsonApiClient.invokeJson(url); + return gson.fromJson(ele, classOfT); + } + + @SuppressWarnings("rawtypes") + private String buildListString(List idList) { + if(idList == null) return null; + + String ids = ""; + Integer x = 0; + for(Object id : idList) { + x++; + ids += id.toString(); + if(x != idList.size()) { + ids += ","; + } + } + + return ids; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/api/client/ApiException.java b/src/main/java/eu/crushedpixel/replaymod/api/client/ApiException.java index 421a054f..add2086b 100755 --- a/src/main/java/eu/crushedpixel/replaymod/api/client/ApiException.java +++ b/src/main/java/eu/crushedpixel/replaymod/api/client/ApiException.java @@ -4,17 +4,17 @@ import eu.crushedpixel.replaymod.api.client.holders.ApiError; public class ApiException extends Exception { - private static final long serialVersionUID = 349073390504232810L; + private static final long serialVersionUID = 349073390504232810L; - private ApiError error; - - public ApiException(ApiError error) { - super(error.getDesc()); - this.error = error; - } - - public ApiError getError() { - return error; - } + private ApiError error; + + public ApiException(ApiError error) { + super(error.getDesc()); + this.error = error; + } + + public ApiError getError() { + return error; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/api/client/ApiMethods.java b/src/main/java/eu/crushedpixel/replaymod/api/client/ApiMethods.java index eb2d04da..029d64cb 100755 --- a/src/main/java/eu/crushedpixel/replaymod/api/client/ApiMethods.java +++ b/src/main/java/eu/crushedpixel/replaymod/api/client/ApiMethods.java @@ -1,16 +1,16 @@ package eu.crushedpixel.replaymod.api.client; public class ApiMethods { - - public static final String login = "login"; - public static final String logout = "logout"; - public static final String replay_files = "replay_files"; - public static final String file_details = "file_details"; - public static final String upload_file = "upload_file"; - public static final String download_file = "download_file"; - public static final String get_thumbnail = "get_thumbnail"; - public static final String remove_file = "remove_file"; - public static final String rate_file = "rate_file"; - public static final String check_auth = "check_auth"; - + + public static final String login = "login"; + public static final String logout = "logout"; + public static final String replay_files = "replay_files"; + public static final String file_details = "file_details"; + public static final String upload_file = "upload_file"; + public static final String download_file = "download_file"; + public static final String get_thumbnail = "get_thumbnail"; + public static final String remove_file = "remove_file"; + public static final String rate_file = "rate_file"; + public static final String check_auth = "check_auth"; + } diff --git a/src/main/java/eu/crushedpixel/replaymod/api/client/FileUploader.java b/src/main/java/eu/crushedpixel/replaymod/api/client/FileUploader.java index 09806e6a..481f33a5 100755 --- a/src/main/java/eu/crushedpixel/replaymod/api/client/FileUploader.java +++ b/src/main/java/eu/crushedpixel/replaymod/api/client/FileUploader.java @@ -1,160 +1,149 @@ package eu.crushedpixel.replaymod.api.client; -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; +import com.google.gson.Gson; +import eu.crushedpixel.replaymod.api.client.holders.ApiError; +import eu.crushedpixel.replaymod.api.client.holders.Category; +import eu.crushedpixel.replaymod.gui.online.GuiUploadFile; + +import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; -import com.google.gson.Gson; -import com.google.gson.JsonParser; - -import eu.crushedpixel.replaymod.api.client.holders.ApiError; -import eu.crushedpixel.replaymod.api.client.holders.Category; -import eu.crushedpixel.replaymod.gui.online.GuiUploadFile; - public class FileUploader { - private static Gson gson = new Gson(); - private static JsonParser jsonParser = new JsonParser(); + private static final Gson gson = new Gson(); - private boolean uploading = false; - private long filesize; - private long current; + private boolean uploading = false; + private long filesize; + private long current; - private String attachmentName = "file"; - private String attachmentFileName = "file.mcpr"; - private String crlf = "\r\n"; - private String twoHyphens = "--"; + private String attachmentName = "file"; + private String attachmentFileName = "file.mcpr"; + private String crlf = "\r\n"; + private String twoHyphens = "--"; - private boolean cancel = false; + private boolean cancel = false; - private String boundary = "*****"; - private GuiUploadFile parent; - //private CountingHttpEntity counter; + private String boundary = "*****"; + private GuiUploadFile parent; - public void uploadFile(GuiUploadFile gui, String auth, String filename, List tags, File file, Category category) throws IOException, ApiException, RuntimeException { - parent = gui; - gui.onStartUploading(); - filesize = 0; + public void uploadFile(GuiUploadFile gui, String auth, String filename, List tags, File file, Category category) throws IOException, ApiException, RuntimeException { + parent = gui; + gui.onStartUploading(); + filesize = 0; - if(uploading) throw new RuntimeException("FileUploader is already uploading"); - uploading = true; + if(uploading) throw new RuntimeException("FileUploader is already uploading"); + uploading = true; - String postData = "?auth="+auth+"&category="+category.getId(); + String postData = "?auth=" + auth + "&category=" + category.getId(); - if(tags.size() > 0) { - postData += "&tags="; - for(String tag : tags) { - postData += tag; - if(!tag.equals(tags.get(tags.size()-1))) { - postData += ","; - } - } - } + if(tags.size() > 0) { + postData += "&tags="; + for(String tag : tags) { + postData += tag; + if(!tag.equals(tags.get(tags.size() - 1))) { + postData += ","; + } + } + } - postData +="&name="+URLEncoder.encode(filename, "UTF-8"); - System.out.println(postData); + postData += "&name=" + URLEncoder.encode(filename, "UTF-8"); + System.out.println(postData); - String url = "http://ReplayMod.com/api/upload_file"+postData; - HttpURLConnection con = (HttpURLConnection)new URL(url).openConnection(); - con.setUseCaches(false); - con.setDoOutput(true); - con.setRequestMethod("POST"); - con.setChunkedStreamingMode(1024); - con.setRequestProperty("Connection", "Keep-Alive"); - con.setRequestProperty("Cache-Control", "no-cache"); - con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + this.boundary); + String url = "http://ReplayMod.com/api/upload_file" + postData; + HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); + con.setUseCaches(false); + con.setDoOutput(true); + con.setRequestMethod("POST"); + con.setChunkedStreamingMode(1024); + con.setRequestProperty("Connection", "Keep-Alive"); + con.setRequestProperty("Cache-Control", "no-cache"); + con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + this.boundary); - HashMap params = new HashMap(); - params.put("auth", auth); - params.put("name", filename); - params.put("category", category.getId()+""); + HashMap params = new HashMap(); + params.put("auth", auth); + params.put("name", filename); + params.put("category", category.getId() + ""); - DataOutputStream request = new DataOutputStream(con.getOutputStream()); + DataOutputStream request = new DataOutputStream(con.getOutputStream()); - request.writeBytes(this.twoHyphens + this.boundary + this.crlf); - request.writeBytes("Content-Disposition: form-data; name=\"" + this.attachmentName + "\";filename=\"" + this.attachmentFileName + "\"" + this.crlf); - request.writeBytes(this.crlf); + request.writeBytes(this.twoHyphens + this.boundary + this.crlf); + request.writeBytes("Content-Disposition: form-data; name=\"" + this.attachmentName + "\";filename=\"" + this.attachmentFileName + "\"" + this.crlf); + request.writeBytes(this.crlf); - byte[] buf = new byte[1024]; - FileInputStream fis = new FileInputStream(file); - filesize = fis.getChannel().size(); - current = 0; - int len; - while((len = fis.read(buf)) != -1) { - request.write(buf); - current += len; - if(cancel) { - uploading = false; - current = 0; - cancel = false; - parent.onFinishUploading(false, "Upload has been canceled"); - fis.close(); - return; - } - } - fis.close(); + byte[] buf = new byte[1024]; + FileInputStream fis = new FileInputStream(file); + filesize = fis.getChannel().size(); + current = 0; + int len; + while((len = fis.read(buf)) != -1) { + request.write(buf); + current += len; + if(cancel) { + uploading = false; + current = 0; + cancel = false; + parent.onFinishUploading(false, "Upload has been canceled"); + fis.close(); + return; + } + } + fis.close(); - request.writeBytes(this.crlf); - request.writeBytes(this.twoHyphens + this.boundary + this.twoHyphens + this.crlf); + request.writeBytes(this.crlf); + request.writeBytes(this.twoHyphens + this.boundary + this.twoHyphens + this.crlf); - request.flush(); - request.close(); + request.flush(); + request.close(); - boolean success = false; - int responseCode = con.getResponseCode(); - InputStream is = null; - if(responseCode == 200) { - success = true; - is = con.getInputStream(); - } else { - is = con.getErrorStream(); - } + boolean success = false; + int responseCode = con.getResponseCode(); + InputStream is = null; + if(responseCode == 200) { + success = true; + is = con.getInputStream(); + } else { + is = con.getErrorStream(); + } - String info = null; - - if(is != null) { - BufferedReader r = new BufferedReader(new InputStreamReader(is)); - info = null; - if(responseCode != 200) { - ApiError error = new ApiError(-1, "An unknown error occured"); - String json = ""; - while(r.ready()) { - json += r.readLine(); - } - error = gson.fromJson(json, ApiError.class); - info = error.getDesc(); - System.out.println(info); - } - } + String info = null; + + if(is != null) { + BufferedReader r = new BufferedReader(new InputStreamReader(is)); + info = null; + if(responseCode != 200) { + String json = ""; + while(r.ready()) { + json += r.readLine(); + } + ApiError error = gson.fromJson(json, ApiError.class); + info = error.getDesc(); + System.out.println(info); + } + } - con.disconnect(); + con.disconnect(); - if(info == null) info = "An unknown error occured"; - - parent.onFinishUploading(success, info); + if(info == null) info = "An unknown error occured"; - uploading = false; - } + parent.onFinishUploading(success, info); - public float getUploadProgress() { - if(!uploading || filesize == 0) return 0; - return (float)((double)current/(double)filesize); - } + uploading = false; + } - public boolean isUploading() { - return uploading; - } + public float getUploadProgress() { + if(!uploading || filesize == 0) return 0; + return (float) ((double) current / (double) filesize); + } - public void cancelUploading() { - cancel = true; - } + public boolean isUploading() { + return uploading; + } + + public void cancelUploading() { + cancel = true; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/api/client/GsonApiClient.java b/src/main/java/eu/crushedpixel/replaymod/api/client/GsonApiClient.java index 193b7fbc..4f7d40bd 100755 --- a/src/main/java/eu/crushedpixel/replaymod/api/client/GsonApiClient.java +++ b/src/main/java/eu/crushedpixel/replaymod/api/client/GsonApiClient.java @@ -1,38 +1,37 @@ package eu.crushedpixel.replaymod.api.client; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; + import java.io.IOException; import java.util.Map; -import com.google.gson.JsonObject; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; +public class GsonApiClient { -public class GsonApiClient { + private static final JsonParser parser = new JsonParser(); - private static final JsonParser parser = new JsonParser(); - - public static JsonElement invoke(QueryBuilder query) throws IOException, ApiException { - String apiResult = SimpleApiClient.invoke(query); - return wrapWithJson(apiResult); - } + public static JsonElement invoke(QueryBuilder query) throws IOException, ApiException { + String apiResult = SimpleApiClient.invoke(query); + return wrapWithJson(apiResult); + } - public static JsonElement invokeJson(String url) throws IOException, ApiException { - String apiResult = SimpleApiClient.invokeUrl(url); - return wrapWithJson(apiResult); - } + public static JsonElement invokeJson(String url) throws IOException, ApiException { + String apiResult = SimpleApiClient.invokeUrl(url); + return wrapWithJson(apiResult); + } - public static JsonElement invokeJson(String apiKey, String method, Map paramMap) throws IOException, ApiException { - String apiResult = SimpleApiClient.invoke(method, paramMap); - return wrapWithJson(apiResult); - } + public static JsonElement invokeJson(String apiKey, String method, Map paramMap) throws IOException, ApiException { + String apiResult = SimpleApiClient.invoke(method, paramMap); + return wrapWithJson(apiResult); + } - public static JsonElement invokeJson(String apiKey, String method) throws IOException, ApiException { - String apiResult = SimpleApiClient.invoke(method, null); - return wrapWithJson(apiResult); - } - - private static JsonElement wrapWithJson(String apiResult) { - JsonElement element = parser.parse(apiResult); - return element; - } + public static JsonElement invokeJson(String apiKey, String method) throws IOException, ApiException { + String apiResult = SimpleApiClient.invoke(method, null); + return wrapWithJson(apiResult); + } + + private static JsonElement wrapWithJson(String apiResult) { + JsonElement element = parser.parse(apiResult); + return element; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/api/client/QueryBuilder.java b/src/main/java/eu/crushedpixel/replaymod/api/client/QueryBuilder.java index d87aa8e4..cae87e84 100755 --- a/src/main/java/eu/crushedpixel/replaymod/api/client/QueryBuilder.java +++ b/src/main/java/eu/crushedpixel/replaymod/api/client/QueryBuilder.java @@ -7,160 +7,90 @@ import java.util.Map; public class QueryBuilder { - public static final String API_BASE_URL = "http://ReplayMod.com/api/"; + public static final String API_BASE_URL = "http://ReplayMod.com/api/"; - public String apiMethod; - public Map paramMap; + public String apiMethod; + public Map paramMap; - /** - * Creates an empty QueryBuilder from a given apikey. - *
Note that in order to use the QueryBuilder an apiMethod String has to be set. - * @param apiKey The apikey to use - */ - public QueryBuilder() { - this(null); - } + public QueryBuilder() { + this(null); + } - /** - * Creates an empty QueryBuilder from a given apikey and apiMethod. - * - * @param apiKey The apikey to use - * @param apiMethod The apiMethod to use - */ - public QueryBuilder(String apiMethod) { - this.apiMethod = apiMethod; - } + public QueryBuilder(String apiMethod) { + this.apiMethod = apiMethod; + } - /** - * Creates a QueryBuilder from a given apikey and apiMethod containing a single key/value parameter. - * - * @param apiKey The apikey to use - * @param apiMethod The apiMethod to use - * @param key The parameter key - * @param value The parameter value - */ - public QueryBuilder(String apiMethod, String key, String value) { - this(apiMethod); - put(key, value); - } + public QueryBuilder(String apiMethod, String key, String value) { + this(apiMethod); + put(key, value); + } - /** - * Creates a QueryBuilder from a given apikey and apiMethod containing two key/value parameters. - * - * @param apiKey The apikey to use - * @param apiMethod The apiMethod to use - * @param key1 The first parameter key - * @param value1 The first parameter value - * @param key2 The second parameter key - * @param value2 The second parameter value - */ - public QueryBuilder(String apiMethod, String key1, String value1, String key2, String value2) { - this(apiMethod); - put(key1, value1); - put(key2, value2); - } + public QueryBuilder(String apiMethod, String key1, String value1, String key2, String value2) { + this(apiMethod); + put(key1, value1); + put(key2, value2); + } - /** - * Creates a QueryBuilder from a given apikey and apiMethod containing three key/value parameters. - * - * @param apiKey The apikey to use - * @param apiMethod The apiMethod to use - * @param key1 The first parameter key - * @param value1 The first parameter value - * @param key2 The second parameter key - * @param value2 The second parameter value - * @param key3 The third parameter key - * @param value3 The third parameter value - */ - public QueryBuilder(String apiMethod, String key1, String value1, String key2, String value2, String key3, String value3) { - this(apiMethod); - put(key1, value1); - put(key2, value2); - put(key3, value3); - } + public QueryBuilder(String apiMethod, String key1, String value1, String key2, String value2, String key3, String value3) { + this(apiMethod); + put(key1, value1); + put(key2, value2); + put(key3, value3); + } - /** - * Adds a key/value parameter to the QueryBuilder. - * @param key The parameter key - * @param value The parameter value - */ - public void put(String key, Object value) { - if(key != null && value != null) { - if(paramMap == null) { - paramMap = new HashMap(); - } - paramMap.put(key, value.toString()); - } - } + public void put(String key, Object value) { + if(key != null && value != null) { + if(paramMap == null) { + paramMap = new HashMap(); + } + paramMap.put(key, value.toString()); + } + } - /** - * Adds two key/value parameters to the QueryBuilder. - * @param key1 The first parameter key - * @param value1 The first parameter value - * @param key2 The second parameter key - * @param value2 The second parameter value - */ - public void put(String key1, Object value1, String key2, Object value2) { - put(key1, value1); - put(key2, value2); - } + public void put(String key1, Object value1, String key2, Object value2) { + put(key1, value1); + put(key2, value2); + } - /** - * Adds three key/value parameters to the QueryBuilder. - * @param key1 The first parameter key - * @param value1 The first parameter value - * @param key2 The second parameter key - * @param value2 The second parameter value - * @param key3 The third parameter key - * @param value3 The third parameter value - */ - public void put(String key1, Object value1, String key2, Object value2, String key3, Object value3) { - put(key1, value1); - put(key2, value2); - put(key3, value3); - } + public void put(String key1, Object value1, String key2, Object value2, String key3, Object value3) { + put(key1, value1); + put(key2, value2); + put(key3, value3); + } - /** - * Adds a map of key/value parameters to the QueryBuilder. - * @param paraMap The map to add - */ - public void put(Map paraMap) { - if(paraMap == null) return; - for(String key: paraMap.keySet()) { - put(key,paraMap.get(key)); - } - } + public void put(Map paraMap) { + if(paraMap == null) return; + for(String key : paraMap.keySet()) { + put(key, paraMap.get(key)); + } + } - /** - * Creates an URL from the QueryBuilder using the given apikey and apiMethod and applies all - * parameters to it. - */ - public String toString() { - if(apiMethod == null) throw new IllegalArgumentException("apiMethod may not be null"); + public String toString() { + if(apiMethod == null) throw new IllegalArgumentException("apiMethod may not be null"); - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); - // build base url - sb.append(API_BASE_URL); - sb.append(apiMethod); + // build base url + sb.append(API_BASE_URL); + sb.append(apiMethod); - // process parameters - try { - if(paramMap != null) { - boolean first = true; - for(String paramName: paramMap.keySet()) { - if(first) sb.append("?"); - if(!first) sb.append("&"); - first = false; - sb.append(paramName); - sb.append("="); - String value = paramMap.get(paramName); - sb.append(URLEncoder.encode(value, "UTF-8")); - } - } - return sb.toString(); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - } + // process parameters + try { + if(paramMap != null) { + boolean first = true; + for(String paramName : paramMap.keySet()) { + if(first) sb.append("?"); + if(!first) sb.append("&"); + first = false; + sb.append(paramName); + sb.append("="); + String value = paramMap.get(paramName); + sb.append(URLEncoder.encode(value, "UTF-8")); + } + } + return sb.toString(); + } catch(UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/api/client/SearchPagination.java b/src/main/java/eu/crushedpixel/replaymod/api/client/SearchPagination.java index 2060261a..fe3fb34d 100755 --- a/src/main/java/eu/crushedpixel/replaymod/api/client/SearchPagination.java +++ b/src/main/java/eu/crushedpixel/replaymod/api/client/SearchPagination.java @@ -1,50 +1,49 @@ package eu.crushedpixel.replaymod.api.client; +import eu.crushedpixel.replaymod.ReplayMod; +import eu.crushedpixel.replaymod.api.client.holders.FileInfo; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import eu.crushedpixel.replaymod.ReplayMod; -import eu.crushedpixel.replaymod.api.client.holders.FileInfo; - public class SearchPagination { - private int page; - private List files = new ArrayList(); + private final SearchQuery searchQuery; + private int page; + private List files = new ArrayList(); - private final SearchQuery searchQuery; + public SearchPagination(SearchQuery searchQuery) { + this.page = -1; + this.searchQuery = searchQuery; + } - public SearchPagination(SearchQuery searchQuery) { - this.page = -1; - this.searchQuery = searchQuery; - } + public List getFiles() { + return new ArrayList(files); + } - public List getFiles() { - return new ArrayList(files); - } - - public int getLoadedPages() { - return page; - } + public int getLoadedPages() { + return page; + } - public boolean fetchPage() { - page++; - searchQuery.offset = page; + public boolean fetchPage() { + page++; + searchQuery.offset = page; - try { - FileInfo[] fis = ReplayMod.apiClient.searchFiles(searchQuery); - if(fis.length <= 1) { - page--; - return false; - } + try { + FileInfo[] fis = ReplayMod.apiClient.searchFiles(searchQuery); + if(fis.length <= 1) { + page--; + return false; + } - files.addAll(Arrays.asList(fis)); - - return true; - } catch(Exception e) { - e.printStackTrace(); - } - page--; - return false; - } + files.addAll(Arrays.asList(fis)); + + return true; + } catch(Exception e) { + e.printStackTrace(); + } + page--; + return false; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/api/client/SearchQuery.java b/src/main/java/eu/crushedpixel/replaymod/api/client/SearchQuery.java index 52d17a80..5dc9cdfc 100755 --- a/src/main/java/eu/crushedpixel/replaymod/api/client/SearchQuery.java +++ b/src/main/java/eu/crushedpixel/replaymod/api/client/SearchQuery.java @@ -5,51 +5,52 @@ import java.net.URLEncoder; public class SearchQuery { - public Boolean order, singleplayer; - public String player, tag, version, server, name, auth; - public Integer category, offset; + public Boolean order, singleplayer; + public String player, tag, version, server, name, auth; + public Integer category, offset; - public SearchQuery() {} + public SearchQuery() { + } - public SearchQuery(Boolean order, Boolean singleplayer, String player, - String tag, String version, String server, String name, - String auth, Integer category, Integer offset) { - this.order = order; - this.singleplayer = singleplayer; - this.player = player; - this.tag = tag; - this.version = version; - this.server = server; - this.name = name; - this.auth = auth; - this.category = category; - this.offset = offset; - } + public SearchQuery(Boolean order, Boolean singleplayer, String player, + String tag, String version, String server, String name, + String auth, Integer category, Integer offset) { + this.order = order; + this.singleplayer = singleplayer; + this.player = player; + this.tag = tag; + this.version = version; + this.server = server; + this.name = name; + this.auth = auth; + this.category = category; + this.offset = offset; + } - public String buildQuery() { - String query = ""; - boolean first = true; + public String buildQuery() { + String query = ""; + boolean first = true; - //Please don't slaughter me for this code, - //even if I deserve it, which I certainly do. - for(Field f : this.getClass().getDeclaredFields()) { - try { - Object value = f.get(this); - if(value == null) continue; - query += first ? "?" : "&"; - first = false; - query += f.getName()+"="; - query += URLEncoder.encode(String.valueOf(value), "UTF-8"); - } catch(Exception e) { - e.printStackTrace(); - } - } + //Please don't slaughter me for this code, + //even if I deserve it, which I certainly do. + for(Field f : this.getClass().getDeclaredFields()) { + try { + Object value = f.get(this); + if(value == null) continue; + query += first ? "?" : "&"; + first = false; + query += f.getName() + "="; + query += URLEncoder.encode(String.valueOf(value), "UTF-8"); + } catch(Exception e) { + e.printStackTrace(); + } + } - return query; - } + return query; + } - @Override - public String toString() { - return buildQuery(); - } + @Override + public String toString() { + return buildQuery(); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/api/client/SimpleApiClient.java b/src/main/java/eu/crushedpixel/replaymod/api/client/SimpleApiClient.java index 54c4b7dd..8d1352b4 100755 --- a/src/main/java/eu/crushedpixel/replaymod/api/client/SimpleApiClient.java +++ b/src/main/java/eu/crushedpixel/replaymod/api/client/SimpleApiClient.java @@ -1,120 +1,123 @@ package eu.crushedpixel.replaymod.api.client; +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import eu.crushedpixel.replaymod.api.client.holders.ApiError; +import eu.crushedpixel.replaymod.utils.StreamTools; + import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Map; -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; - -import eu.crushedpixel.replaymod.api.client.holders.ApiError; -import eu.crushedpixel.replaymod.utils.StreamTools; - public class SimpleApiClient { - private static final JsonParser jsonParser = new JsonParser(); - private static final Gson gson = new Gson(); - - /** - * Returns a Json String from the given QueryBuilder - * @param query The QueryBuilder to use - * @return A Json String from the API - * @throws IOException - * @throws ApiException - */ - public static String invoke(QueryBuilder query) throws IOException, ApiException { - return invokeImpl(query.toString()); - } + private static final JsonParser jsonParser = new JsonParser(); + private static final Gson gson = new Gson(); - /** - * Returns a Json String from the given URL - * @param url The URL to parse the Json from - * @return A Json String from the API - * @throws IOException - * @throws ApiException - */ - public static String invokeUrl(String url) throws IOException, ApiException { - return invokeImpl(url); - } + /** + * Returns a Json String from the given QueryBuilder + * + * @param query The QueryBuilder to use + * @return A Json String from the API + * @throws IOException + * @throws ApiException + */ + public static String invoke(QueryBuilder query) throws IOException, ApiException { + return invokeImpl(query.toString()); + } - /** - * Returns a Json String from the API - * @param apiKey The apikey to use - * @param method The apiMethod to be called - * @param paramMap The parameters to apply - * @return A Json String from the API - * @throws IOException - * @throws ApiException - */ - public static String invoke(String method, Map paramMap) throws IOException, ApiException { - return invokeImpl(method, paramMap); - } + /** + * Returns a Json String from the given URL + * + * @param url The URL to parse the Json from + * @return A Json String from the API + * @throws IOException + * @throws ApiException + */ + public static String invokeUrl(String url) throws IOException, ApiException { + return invokeImpl(url); + } - /** - * Returns a Json String from the API - * @param apiKey The apikey to use - * @param method The apiMethod to be called - * @return A Json String from the API - * @throws IOException - * @throws ApiException - */ - public static String invoke(String method) throws IOException, ApiException { - return invokeImpl(method, null); - } + /** + * Returns a Json String from the API + * + * @param apiKey The apikey to use + * @param method The apiMethod to be called + * @param paramMap The parameters to apply + * @return A Json String from the API + * @throws IOException + * @throws ApiException + */ + public static String invoke(String method, Map paramMap) throws IOException, ApiException { + return invokeImpl(method, paramMap); + } - private static String invokeImpl(String urlString) throws IOException, ApiException { + /** + * Returns a Json String from the API + * + * @param apiKey The apikey to use + * @param method The apiMethod to be called + * @return A Json String from the API + * @throws IOException + * @throws ApiException + */ + public static String invoke(String method) throws IOException, ApiException { + return invokeImpl(method, null); + } - // read response - String responseContent = null; - InputStream is = null; - HttpURLConnection httpUrlConnection = null; - HttpURLConnection.setFollowRedirects(false); - try { - URL url = new URL(urlString); - httpUrlConnection = (HttpURLConnection)url.openConnection(); + private static String invokeImpl(String urlString) throws IOException, ApiException { - httpUrlConnection.setRequestMethod("GET"); + // read response + String responseContent = null; + InputStream is = null; + HttpURLConnection httpUrlConnection = null; + HttpURLConnection.setFollowRedirects(false); + try { + URL url = new URL(urlString); + httpUrlConnection = (HttpURLConnection) url.openConnection(); - // give it 15 seconds to respond - httpUrlConnection.setReadTimeout(15*1000); - httpUrlConnection.connect(); + httpUrlConnection.setRequestMethod("GET"); - int responseCode = httpUrlConnection.getResponseCode(); + // give it 15 seconds to respond + httpUrlConnection.setReadTimeout(15 * 1000); + httpUrlConnection.connect(); - if(responseCode != 200) { - is = httpUrlConnection.getErrorStream(); - if(is != null) { - responseContent = StreamTools.readStreamtoString(is,"UTF-8"); - } else { - responseContent = ""; - } - JsonObject response = jsonParser.parse(responseContent).getAsJsonObject(); - throw new ApiException(gson.fromJson(response, ApiError.class)); - } + int responseCode = httpUrlConnection.getResponseCode(); - is = httpUrlConnection.getInputStream(); + if(responseCode != 200) { + is = httpUrlConnection.getErrorStream(); + if(is != null) { + responseContent = StreamTools.readStreamtoString(is, "UTF-8"); + } else { + responseContent = ""; + } + JsonObject response = jsonParser.parse(responseContent).getAsJsonObject(); + throw new ApiException(gson.fromJson(response, ApiError.class)); + } - responseContent = StreamTools.readStreamtoString(is,"UTF-8"); + is = httpUrlConnection.getInputStream(); - } catch(IOException e) { - throw e; - } finally { - if(is != null) { - is.close(); - } - if(httpUrlConnection != null) { - httpUrlConnection.disconnect(); - } - } - return responseContent; - } + responseContent = StreamTools.readStreamtoString(is, "UTF-8"); - private static String invokeImpl(String method, Map paramMap) throws IOException, ApiException { - QueryBuilder queryBuilder = new QueryBuilder(method); - queryBuilder.put(paramMap); - return invokeImpl(queryBuilder.toString()); - } + } catch(IOException e) { + throw e; + } finally { + if(is != null) { + is.close(); + } + if(httpUrlConnection != null) { + httpUrlConnection.disconnect(); + } + } + return responseContent; + } + + private static String invokeImpl(String method, Map paramMap) throws IOException, ApiException { + QueryBuilder queryBuilder = new QueryBuilder(method); + queryBuilder.put(paramMap); + return invokeImpl(queryBuilder.toString()); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/api/client/holders/ApiError.java b/src/main/java/eu/crushedpixel/replaymod/api/client/holders/ApiError.java index 5050172a..950dd412 100755 --- a/src/main/java/eu/crushedpixel/replaymod/api/client/holders/ApiError.java +++ b/src/main/java/eu/crushedpixel/replaymod/api/client/holders/ApiError.java @@ -2,26 +2,28 @@ package eu.crushedpixel.replaymod.api.client.holders; public class ApiError { - public ApiError(int id, String desc) { - this.id = id; - this.desc = desc; - } - - private int id; - private String desc; - - public int getId() { - return id; - } - public void setId(int id) { - this.id = id; - } - public String getDesc() { - return desc; - } - public void setDesc(String desc) { - this.desc = desc; - } - - + private int id; + private String desc; + public ApiError(int id, String desc) { + this.id = id; + this.desc = desc; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + } diff --git a/src/main/java/eu/crushedpixel/replaymod/api/client/holders/AuthKey.java b/src/main/java/eu/crushedpixel/replaymod/api/client/holders/AuthKey.java index a5b77b82..7146084b 100755 --- a/src/main/java/eu/crushedpixel/replaymod/api/client/holders/AuthKey.java +++ b/src/main/java/eu/crushedpixel/replaymod/api/client/holders/AuthKey.java @@ -1,14 +1,14 @@ package eu.crushedpixel.replaymod.api.client.holders; public class AuthKey { - - private String auth; - - public AuthKey(String authkey) { - this.auth = authkey; - } - - public String getAuthkey() { - return auth; - } + + private String auth; + + public AuthKey(String authkey) { + this.auth = authkey; + } + + public String getAuthkey() { + return auth; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/api/client/holders/Category.java b/src/main/java/eu/crushedpixel/replaymod/api/client/holders/Category.java index 4aa82c01..2ec15e6d 100755 --- a/src/main/java/eu/crushedpixel/replaymod/api/client/holders/Category.java +++ b/src/main/java/eu/crushedpixel/replaymod/api/client/holders/Category.java @@ -2,38 +2,38 @@ package eu.crushedpixel.replaymod.api.client.holders; public enum Category { - SURVIVAL(0), MINIGAME(1), BUILD(2); - - private int id; - - Category(int id) { - this.id = id; - } - - public int getId() { - return this.id; - } - - public Category fromId(int id) { - for(Category c : values()) { - if(c.id == id) return c; - } - return null; - } - - public String toNiceString() { - return (""+this).charAt(0)+(""+this).substring(1).toLowerCase(); - } - - public Category next() { - for(int i=0; i requests = new ConcurrentLinkedQueue(); + private String prefix = "§8[§6Replay Mod§8]§r "; + private EntityPlayerSP player = null; + public Thread t = new Thread(new Runnable() { + + @Override + public void run() { + while(alive) { + while(active) { + try { + while(player == null) { + if(!alive) { + break; + } + try { + Thread.sleep(100); + player = Minecraft.getMinecraft().thePlayer; + } catch(Exception e) { + } + } + + player.addChatComponentMessage(requests.poll()); + Thread.sleep(100); + } catch(Exception e) { + } + } + + try { + Thread.sleep(1000); + } catch(InterruptedException e) { + e.printStackTrace(); + } + } + } + }); + + public ChatMessageHandler() { + t.start(); + } + + public void addChatMessage(String message, ChatMessageType type) { + if(ReplayMod.replaySettings.isShowNotifications()) { + message = prefix + toColor(message, type); + ChatComponentText cct = new ChatComponentText(message); + requests.add(cct); + } + } + + private String toColor(String message, ChatMessageType type) { + if(type == ChatMessageType.INFORMATION) { + return "§2" + message; + } else if(type == ChatMessageType.WARNING) { + return "§c" + message; + } + + return message; + } + + public void stop() { + active = false; + } + + public void initialize() { + active = true; + requests.clear(); + if(!ReplayMod.replaySettings.isShowNotifications()) { + System.out.println("Chat messages are disabled"); + } + } + + public enum ChatMessageType { + INFORMATION, WARNING; + } +} diff --git a/src/main/java/eu/crushedpixel/replaymod/chat/ChatMessageRequests.java b/src/main/java/eu/crushedpixel/replaymod/chat/ChatMessageRequests.java deleted file mode 100755 index 7d98dfad..00000000 --- a/src/main/java/eu/crushedpixel/replaymod/chat/ChatMessageRequests.java +++ /dev/null @@ -1,95 +0,0 @@ -package eu.crushedpixel.replaymod.chat; - -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.EntityPlayerSP; -import net.minecraft.server.MinecraftServer; -import net.minecraft.util.ChatComponentText; -import net.minecraft.util.IChatComponent; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; -import eu.crushedpixel.replaymod.ReplayMod; - -@SideOnly(Side.CLIENT) -public class ChatMessageRequests { - - public enum ChatMessageType { - INFORMATION, WARNING; - } - - private static boolean active = true; - private static boolean alive = true; - - private static Queue requests = new ConcurrentLinkedQueue(); - private static String prefix = "§8[§6Replay Mod§8]§r "; - - private static EntityPlayerSP player = null; - - public static Thread t = new Thread(new Runnable() { - - @Override - public void run() { - while(alive) { - while(active) { - try { - while(player == null) { - if(!alive) { - break; - } - try { - Thread.sleep(100); - player = Minecraft.getMinecraft().thePlayer; - } catch(Exception e) {} - } - - player.addChatComponentMessage(requests.poll()); - Thread.sleep(100); - } catch(Exception e) {} - } - - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - }); - - static { - t.start(); - } - - public static void addChatMessage(String message, ChatMessageType type) { - if(ReplayMod.replaySettings.isShowNotifications()) { - message = prefix+toColor(message, type); - ChatComponentText cct = new ChatComponentText(message); - requests.add(cct); - } - } - - private static String toColor(String message, ChatMessageType type) { - if(type == ChatMessageType.INFORMATION) { - return "§2"+message; - } else if(type == ChatMessageType.WARNING) { - return "§c"+message; - } - - return message; - } - - public static void stop() { - active = false; - } - - public static void initialize() { - active = true; - requests.clear(); - if(ReplayMod.replaySettings.isShowNotifications()) { - } else { - System.out.println("Chat messages are disabled"); - } - } -} diff --git a/src/main/java/eu/crushedpixel/replaymod/coremod/ClassTransformer.java b/src/main/java/eu/crushedpixel/replaymod/coremod/ClassTransformer.java index 68f8c491..f9aea6c0 100755 --- a/src/main/java/eu/crushedpixel/replaymod/coremod/ClassTransformer.java +++ b/src/main/java/eu/crushedpixel/replaymod/coremod/ClassTransformer.java @@ -1,11 +1,7 @@ package eu.crushedpixel.replaymod.coremod; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - +import akka.japi.Pair; import net.minecraft.launchwrapper.IClassTransformer; - import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; @@ -14,75 +10,77 @@ import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; -import akka.japi.Pair; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; public class ClassTransformer implements IClassTransformer { - @Override - public byte[] transform(String name, String transformedName, - byte[] basicClass) { - if(name.equals("cqh")) { - return patchRenderEffectMethod(name, basicClass, true); - } - - if(name.equals("net.minecraft.client.renderer.entity.RenderItem")) { - return patchRenderEffectMethod(name, basicClass, false); - } - - return basicClass; - } - - public byte[] patchRenderEffectMethod(String name, byte[] bytes, boolean obfuscated) { - System.out.println("REPLAY MOD CORE PATCHER: Inside RenderItem class"); - - String methodName = obfuscated ? "a" : "renderEffect"; - String classDescriptor = obfuscated ? "(Lcxe;)V" : "(Lnet/minecraft/client/resources/model/IBakedModel;)V"; - - String minecraftClass = obfuscated ? "bsu" : "net/minecraft/client/Minecraft"; - String getSystemTime = obfuscated ? "I" : "getSystemTime"; - String sysTimeDesc = "()J"; - - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader(bytes); - classReader.accept(classNode, 0); - - List> toInsert = new ArrayList>(); - - Iterator iterator = classNode.methods.iterator(); - while(iterator.hasNext()) { - MethodNode m = iterator.next(); - if(m.name.equals(methodName) && m.desc.equals(classDescriptor)) { - System.out.println("REPLAY MOD CORE PATCHER: Inside renderEffect method"); - - Iterator nodeIterator = m.instructions.iterator(); - while(nodeIterator.hasNext()) { - AbstractInsnNode node = nodeIterator.next(); - if(node instanceof MethodInsnNode) { - MethodInsnNode min = (MethodInsnNode)node; - if(min.getOpcode() == Opcodes.INVOKESTATIC &&min.name.equals(getSystemTime) && - min.owner.equals(minecraftClass) && min.desc.equals(sysTimeDesc)) { - MethodInsnNode n = new MethodInsnNode(Opcodes.INVOKESTATIC, - "eu/crushedpixel/replaymod/timer/EnchantmentTimer", "getEnchantmentTime", - min.desc, min.itf); - toInsert.add(new Pair(min, n)); - } - } - } - - for(Pair pair : toInsert) { - m.instructions.insertBefore(pair.first(), pair.second()); - m.instructions.remove(pair.first()); - } - - } - } - - ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); - classNode.accept(writer); - return writer.toByteArray(); - } + @Override + public byte[] transform(String name, String transformedName, + byte[] basicClass) { + if(name.equals("cqh")) { + return patchRenderEffectMethod(name, basicClass, true); + } - // net.minecraft.client.renderer.entity.RenderItem -> cqh - // private void renderEffect(IBakedModel model) -> private void a(cxe paramcxe) - // float f = (float)(Minecraft.getSystemTime() % 3000L) / 3000.0F / 8.0F; -> float f1 = (float)(bsu.I() % 3000L) / 3000.0F / 8.0F; + if(name.equals("net.minecraft.client.renderer.entity.RenderItem")) { + return patchRenderEffectMethod(name, basicClass, false); + } + + return basicClass; + } + + public byte[] patchRenderEffectMethod(String name, byte[] bytes, boolean obfuscated) { + System.out.println("REPLAY MOD CORE PATCHER: Inside RenderItem class"); + + String methodName = obfuscated ? "a" : "renderEffect"; + String classDescriptor = obfuscated ? "(Lcxe;)V" : "(Lnet/minecraft/client/resources/model/IBakedModel;)V"; + + String minecraftClass = obfuscated ? "bsu" : "net/minecraft/client/Minecraft"; + String getSystemTime = obfuscated ? "I" : "getSystemTime"; + String sysTimeDesc = "()J"; + + ClassNode classNode = new ClassNode(); + ClassReader classReader = new ClassReader(bytes); + classReader.accept(classNode, 0); + + List> toInsert = new ArrayList>(); + + Iterator iterator = classNode.methods.iterator(); + while(iterator.hasNext()) { + MethodNode m = iterator.next(); + if(m.name.equals(methodName) && m.desc.equals(classDescriptor)) { + System.out.println("REPLAY MOD CORE PATCHER: Inside renderEffect method"); + + Iterator nodeIterator = m.instructions.iterator(); + while(nodeIterator.hasNext()) { + AbstractInsnNode node = nodeIterator.next(); + if(node instanceof MethodInsnNode) { + MethodInsnNode min = (MethodInsnNode) node; + if(min.getOpcode() == Opcodes.INVOKESTATIC && min.name.equals(getSystemTime) && + min.owner.equals(minecraftClass) && min.desc.equals(sysTimeDesc)) { + MethodInsnNode n = new MethodInsnNode(Opcodes.INVOKESTATIC, + "eu/crushedpixel/replaymod/timer/EnchantmentTimer", "getEnchantmentTime", + min.desc, min.itf); + toInsert.add(new Pair(min, n)); + } + } + } + + for(Pair pair : toInsert) { + m.instructions.insertBefore(pair.first(), pair.second()); + m.instructions.remove(pair.first()); + } + + } + } + + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); + classNode.accept(writer); + return writer.toByteArray(); + } + + // net.minecraft.client.renderer.entity.RenderItem -> cqh + // private void renderEffect(IBakedModel model) -> private void a(cxe paramcxe) + // float f = (float)(Minecraft.getSystemTime() % 3000L) / 3000.0F / 8.0F; -> float f1 = (float)(bsu.I() % 3000L) / 3000.0F / 8.0F; } diff --git a/src/main/java/eu/crushedpixel/replaymod/coremod/LoadingPlugin.java b/src/main/java/eu/crushedpixel/replaymod/coremod/LoadingPlugin.java index 551b81f4..57645876 100755 --- a/src/main/java/eu/crushedpixel/replaymod/coremod/LoadingPlugin.java +++ b/src/main/java/eu/crushedpixel/replaymod/coremod/LoadingPlugin.java @@ -1,32 +1,33 @@ package eu.crushedpixel.replaymod.coremod; -import java.util.Map; - import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin; +import java.util.Map; + public class LoadingPlugin implements IFMLLoadingPlugin { - @Override - public String[] getASMTransformerClass() { - return new String[]{ClassTransformer.class.getName()}; - } + @Override + public String[] getASMTransformerClass() { + return new String[]{ClassTransformer.class.getName()}; + } - @Override - public String getModContainerClass() { - return null; - } + @Override + public String getModContainerClass() { + return null; + } - @Override - public String getSetupClass() { - return null; - } + @Override + public String getSetupClass() { + return null; + } - @Override - public void injectData(Map data) {} + @Override + public void injectData(Map data) { + } - @Override - public String getAccessTransformerClass() { - return null; - } + @Override + public String getAccessTransformerClass() { + return null; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/entities/CameraEntity.java b/src/main/java/eu/crushedpixel/replaymod/entities/CameraEntity.java index e2136156..cf31dbd0 100755 --- a/src/main/java/eu/crushedpixel/replaymod/entities/CameraEntity.java +++ b/src/main/java/eu/crushedpixel/replaymod/entities/CameraEntity.java @@ -1,195 +1,190 @@ package eu.crushedpixel.replaymod.entities; -import java.lang.reflect.Field; - -import net.minecraft.client.Minecraft; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.network.play.server.S03PacketTimeUpdate; -import net.minecraft.util.MathHelper; -import net.minecraft.util.MovingObjectPosition; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; - -import org.lwjgl.Sys; - import eu.crushedpixel.replaymod.holders.Position; import eu.crushedpixel.replaymod.replay.LesserDataWatcher; import eu.crushedpixel.replaymod.replay.ReplayHandler; -import eu.crushedpixel.replaymod.replay.TimeHandler; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.MathHelper; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import org.lwjgl.Sys; + +import java.lang.reflect.Field; public class CameraEntity extends EntityPlayer { - private Vec3 direction; - private double motion; + private static final double MAX_SPEED = 20; + private Vec3 direction; + private double motion; + private Field drawBlockOutline; + private double decay = 4; - private Field drawBlockOutline; + private long lastCall = 0; - private static final double MAX_SPEED = 20; + private boolean speedup = false; - private double decay = 4; + public CameraEntity(World worldIn) { + //super(worldIn); + super(worldIn, Minecraft.getMinecraft().getSession().getProfile()); + } - private long lastCall = 0; + //frac = time since last tick + public void updateMovement() { + Minecraft mc = Minecraft.getMinecraft(); + if(ReplayHandler.getCameraEntity() != null && mc.thePlayer != null + && mc.getRenderViewEntity() != null) { + //Aligns the particle rotation + mc.thePlayer.rotationPitch = mc.getRenderViewEntity().rotationPitch; + mc.thePlayer.rotationYaw = mc.getRenderViewEntity().rotationYaw; - private boolean speedup = false; + //removes water/suffocation/shadow overlays in screen + mc.thePlayer.posX = 0; + mc.thePlayer.posY = 500; + mc.thePlayer.posZ = 0; + } - //frac = time since last tick - public void updateMovement() { - Minecraft mc = Minecraft.getMinecraft(); - if(ReplayHandler.getCameraEntity() != null && mc.thePlayer != null - && mc.getRenderViewEntity() != null) { - //Aligns the particle rotation - mc.thePlayer.rotationPitch = mc.getRenderViewEntity().rotationPitch; - mc.thePlayer.rotationYaw = mc.getRenderViewEntity().rotationYaw; + if(direction == null || motion < 0.1) { + lastCall = Sys.getTime(); + return; + } - //removes water/suffocation/shadow overlays in screen - mc.thePlayer.posX = 0; - mc.thePlayer.posY = 500; - mc.thePlayer.posZ = 0; - } + long frac = Sys.getTime() - lastCall; - if(direction == null || motion < 0.1) { - lastCall = Sys.getTime(); - return; - } + if(frac == 0) return; - long frac = Sys.getTime() - lastCall; + Vec3 movement = direction.normalize(); + double factor = motion * (frac / 1000D); - if(frac == 0) return; + moveRelative(movement.xCoord * factor, movement.yCoord * factor, movement.zCoord * factor); - Vec3 movement = direction.normalize(); - double factor = motion*(frac/1000D); + double decFac = Math.max(0, 1 - (decay * (frac / 1000D))); - moveRelative(movement.xCoord*factor, movement.yCoord*factor, movement.zCoord*factor); + if(!speedup) { + motion *= decFac; + } else { + speedup = false; + } - double decFac = Math.max(0, 1-(decay*(frac/1000D))); + lastCall = Sys.getTime(); + } - if(!speedup) { - motion *= decFac; - } else { - speedup = false; - } + public void setDirection(float pitch, float yaw) { + this.setRotation(yaw, pitch); + } - lastCall = Sys.getTime(); - } + public void speedUp() { + this.motion = Math.min(MAX_SPEED, motion + 0.1); + speedup = true; + } - public void setDirection(float pitch, float yaw) { - this.setRotation(yaw, pitch); - } + public void setMovement(MoveDirection dir) { + Vec3 oldDir = direction; - public void speedUp() { - this.motion = Math.min(MAX_SPEED, motion+0.1); - speedup = true; - } + switch(dir) { + case BACKWARD: + direction = this.getVectorForRotation(-rotationPitch, rotationYaw - 180); + break; + case DOWN: + direction = this.getVectorForRotation(90, 0); + break; + case FORWARD: + direction = this.getVectorForRotation(rotationPitch, rotationYaw); + break; + case LEFT: + direction = this.getVectorForRotation(0, rotationYaw - 90); + break; + case RIGHT: + direction = this.getVectorForRotation(0, rotationYaw + 90); + break; + case UP: + direction = this.getVectorForRotation(-90, 0); + break; + } - public void setMovement(MoveDirection dir) { - Vec3 oldDir = direction; + if(oldDir != null) + direction = direction.normalize().add(new Vec3(oldDir.xCoord * (motion / 4f), oldDir.yCoord * (motion / 4f), oldDir.zCoord * (motion / 4f)).normalize()); + } - switch(dir) { - case BACKWARD: - direction = this.getVectorForRotation(-rotationPitch, rotationYaw-180); - break; - case DOWN: - direction = this.getVectorForRotation(90, 0); - break; - case FORWARD: - direction = this.getVectorForRotation(rotationPitch, rotationYaw); - break; - case LEFT: - direction = this.getVectorForRotation(0, rotationYaw-90); - break; - case RIGHT: - direction = this.getVectorForRotation(0, rotationYaw+90); - break; - case UP: - direction = this.getVectorForRotation(-90, 0); - break; - } + public void moveAbsolute(double x, double y, double z) { + if(ReplayHandler.isInPath()) return; + this.lastTickPosX = this.prevPosX = this.posX = x; + this.lastTickPosY = this.prevPosY = this.posY = y; + this.lastTickPosZ = this.prevPosZ = this.posZ = z; + } - if(oldDir != null) direction = direction.normalize().add(new Vec3(oldDir.xCoord*(motion/4f), oldDir.yCoord*(motion/4f), oldDir.zCoord*(motion/4f)).normalize()); - } + public void moveRelative(double x, double y, double z) { + if(ReplayHandler.isInPath()) return; + this.lastTickPosX = this.prevPosX = this.posX = this.posX + x; + this.lastTickPosY = this.prevPosY = this.posY = this.posY + y; + this.lastTickPosZ = this.prevPosZ = this.posZ = this.posZ + z; + } - public void moveAbsolute(double x, double y, double z) { - if(ReplayHandler.isInPath()) return; - this.lastTickPosX = this.prevPosX = this.posX = x; - this.lastTickPosY = this.prevPosY = this.posY = y; - this.lastTickPosZ = this.prevPosZ = this.posZ = z; - } + public void movePath(Position pos) { + this.prevRotationPitch = this.rotationPitch = pos.getPitch(); + this.prevRotationYaw = this.rotationYaw = pos.getYaw(); + this.lastTickPosX = this.prevPosX = this.posX = pos.getX(); + this.lastTickPosY = this.prevPosY = this.posY = pos.getY(); + this.lastTickPosZ = this.prevPosZ = this.posZ = pos.getZ(); + } - public void moveRelative(double x, double y, double z) { - if(ReplayHandler.isInPath()) return; - this.lastTickPosX = this.prevPosX = this.posX = this.posX+x; - this.lastTickPosY = this.prevPosY = this.posY = this.posY+y; - this.lastTickPosZ = this.prevPosZ = this.posZ = this.posZ+z; - } + @Override + protected void entityInit() { + this.dataWatcher = new LesserDataWatcher(this); + } - public void movePath(Position pos) { - this.prevRotationPitch = this.rotationPitch = pos.getPitch(); - this.prevRotationYaw = this.rotationYaw = pos.getYaw(); - this.lastTickPosX = this.prevPosX = this.posX = pos.getX(); - this.lastTickPosY = this.prevPosY = this.posY = pos.getY(); - this.lastTickPosZ = this.prevPosZ = this.posZ = pos.getZ(); - } - - @Override - protected void entityInit() { - this.dataWatcher = new LesserDataWatcher(this); - } + @Override + public void setAngles(float yaw, float pitch) { + this.rotationYaw = (float) ((double) this.rotationYaw + (double) yaw * 0.15D); + this.rotationPitch = (float) ((double) this.rotationPitch - (double) pitch * 0.15D); + this.rotationPitch = MathHelper.clamp_float(this.rotationPitch, -90.0F, 90.0F); + this.prevRotationPitch = this.rotationPitch; + this.prevRotationYaw = this.rotationYaw; + } - public CameraEntity(World worldIn) { - //super(worldIn); - super(worldIn, Minecraft.getMinecraft().getSession().getProfile()); - } + @Override + public MovingObjectPosition rayTrace(double p_174822_1_, float p_174822_3_) { + return null; + } - @Override - public void setAngles(float yaw, float pitch) - { - this.rotationYaw = (float)((double)this.rotationYaw + (double)yaw * 0.15D); - this.rotationPitch = (float)((double)this.rotationPitch - (double)pitch * 0.15D); - this.rotationPitch = MathHelper.clamp_float(this.rotationPitch, -90.0F, 90.0F); - this.prevRotationPitch = this.rotationPitch; - this.prevRotationYaw = this.rotationYaw; - } + @Override + public boolean canBePushed() { + return false; + } + @Override + protected void createRunningParticles() { + } - @Override - public MovingObjectPosition rayTrace(double p_174822_1_, float p_174822_3_) { - return null; - } + @Override + public boolean canBeCollidedWith() { + return false; + } - @Override - public boolean canBePushed() { - return false; - } + @Override + public boolean canRenderOnFire() { + return false; + } - @Override - protected void createRunningParticles() {} + @Override + public void setCurrentItemOrArmor(int slotIn, ItemStack stack) { + } - @Override - public boolean canBeCollidedWith() { - return false; - } - @Override - public boolean canRenderOnFire() { - return false; - } + @Override + public ItemStack[] getInventory() { + return null; + } - public enum MoveDirection { - UP, DOWN, LEFT, RIGHT, FORWARD, BACKWARD; - } + @Override + public boolean isSpectator() { + return true; + } - @Override - public void setCurrentItemOrArmor(int slotIn, ItemStack stack) {} - - @Override - public ItemStack[] getInventory() { - return null; - } - - @Override - public boolean isSpectator() { - return true; - } + public enum MoveDirection { + UP, DOWN, LEFT, RIGHT, FORWARD, BACKWARD; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/events/GuiEventHandler.java b/src/main/java/eu/crushedpixel/replaymod/events/GuiEventHandler.java index 594ffa0e..7d1021fd 100755 --- a/src/main/java/eu/crushedpixel/replaymod/events/GuiEventHandler.java +++ b/src/main/java/eu/crushedpixel/replaymod/events/GuiEventHandler.java @@ -1,26 +1,5 @@ package eu.crushedpixel.replaymod.events; -import java.awt.Color; -import java.awt.Point; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiChat; -import net.minecraft.client.gui.GuiDisconnected; -import net.minecraft.client.gui.GuiIngameMenu; -import net.minecraft.client.gui.GuiMainMenu; -import net.minecraft.client.gui.GuiOptions; -import net.minecraft.client.gui.GuiVideoSettings; -import net.minecraft.client.gui.inventory.GuiInventory; -import net.minecraft.client.multiplayer.WorldClient; -import net.minecraft.client.settings.GameSettings.Options; -import net.minecraftforge.client.event.GuiOpenEvent; -import net.minecraftforge.client.event.GuiScreenEvent.ActionPerformedEvent; -import net.minecraftforge.client.event.GuiScreenEvent.DrawScreenEvent; -import net.minecraftforge.client.event.GuiScreenEvent.InitGuiEvent; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import eu.crushedpixel.replaymod.ReplayMod; import eu.crushedpixel.replaymod.gui.GuiCancelRender; import eu.crushedpixel.replaymod.gui.GuiConstants; @@ -42,175 +21,183 @@ import eu.crushedpixel.replaymod.utils.MouseUtils; import eu.crushedpixel.replaymod.utils.ReplayFileIO; import eu.crushedpixel.replaymod.utils.ResourceHelper; import eu.crushedpixel.replaymod.video.VideoWriter; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.*; +import net.minecraft.client.gui.inventory.GuiInventory; +import net.minecraft.client.multiplayer.WorldClient; +import net.minecraftforge.client.event.GuiOpenEvent; +import net.minecraftforge.client.event.GuiScreenEvent.ActionPerformedEvent; +import net.minecraftforge.client.event.GuiScreenEvent.DrawScreenEvent; +import net.minecraftforge.client.event.GuiScreenEvent.InitGuiEvent; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; + +import java.awt.*; +import java.util.ArrayList; +import java.util.List; public class GuiEventHandler { - private static Minecraft mc = Minecraft.getMinecraft(); + private static final Color DARK_RED = Color.decode("#DF0101"); + private static final Color DARK_GREEN = Color.decode("#01DF01"); + private final Minecraft mc = Minecraft.getMinecraft(); + private final List allowedGUIs = new ArrayList() { + { + add(GuiReplaySettings.class); + add(GuiReplaySaving.class); + add(GuiIngameMenu.class); + add(GuiOptions.class); + add(GuiVideoSettings.class); + } + }; + private int replayCount = 0; + private GuiButton editorButton; - private static int replayCount = 0; - - private static List allowedGUIs = new ArrayList() { - { - add(GuiReplaySettings.class); - add(GuiReplaySaving.class); - add(GuiIngameMenu.class); - add(GuiOptions.class); - add(GuiVideoSettings.class); - } - }; + @SubscribeEvent + public void onGui(GuiOpenEvent event) { + if(VideoWriter.isRecording() && !(event.gui instanceof GuiCancelRender)) { + event.gui = null; + return; + } - @SubscribeEvent - public void onGui(GuiOpenEvent event) { - if(VideoWriter.isRecording() && !(event.gui instanceof GuiCancelRender)) { - event.gui = null; - return; - } + if(!(event.gui instanceof GuiReplayViewer || event.gui instanceof GuiUploadFile)) + ResourceHelper.freeAllResources(); - if(!(event.gui instanceof GuiReplayViewer || event.gui instanceof GuiUploadFile)) ResourceHelper.freeAllResources(); + if(event.gui instanceof GuiMainMenu) { + if(ReplayMod.firstMainMenu) { + ReplayMod.firstMainMenu = false; + event.gui = new GuiLoginPrompt(event.gui, event.gui); + return; + } else { + try { + MCTimerHandler.setTimerSpeed(1); + } catch(Exception e) { + e.printStackTrace(); + } + } + } - if(event.gui instanceof GuiMainMenu) { - if(ReplayMod.firstMainMenu) { - ReplayMod.firstMainMenu = false; - event.gui = new GuiLoginPrompt(event.gui, event.gui); - return; - } else { - try { - MCTimerHandler.setTimerSpeed(1); - } catch (Exception e) { - e.printStackTrace(); - } - } - } + if(!AuthenticationHandler.isAuthenticated()) return; + if(event.gui != null && GuiReplaySaving.replaySaving && !allowedGUIs.contains(event.gui.getClass())) { + event.gui = new GuiReplaySaving(event.gui); + return; + } + if(event.gui instanceof GuiChat || event.gui instanceof GuiInventory) { + if(ReplayHandler.isInReplay()) { + event.setCanceled(true); + } + } else if(event.gui instanceof GuiDisconnected) { + if(!ReplayHandler.isInReplay() && System.currentTimeMillis() - ReplayHandler.lastExit < 5000) { + event.setCanceled(true); + } + } + } - if(!AuthenticationHandler.isAuthenticated()) return; - if(event.gui != null && GuiReplaySaving.replaySaving && !allowedGUIs.contains(event.gui.getClass())) { - event.gui = new GuiReplaySaving(event.gui); - return; - } - if(event.gui instanceof GuiChat || event.gui instanceof GuiInventory) { - if(ReplayHandler.isInReplay()) { - event.setCanceled(true); - } - } + @SubscribeEvent + public void onDraw(DrawScreenEvent e) { + if(e.gui instanceof GuiMainMenu) { + e.gui.drawString(mc.fontRendererObj, "Replay Mod:", 5, 5, Color.WHITE.getRGB()); + if(AuthenticationHandler.isAuthenticated()) { + e.gui.drawString(mc.fontRendererObj, "LOGGED IN", 5, 15, DARK_GREEN.getRGB()); + } else { + e.gui.drawString(mc.fontRendererObj, "LOGGED OUT", 5, 15, DARK_RED.getRGB()); + } - else if(event.gui instanceof GuiDisconnected) { - if(!ReplayHandler.isInReplay() && System.currentTimeMillis() - ReplayHandler.lastExit < 5000) { - event.setCanceled(true); - } - } - } + if(replayCount == 0) { + if(editorButton.isMouseOver()) { + Point mouse = MouseUtils.getMousePos(); + e.gui.drawCenteredString(mc.fontRendererObj, "At least one Replay required", (int) mouse.getX(), (int) mouse.getY() + 4, Color.RED.getRGB()); + } + } else if(!VersionValidator.isValid) { + if(editorButton.isMouseOver()) { + Point mouse = MouseUtils.getMousePos(); + e.gui.drawCenteredString(mc.fontRendererObj, "Java 1.7 or newer required", (int) mouse.getX(), (int) mouse.getY() + 4, Color.RED.getRGB()); + } + } + } + } - private static final Color DARK_RED = Color.decode("#DF0101"); - private static final Color DARK_GREEN = Color.decode("#01DF01"); + @SubscribeEvent + public void onInit(InitGuiEvent event) { + if(event.gui instanceof GuiIngameMenu && ReplayHandler.isInReplay()) { + for(GuiButton b : new ArrayList(event.buttonList)) { + if(b.id == 1) { + b.displayString = "Exit Replay"; + b.yPosition -= 24 * 2; + b.id = GuiConstants.EXIT_REPLAY_BUTTON; + } else if(b.id >= 5 && b.id <= 7) { + event.buttonList.remove(b); + } else if(b.id != 4) { + b.yPosition -= 24 * 2; + } + } + } else if(event.gui instanceof GuiMainMenu) { + int i1 = event.gui.height / 4 + 24 + 10; - @SubscribeEvent - public void onDraw(DrawScreenEvent e) { - if(e.gui instanceof GuiMainMenu) { - e.gui.drawString(mc.fontRendererObj, "Replay Mod:", 5, 5, Color.WHITE.getRGB()); - if(AuthenticationHandler.isAuthenticated()) { - e.gui.drawString(mc.fontRendererObj, "LOGGED IN", 5, 15, DARK_GREEN.getRGB()); - } else { - e.gui.drawString(mc.fontRendererObj, "LOGGED OUT", 5, 15, DARK_RED.getRGB()); - } - - if(replayCount == 0) { - if(editorButton.isMouseOver()) { - Point mouse = MouseUtils.getMousePos(); - e.gui.drawCenteredString(mc.fontRendererObj, "At least one Replay required", (int)mouse.getX(), (int)mouse.getY()+4, Color.RED.getRGB()); - } - } else if(!VersionValidator.isValid) { - if(editorButton.isMouseOver()) { - Point mouse = MouseUtils.getMousePos(); - e.gui.drawCenteredString(mc.fontRendererObj, "Java 1.7 or newer required", (int)mouse.getX(), (int)mouse.getY()+4, Color.RED.getRGB()); - } - } - } - } + for(GuiButton b : (List) event.buttonList) { + if(b.id != 0 && b.id != 4 && b.id != 5) { + b.yPosition = b.yPosition - 2 * 24 + 10; + } + } - private GuiButton editorButton; - - @SubscribeEvent - public void onInit(InitGuiEvent event) { - if(event.gui instanceof GuiIngameMenu && ReplayHandler.isInReplay()) { - for(GuiButton b : new ArrayList(event.buttonList)) { - if(b.id == 1) { - b.displayString = "Exit Replay"; - b.yPosition -= 24*2; - b.id = GuiConstants.EXIT_REPLAY_BUTTON; - } else if(b.id >= 5 && b.id <= 7) { - event.buttonList.remove(b); - } else if(b.id != 4) { - b.yPosition -= 24*2; - } - } - } else if(event.gui instanceof GuiMainMenu) { - int i1 = event.gui.height / 4 + 24 + 10; + GuiButton rm = new GuiButton(GuiConstants.REPLAY_MANAGER_BUTTON_ID, event.gui.width / 2 - 100, i1 + 2 * 24, "Replay Viewer"); + rm.width = rm.width / 2 - 2; + //rm.enabled = AuthenticationHandler.isAuthenticated(); + event.buttonList.add(rm); - for(GuiButton b : (List)event.buttonList) { - if(b.id != 0 && b.id != 4 && b.id != 5) { - b.yPosition = b.yPosition - 2*24 + 10; - } - } + replayCount = ReplayFileIO.getAllReplayFiles().size(); - GuiButton rm = new GuiButton(GuiConstants.REPLAY_MANAGER_BUTTON_ID, event.gui.width / 2 - 100, i1 + 2*24, "Replay Viewer"); - rm.width = rm.width/2 - 2; - //rm.enabled = AuthenticationHandler.isAuthenticated(); - event.buttonList.add(rm); + GuiButton re = new GuiButton(GuiConstants.REPLAY_EDITOR_BUTTON_ID, event.gui.width / 2 + 2, i1 + 2 * 24, "Replay Editor"); + re.width = re.width / 2 - 2; + re.enabled = VersionValidator.isValid && replayCount > 0; + event.buttonList.add(re); - replayCount = ReplayFileIO.getAllReplayFiles().size(); - - GuiButton re = new GuiButton(GuiConstants.REPLAY_EDITOR_BUTTON_ID, event.gui.width / 2 + 2, i1 + 2*24, "Replay Editor"); - re.width = re.width/2 - 2; - re.enabled = VersionValidator.isValid && replayCount > 0; - event.buttonList.add(re); - - editorButton = re; - - GuiButton rc = new GuiButton(GuiConstants.REPLAY_CENTER_BUTTON_ID, event.gui.width / 2 - 100, i1 + 3*24, "Replay Center"); - rc.enabled = true; - event.buttonList.add(rc); - - } else if(event.gui instanceof GuiOptions) { - event.buttonList.add(new GuiButton(GuiConstants.REPLAY_OPTIONS_BUTTON_ID, - event.gui.width / 2 - 155, event.gui.height / 6 + 48 - 6 - 24, 310, 20, "Replay Mod Settings...")); - } - } + editorButton = re; - @SubscribeEvent - public void onButton(ActionPerformedEvent event) { - if(!event.button.enabled) return; - if(event.gui instanceof GuiMainMenu) { - if(event.button.id == GuiConstants.REPLAY_MANAGER_BUTTON_ID) { - mc.displayGuiScreen(new GuiReplayViewer()); - } else if(event.button.id == GuiConstants.REPLAY_CENTER_BUTTON_ID) { - if(AuthenticationHandler.isAuthenticated()) { - mc.displayGuiScreen(new GuiReplayCenter()); - } else { - mc.displayGuiScreen(new GuiLoginPrompt(event.gui, new GuiReplayCenter())); - } - } else if(event.button.id == GuiConstants.REPLAY_EDITOR_BUTTON_ID) { - mc.displayGuiScreen(new GuiReplayStudio()); - } - } else if(event.gui instanceof GuiOptions && event.button.id == GuiConstants.REPLAY_OPTIONS_BUTTON_ID) { - mc.displayGuiScreen(new GuiReplaySettings(event.gui)); - } + GuiButton rc = new GuiButton(GuiConstants.REPLAY_CENTER_BUTTON_ID, event.gui.width / 2 - 100, i1 + 3 * 24, "Replay Center"); + rc.enabled = true; + event.buttonList.add(rc); - if(ReplayHandler.isInReplay() && event.gui instanceof GuiIngameMenu && event.button.id == GuiConstants.EXIT_REPLAY_BUTTON) { - if(ReplayHandler.isInPath()) ReplayProcess.stopReplayProcess(false); - ReplayHandler.endReplay(); - - event.button.enabled = false; - - LightingHandler.setLighting(false); + } else if(event.gui instanceof GuiOptions) { + event.buttonList.add(new GuiButton(GuiConstants.REPLAY_OPTIONS_BUTTON_ID, + event.gui.width / 2 - 155, event.gui.height / 6 + 48 - 6 - 24, 310, 20, "Replay Mod Settings...")); + } + } - ReplayHandler.lastExit = System.currentTimeMillis(); + @SubscribeEvent + public void onButton(ActionPerformedEvent event) { + if(!event.button.enabled) return; + if(event.gui instanceof GuiMainMenu) { + if(event.button.id == GuiConstants.REPLAY_MANAGER_BUTTON_ID) { + mc.displayGuiScreen(new GuiReplayViewer()); + } else if(event.button.id == GuiConstants.REPLAY_CENTER_BUTTON_ID) { + if(AuthenticationHandler.isAuthenticated()) { + mc.displayGuiScreen(new GuiReplayCenter()); + } else { + mc.displayGuiScreen(new GuiLoginPrompt(event.gui, new GuiReplayCenter())); + } + } else if(event.button.id == GuiConstants.REPLAY_EDITOR_BUTTON_ID) { + mc.displayGuiScreen(new GuiReplayStudio()); + } + } else if(event.gui instanceof GuiOptions && event.button.id == GuiConstants.REPLAY_OPTIONS_BUTTON_ID) { + mc.displayGuiScreen(new GuiReplaySettings(event.gui)); + } - mc.theWorld.sendQuittingDisconnectingPacket(); - mc.loadWorld((WorldClient)null); - mc.displayGuiScreen(new GuiMainMenu()); - - ReplayGuiRegistry.show(); - } - } + if(ReplayHandler.isInReplay() && event.gui instanceof GuiIngameMenu && event.button.id == GuiConstants.EXIT_REPLAY_BUTTON) { + if(ReplayHandler.isInPath()) ReplayProcess.stopReplayProcess(false); + ReplayHandler.endReplay(); + + event.button.enabled = false; + + LightingHandler.setLighting(false); + + ReplayHandler.lastExit = System.currentTimeMillis(); + + mc.theWorld.sendQuittingDisconnectingPacket(); + mc.loadWorld((WorldClient) null); + mc.displayGuiScreen(new GuiMainMenu()); + + ReplayGuiRegistry.show(); + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/events/GuiReplayOverlay.java b/src/main/java/eu/crushedpixel/replaymod/events/GuiReplayOverlay.java index bac1a2b3..ae3dad7a 100755 --- a/src/main/java/eu/crushedpixel/replaymod/events/GuiReplayOverlay.java +++ b/src/main/java/eu/crushedpixel/replaymod/events/GuiReplayOverlay.java @@ -1,10 +1,21 @@ - package eu.crushedpixel.replaymod.events; -import java.awt.Color; -import java.awt.Point; -import java.util.concurrent.TimeUnit; - +import eu.crushedpixel.replaymod.ReplayMod; +import eu.crushedpixel.replaymod.entities.CameraEntity; +import eu.crushedpixel.replaymod.gui.GuiCancelRender; +import eu.crushedpixel.replaymod.gui.GuiMouseInput; +import eu.crushedpixel.replaymod.gui.GuiReplaySpeedSlider; +import eu.crushedpixel.replaymod.gui.GuiSpectateSelection; +import eu.crushedpixel.replaymod.holders.Keyframe; +import eu.crushedpixel.replaymod.holders.Position; +import eu.crushedpixel.replaymod.holders.PositionKeyframe; +import eu.crushedpixel.replaymod.holders.TimeKeyframe; +import eu.crushedpixel.replaymod.recording.ConnectionEventHandler; +import eu.crushedpixel.replaymod.registry.ReplayGuiRegistry; +import eu.crushedpixel.replaymod.replay.ReplayHandler; +import eu.crushedpixel.replaymod.replay.ReplayProcess; +import eu.crushedpixel.replaymod.utils.MouseUtils; +import eu.crushedpixel.replaymod.video.VideoWriter; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiChat; @@ -16,739 +27,698 @@ import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; - import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; -import eu.crushedpixel.replaymod.ReplayMod; -import eu.crushedpixel.replaymod.entities.CameraEntity; -import eu.crushedpixel.replaymod.gui.GuiCancelRender; -import eu.crushedpixel.replaymod.gui.GuiReplaySpeedSlider; -import eu.crushedpixel.replaymod.gui.GuiSpectateSelection; -import eu.crushedpixel.replaymod.gui.elements.GuiMouseInput; -import eu.crushedpixel.replaymod.holders.Keyframe; -import eu.crushedpixel.replaymod.holders.Position; -import eu.crushedpixel.replaymod.holders.PositionKeyframe; -import eu.crushedpixel.replaymod.holders.TimeKeyframe; -import eu.crushedpixel.replaymod.recording.ConnectionEventHandler; -import eu.crushedpixel.replaymod.registry.ReplayGuiRegistry; -import eu.crushedpixel.replaymod.replay.ReplayHandler; -import eu.crushedpixel.replaymod.replay.ReplayProcess; -import eu.crushedpixel.replaymod.utils.MouseUtils; -import eu.crushedpixel.replaymod.video.VideoWriter; +import java.awt.*; +import java.util.concurrent.TimeUnit; public class GuiReplayOverlay extends Gui { - private Minecraft mc = Minecraft.getMinecraft(); - - private int sliderX = 35; - private int sliderY = 10; - - private int timelineX = sliderX+100+5; - private int realTimelineX = 10 + 4*25; - private int realTimelineY = 33+10; - - private int ppButtonX = 10; - private int ppButtonY = 10; - - private int r_ppButtonX = 10; - private int r_ppButtonY = realTimelineY+1; - - private int exportButtonX = 35; - private int exportButtonY = realTimelineY+1; - - private int place_ButtonX = 60; - private int place_ButtonY = realTimelineY+1; - - private int time_ButtonX = 85; - private int time_ButtonY = realTimelineY+1; - - private long lastSystemTime = System.currentTimeMillis(); - - private ResourceLocation replay_gui = new ResourceLocation("replaymod", "replay_gui.png"); - private ResourceLocation extended_gui = new ResourceLocation("replaymod", "extended_gui.png"); - private ResourceLocation timeline_icons = new ResourceLocation("replaymod", "timeline_icons.png"); - - private GuiReplaySpeedSlider speedSlider; - - private boolean mouseDown = false; - - public void resetUI() throws Exception { - if(FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { - mc.displayGuiScreen(null); - } - ReplayHandler.setRealTimelineCursor(0); - speedSlider = new GuiReplaySpeedSlider(1, sliderX, sliderY, "Speed"); - } - - @SubscribeEvent - public void onRenderGui(RenderGameOverlayEvent event) { - if(ReplayProcess.isVideoRecording() && ReplayHandler.isInPath() && !(mc.currentScreen instanceof GuiCancelRender)) { - if(event.isCancelable()) event.setCanceled(true); - } - } - - @SubscribeEvent - public void renderRecordingIndicator(RenderGameOverlayEvent.Text event) { - if(!ReplayHandler.isInReplay() && ReplayMod.replaySettings.showRecordingIndicator() && ConnectionEventHandler.isRecording()) { - this.drawString(mc.fontRendererObj, "RECORDING", 30, 18-(mc.fontRendererObj.FONT_HEIGHT/2), Color.WHITE.getRGB()); - mc.renderEngine.bindTexture(replay_gui); - GlStateManager.resetColor(); - GlStateManager.enableAlpha(); - this.drawModalRectWithCustomSizedTexture(10, 10, 40, 21, 16, 16, 64, 64); - } - } - - @SubscribeEvent - public void onRenderGui(RenderGameOverlayEvent.Post event) throws IllegalArgumentException, IllegalAccessException { - - if(!ReplayHandler.isInReplay() || FMLClientHandler.instance().isGUIOpen(GuiSpectateSelection.class) || VideoWriter.isRecording()) { - return; - } - - if(!ReplayGuiRegistry.hidden) ReplayGuiRegistry.hide(); - - if(FMLClientHandler.instance().isGUIOpen(GuiChat.class) || FMLClientHandler.instance().isGUIOpen(GuiInventory.class)) { - mc.displayGuiScreen(new GuiMouseInput()); - } - - GL11.glEnable(GL11.GL_BLEND); - - Point mousePoint = MouseUtils.getMousePos(); - final int mouseX = (int) mousePoint.getX(); - final int mouseY = (int) mousePoint.getY(); - - Point scaled = MouseUtils.getScaledDimensions(); - final int width = (int)scaled.getX(); - final int height = (int)scaled.getY(); - - //Draw Timeline - drawTimeline(timelineX, width - 14, 9); - drawRealTimeline(realTimelineX, width - 14 - 11, realTimelineY, mouseX, mouseY); - - //Play/Pause button - int x = 0; - int y = 0; - - boolean play = !ReplayHandler.isPaused(); - boolean hover = false; - - if(FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { - if(mouseX >= ppButtonX && mouseX <= ppButtonX+20 - && mouseY >= ppButtonY && mouseY <= ppButtonY+20) { - hover = true; - } - } - - if(play) { - y = 20; - } - if(hover) { - x = 20; - } - - mc.renderEngine.bindTexture(replay_gui); - - GlStateManager.resetColor(); - this.drawModalRectWithCustomSizedTexture(ppButtonX, ppButtonY, x, y, 20, 20, 64, 64); - - //When hurrying, no Timeline jumping etc. is possible - if(Mouse.isButtonDown(0) && FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class) && !ReplayHandler.isHurrying()) { //clicking the Button - speedSlider.mousePressed(mc, mouseX, mouseY); - if(!mouseDown) { - mouseDown = true; - if(hover) { - boolean paused = !ReplayHandler.isPaused(); - if(paused) { - ReplayHandler.setSpeed(0); - } else { - ReplayHandler.setSpeed(speedSlider.getSliderValue()); - } - - } else if(mouseX >= exportButtonX && mouseX <= exportButtonX+20 && mouseY >= exportButtonY && exportButtonY <= exportButtonY+20) { - ReplayHandler.startPath(true); - } - - if(mouseX >= timelineX+4 && mouseX <= width - 18 && mouseY >= 11 && mouseY <= 29) { - double tot = (width - 18)-(timelineX+4); - double perc = (mouseX-(timelineX+4))/tot; - double time = perc*(double)ReplayHandler.getReplayLength(); - - if(time < ReplayHandler.getReplayTime()) { - mc.displayGuiScreen(null); - } - - CameraEntity cam = ReplayHandler.getCameraEntity(); - if(cam != null) { - ReplayHandler.setLastPosition(new Position(cam.posX, cam.posY, cam.posZ, cam.rotationPitch, cam.rotationYaw)); - } else { - ReplayHandler.setLastPosition(null); - } - - if((int)time != ReplayHandler.getDesiredTimestamp()) - ReplayHandler.setReplayTime((int)time); - } - } - - } else { - /* - if(Mouse.isButtonDown(0) && FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class) && ReplayHandler.isHurrying()) { - System.out.println("HURRYIN'"); - } - */ - try { - speedSlider.mouseReleased(mouseX, mouseY); - mouseDown = false; - } catch(Exception e) {} - } - - //TODO: Save Video Button - hover = false; - x = 0; - y = 18; - - if(FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { - if(mouseX >= exportButtonX && mouseX <= exportButtonX+20 - && mouseY >= exportButtonY && mouseY <= exportButtonY+20) { - hover = true; - } - } - - if(hover) { - x = 20; - } - - mc.renderEngine.bindTexture(timeline_icons); - - GlStateManager.resetColor(); - this.drawModalRectWithCustomSizedTexture(exportButtonX, exportButtonY, x, y, 20, 20, 64, 64); - - //GlStateManager.resetColor(); - - //Place Keyframe Button - hover = false; - x = 0; - y = 0; - - if(FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { - if(mouseX >= place_ButtonX && mouseX <= place_ButtonX+20 - && mouseY >= place_ButtonY && mouseY <= place_ButtonY+20) { - hover = true; - } - } - - if(hover) { - x = 20; - } - - if(ReplayHandler.getSelected() != null && ReplayHandler.getSelected() instanceof PositionKeyframe) { - y += 20; - } - - mc.renderEngine.bindTexture(extended_gui); - - if(hover && Mouse.isButtonDown(0) && isClick() && FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class) - && !ReplayHandler.isInPath()) { - if(ReplayHandler.getSelected() == null || !(ReplayHandler.getSelected() instanceof PositionKeyframe)) { - addPlaceKeyframe(); - } else { - ReplayHandler.removeKeyframe(ReplayHandler.getSelected()); - } - } - - GlStateManager.resetColor(); - this.drawModalRectWithCustomSizedTexture(place_ButtonX, place_ButtonY, x, y, 20, 20, 64, 64); - - - //Time Keyframe Button - hover = false; - x = 0; - y = 40; - - boolean timeSelected = false; - if(ReplayHandler.getSelected() != null && ReplayHandler.getSelected() instanceof TimeKeyframe) { - timeSelected = true; - x = 40; - y = 0; - } - - if(FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { - if(mouseX >= time_ButtonX && mouseX <= time_ButtonX+20 - && mouseY >= time_ButtonY && mouseY <= time_ButtonY+20) { - hover = true; - } - } - - if(hover) { - if(timeSelected) { - y = 20; - } else { - x = 20; - } - } - - mc.renderEngine.bindTexture(extended_gui); - - if(hover && Mouse.isButtonDown(0) && isClick() && FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { - if(ReplayHandler.getSelected() == null || !(ReplayHandler.getSelected() instanceof TimeKeyframe) && !ReplayHandler.isInPath()) { - addTimeKeyframe(); - } else { - ReplayHandler.removeKeyframe(ReplayHandler.getSelected()); - } - } - - GlStateManager.resetColor(); - this.drawModalRectWithCustomSizedTexture(time_ButtonX, time_ButtonY, x, y, 20, 20, 64, 64); - - if(mouseX >= (timelineX+4) && mouseX <= width - 18 && mouseY >= 11 && mouseY <= 29) { - double tot = (width - 18)-(timelineX+4); - double perc = (mouseX-(timelineX+4))/tot; - long time = Math.round(perc*(double)ReplayHandler.getReplayLength()); - - String timestamp = (String.format("%02d:%02ds", - TimeUnit.MILLISECONDS.toMinutes(time), - TimeUnit.MILLISECONDS.toSeconds(time) - - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time)) - )); - - this.drawCenteredString(mc.fontRendererObj, timestamp, mouseX, mouseY+5, Color.WHITE.getRGB()); - } - - if(mc.inGameHasFocus) { - Mouse.setCursorPosition(width/2, height/2); - } - - try { - speedSlider.drawButton(mc, mouseX, mouseY); - } catch(Exception e) {} - - GlStateManager.resetColor(); - - Entity player = ReplayHandler.getCameraEntity(); - if(player != null) { - player.setVelocity(0, 0, 0); - } - - if(!Mouse.isButtonDown(0)) isClick(); - } - - private int tl_begin_x=0; - private int tl_begin_width = 4; - - private int tl_end_x=60; - private int tl_end_width = 4; - - private int tl_middle_x=4; - - private int tl_y=40; - - private void drawTimeline(int minX, int maxX, int y) { - int zero = minX+tl_begin_width; - int full = maxX-tl_end_width; - - GlStateManager.resetColor(); - mc.renderEngine.bindTexture(replay_gui); - this.drawModalRectWithCustomSizedTexture(minX, y, tl_begin_x, tl_y, tl_begin_width, 22, 64, 64); - - for(int i=minX+tl_begin_width; i= slider_min && mouseX <= sl_max && mouseY >= sl_y && mouseY <= sl_y+slider_height || wasSliding)) { - wasSliding = true; - float dx = ((float)Mouse.getDX() * (float)new ScaledResolution(mc, mc.displayWidth, mc.displayHeight).getScaledWidth() / mc.displayWidth); - this.pos_left = Math.min(1f-this.zoom_scale, Math.max(0f, this.pos_left+(dx/(float)tlWidth))); - } - - if(!Mouse.isButtonDown(0)) { - wasSliding = false; - } - - //Timeline Buttons - //+- Buttons - boolean hover = false; - int px = plus_x; - if(FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { - if(mouseX >= maxX+2 && mouseX <= maxX+2+9 - && mouseY >= y+1 && mouseY <= y+1+9) { - hover = true; - } - } - - if(hover) { - px+=9; - } - - this.drawModalRectWithCustomSizedTexture(maxX+2, y+1, px, plus_y, 9, 9, 64, 64); - - if(hover && Mouse.isButtonDown(0) && FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { - zoomIn(); - } - - hover = false; - int mx = minus_x; - - if(FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { - if(mouseX >= maxX+2 && mouseX <= maxX+2+9 - && mouseY >= y+9+3 && mouseY <= y+9+3+9) { - hover = true; - } - } - - if(hover) { - mx+=9; - } - - this.drawModalRectWithCustomSizedTexture(maxX+2, y+9+3, mx, minus_y, 9, 9, 64, 64); - - if(hover && Mouse.isButtonDown(0) && FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { - zoomOut(); - } - - //show Time String - if(mouseX >= zero && mouseX <= full && mouseY >= y && mouseY <= y+22) { - long tot = Math.round((double)timelineLength*zoom_scale); - double perc = (mouseX-(realTimelineX+4))/(double)(full-zero); - - long time = Math.round(this.pos_left*(double)timelineLength)+Math.round(perc*(double)tot); - - String timestamp = (String.format("%02d:%02ds", - TimeUnit.MILLISECONDS.toMinutes(time), - TimeUnit.MILLISECONDS.toSeconds(time) - - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time)) - )); - this.drawCenteredString(mc.fontRendererObj, timestamp, mouseX, mouseY+5, Color.WHITE.getRGB()); - } - - //draw Markers on timeline - MarkerType mt = MarkerType.getMarkerType(zoom_scale, timelineLength); - - //every x seconds, draw small marker - long left_real = Math.round(pos_left*(double)timelineLength); - long right_real = left_real+(Math.round(zoom_scale*timelineLength)); - long tot = Math.round((double)timelineLength*zoom_scale); - - for(int s=0; s<=timelineLength; s+= mt.getSmallDistance()) { - if(s > right_real) break; - if(s >= left_real) { - //calculate absolute position on screen - long relative = (s) - (left_real); - double perc = ((double)relative/(double)tot); - - long real_width = full-zero; - long rel_x = Math.round(perc*(double)real_width); - - long real_x = zero+rel_x; - - this.drawVerticalLine((int)real_x, y+19-3, y+19, Color.WHITE.getRGB()); - } - } - - //every x seconds, draw big marker - for(int s=0; s<=timelineLength; s+= mt.getDistance()) { - if(s > right_real) break; - if(s >= left_real) { - //calculate absolute position on screen - long relative = s - (left_real); - double perc = ((double)relative/(double)tot); - - long real_width = full-zero; - long rel_x = Math.round(perc*(double)real_width); - - long real_x = zero+rel_x; - - this.drawVerticalLine((int)real_x, y+19-7, y+19, Color.LIGHT_GRAY.getRGB()); - - //write text - int time = s; - String timestamp = (String.format("%02d:%02d", - TimeUnit.MILLISECONDS.toMinutes(time), - TimeUnit.MILLISECONDS.toSeconds(time) - - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time)) - )); - - this.drawCenteredString(mc.fontRendererObj, timestamp, (int)real_x, y-8, Color.WHITE.getRGB()); - } - } - - //handle Mouse clicks on realTimeLine - if(Mouse.isButtonDown(0) && FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class) && !wasSliding && mouseX >= minX+tl_begin_width && mouseX <= maxX-tl_end_width && - mouseY >= y && mouseY <= y+22) { - - //calculate real time and set cursor accordingly - int width = (maxX-tl_end_width) - (minX+tl_begin_width); - int rel_x = mouseX-(minX+tl_begin_width); - - float rel_pos = (float)rel_x/(float)width; - - float abs_width = (zoom_scale*(float)timelineLength); - int real_pos = Math.round(left_real+((rel_pos)*abs_width)); - - ReplayHandler.setRealTimelineCursor(real_pos); - - //Keyframe click handling here - if(isClick()) { - //tolerance is 2 pixels multiplied with the timespan of one pixel - int tolerance = 2*Math.round(abs_width/(float)width); - - if(mouseY >= y+9) { - TimeKeyframe close = ReplayHandler.getClosestTimeKeyframeForRealTime(ReplayHandler.getRealTimelineCursor(), tolerance); - ReplayHandler.selectKeyframe(close); //can be null, deselects keyframe - } else { - PositionKeyframe close = ReplayHandler.getClosestPlaceKeyframeForRealTime(ReplayHandler.getRealTimelineCursor(), tolerance); - ReplayHandler.selectKeyframe(close); //can be null, deselects keyframe - } - } - } - - //Draw Realtime Cursor - if(ReplayHandler.getRealTimelineCursor() >= left_real && ReplayHandler.getRealTimelineCursor() <= right_real) { - long rel_pos = ReplayHandler.getRealTimelineCursor()-left_real; - long rel_width = right_real-left_real; - double perc = (double)rel_pos/(double)rel_width; - - int real_width = (maxX-tl_end_width) - (minX+tl_begin_width); - double rel_x = (float)real_width*perc; - - int real_x = (int)Math.round((minX+tl_begin_width)+rel_x); - mc.renderEngine.bindTexture(this.replay_gui); - - GL11.glEnable(GL11.GL_BLEND); - this.drawModalRectWithCustomSizedTexture(real_x-3, y+3, 44, 0, 8, 16, 64, 64); - //this.drawModalRectWithCustomSizedTexture(real_x, sl_y, u, v, width, height, textureWidth, textureHeight) - } - - - //Draw Keyframe logos - mc.renderEngine.bindTexture(timeline_icons); - for(Keyframe kf : ReplayHandler.getKeyframes()) { - if(kf.getRealTimestamp() > right_real) break; - if(kf.getRealTimestamp() >= left_real) { - int dx = 18; - int dy = 0; - - int ry = y+3; - - if(kf instanceof TimeKeyframe) { - dy = 5; - ry += 5; - } - if(ReplayHandler.isSelected(kf)) { - dx += 5; - } - - long relative = kf.getRealTimestamp() - (left_real); - double perc = ((double)relative/(double)tot); - - long real_width = full-zero; - long rel_x = Math.round(perc*(double)real_width); - - long real_x = zero+rel_x - 2; - - this.drawModalRectWithCustomSizedTexture((int)real_x, ry, dx, dy, 5, 5, 64, 64); - } - } - - //Draw Play/Pause Button - //Play/Pause button - - int dx = 0; - int dy = 0; - - boolean play = ReplayHandler.isInPath(); - hover = false; - - if(FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { - if(mouseX >= r_ppButtonX && mouseX <= r_ppButtonX+20 - && mouseY >= r_ppButtonY && mouseY <= r_ppButtonY+20) { - hover = true; - } - } - - if(play) { - dy = 20; - } - if(hover) { - dx = 20; - } - - mc.renderEngine.bindTexture(replay_gui); - - GlStateManager.resetColor(); - this.drawModalRectWithCustomSizedTexture(r_ppButtonX, r_ppButtonY, dx, dy, 20, 20, 64, 64); - - //Handling the click on the Replay starter - if(hover && Mouse.isButtonDown(0) && isClick() && FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { - if(ReplayHandler.isInPath()) { - ReplayHandler.interruptReplay(); - } else { - ReplayHandler.startPath(false); - } - } - - } - - private void addPlaceKeyframe() { - Entity cam = mc.getRenderViewEntity(); - if(cam == null) return; - ReplayHandler.addKeyframe(new PositionKeyframe(ReplayHandler.getRealTimelineCursor(), new Position(cam.posX, cam.posY, cam.posZ, cam.rotationPitch, cam.rotationYaw))); - } - - private void addTimeKeyframe() { - ReplayHandler.addKeyframe(new TimeKeyframe(ReplayHandler.getRealTimelineCursor(), ReplayHandler.getReplayTime())); - } - - private enum MarkerType { - - ONE_S(1*1000, 100), - FIVE_S(5*1000, 1*1000), - QUARTER_M(15*1000, 3*1000), - HALF_M(30*1000, 5*1000), - ONE_M(60*1000, 10*1000), - FIVE_M(5*60*1000, 50*1000); - - int minimum; - int small_min; - int maximum = 10; - - int getDistance() { - return minimum; - } - - int getSmallDistance() { - return small_min; - } - - MarkerType(int minimum, int small_min) { - this.minimum = minimum; - this.small_min = small_min; - } - - public static MarkerType getMarkerType(float scale, long totalLength) { - long visible = Math.round((double)totalLength*scale); - long seconds = visible; - - for(MarkerType mt : values()) { - if(seconds/mt.getDistance() <= 10) { - return mt; - } - } - - return FIVE_M; - } - } - - private void zoomIn() { - if(!isClick()) return; - this.zoom_scale = Math.max(0.025f, zoom_scale-zoom_steps); - } - - private void zoomOut() { - if(!isClick()) return; - this.zoom_scale = Math.min(1f, zoom_scale+zoom_steps); - this.pos_left = Math.min(pos_left, 1f-zoom_scale); - } - - private boolean mouseDwn = false; - - private boolean isClick() { - if(Mouse.isButtonDown(0)) { - boolean bef = new Boolean(mouseDwn); - mouseDwn = true; - return !bef; - } else { - mouseDwn = false; - return false; - } - } + private final Minecraft mc = Minecraft.getMinecraft(); + int sl_begin_x = 0; + int sl_end_x = 63; + int sl_y = 40; + int plus_x = 0; + int plus_y = 0; + int minus_x = 0; + int minus_y = 9; + int slider_begin_x = 1; + int slider_begin_width = 1; + int slider_end_x = 62; + int slider_end_width = 1; + int slider_y = 50; + int slider_height = 7; + private int sliderX = 35; + private int sliderY = 10; + private int timelineX = sliderX + 100 + 5; + private int realTimelineX = 10 + 4 * 25; + private int realTimelineY = 33 + 10; + private int ppButtonX = 10; + private int ppButtonY = 10; + private int r_ppButtonX = 10; + private int r_ppButtonY = realTimelineY + 1; + private int exportButtonX = 35; + private int exportButtonY = realTimelineY + 1; + private int place_ButtonX = 60; + private int place_ButtonY = realTimelineY + 1; + private int time_ButtonX = 85; + private int time_ButtonY = realTimelineY + 1; + private long lastSystemTime = System.currentTimeMillis(); + private ResourceLocation replay_gui = new ResourceLocation("replaymod", "replay_gui.png"); + private ResourceLocation extended_gui = new ResourceLocation("replaymod", "extended_gui.png"); + private ResourceLocation timeline_icons = new ResourceLocation("replaymod", "timeline_icons.png"); + private GuiReplaySpeedSlider speedSlider; + private boolean mouseDown = false; + private int tl_begin_x = 0; + private int tl_begin_width = 4; + private int tl_end_x = 60; + private int tl_end_width = 4; + private int tl_middle_x = 4; + private int tl_y = 40; + private float zoom_scale = 0.1f; //can see 1/10th of the timeline + private float pos_left = 0f; //left border of timeline is at 0% + private float cursor_pos = 0f; //cursor is at 0% + private long timelineLength = 10 * 60 * 1000; //10 min of timeline + private float zoom_steps = 0.05f; + private boolean wasSliding = false; + private boolean mouseDwn = false; + + public void resetUI() throws Exception { + if(FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { + mc.displayGuiScreen(null); + } + ReplayHandler.setRealTimelineCursor(0); + speedSlider = new GuiReplaySpeedSlider(1, sliderX, sliderY, "Speed"); + } + + @SubscribeEvent + public void onRenderGui(RenderGameOverlayEvent event) { + if(ReplayProcess.isVideoRecording() && ReplayHandler.isInPath() && !(mc.currentScreen instanceof GuiCancelRender)) { + if(event.isCancelable()) event.setCanceled(true); + } + } + + @SubscribeEvent + public void renderRecordingIndicator(RenderGameOverlayEvent.Text event) { + if(!ReplayHandler.isInReplay() && ReplayMod.replaySettings.showRecordingIndicator() && ConnectionEventHandler.isRecording()) { + this.drawString(mc.fontRendererObj, "RECORDING", 30, 18 - (mc.fontRendererObj.FONT_HEIGHT / 2), Color.WHITE.getRGB()); + mc.renderEngine.bindTexture(replay_gui); + GlStateManager.resetColor(); + GlStateManager.enableAlpha(); + this.drawModalRectWithCustomSizedTexture(10, 10, 40, 21, 16, 16, 64, 64); + } + } + + @SubscribeEvent + public void onRenderGui(RenderGameOverlayEvent.Post event) throws IllegalArgumentException, IllegalAccessException { + + if(!ReplayHandler.isInReplay() || FMLClientHandler.instance().isGUIOpen(GuiSpectateSelection.class) || VideoWriter.isRecording()) { + return; + } + + if(!ReplayGuiRegistry.hidden) ReplayGuiRegistry.hide(); + + if(FMLClientHandler.instance().isGUIOpen(GuiChat.class) || FMLClientHandler.instance().isGUIOpen(GuiInventory.class)) { + mc.displayGuiScreen(new GuiMouseInput()); + } + + GL11.glEnable(GL11.GL_BLEND); + + Point mousePoint = MouseUtils.getMousePos(); + final int mouseX = (int) mousePoint.getX(); + final int mouseY = (int) mousePoint.getY(); + + Point scaled = MouseUtils.getScaledDimensions(); + final int width = (int) scaled.getX(); + final int height = (int) scaled.getY(); + + //Draw Timeline + drawTimeline(timelineX, width - 14, 9); + drawRealTimeline(realTimelineX, width - 14 - 11, realTimelineY, mouseX, mouseY); + + //Play/Pause button + int x = 0; + int y = 0; + + boolean play = !ReplayMod.replaySender.paused(); + boolean hover = false; + + if(FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { + if(mouseX >= ppButtonX && mouseX <= ppButtonX + 20 + && mouseY >= ppButtonY && mouseY <= ppButtonY + 20) { + hover = true; + } + } + + if(play) { + y = 20; + } + if(hover) { + x = 20; + } + + mc.renderEngine.bindTexture(replay_gui); + + GlStateManager.resetColor(); + this.drawModalRectWithCustomSizedTexture(ppButtonX, ppButtonY, x, y, 20, 20, 64, 64); + + //When hurrying, no Timeline jumping etc. is possible + if(Mouse.isButtonDown(0) && FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class) && !ReplayMod.replaySender.isHurrying()) { //clicking the Button + speedSlider.mousePressed(mc, mouseX, mouseY); + if(!mouseDown) { + mouseDown = true; + if(hover) { + boolean paused = !ReplayMod.replaySender.paused(); + if(paused) { + ReplayMod.replaySender.setReplaySpeed(0); + } else { + ReplayMod.replaySender.setReplaySpeed(speedSlider.getSliderValue()); + } + + } else if(mouseX >= exportButtonX && mouseX <= exportButtonX + 20 && mouseY >= exportButtonY && exportButtonY <= exportButtonY + 20) { + ReplayHandler.startPath(true); + } + + if(mouseX >= timelineX + 4 && mouseX <= width - 18 && mouseY >= 11 && mouseY <= 29) { + double tot = (width - 18) - (timelineX + 4); + double perc = (mouseX - (timelineX + 4)) / tot; + double time = perc * (double) ReplayMod.replaySender.replayLength(); + + if(time < ReplayMod.replaySender.currentTimeStamp()) { + mc.displayGuiScreen(null); + } + + CameraEntity cam = ReplayHandler.getCameraEntity(); + if(cam != null) { + ReplayHandler.setLastPosition(new Position(cam.posX, cam.posY, cam.posZ, cam.rotationPitch, cam.rotationYaw)); + } else { + ReplayHandler.setLastPosition(null); + } + + if((int) time != ReplayMod.replaySender.getDesiredTimestamp()) + ReplayMod.replaySender.jumpToTime((int) time); + } + } + + } else { + try { + speedSlider.mouseReleased(mouseX, mouseY); + mouseDown = false; + } catch(Exception e) { + } + } + + //TODO: Save Video Button + hover = false; + x = 0; + y = 18; + + if(FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { + if(mouseX >= exportButtonX && mouseX <= exportButtonX + 20 + && mouseY >= exportButtonY && mouseY <= exportButtonY + 20) { + hover = true; + } + } + + if(hover) { + x = 20; + } + + mc.renderEngine.bindTexture(timeline_icons); + + GlStateManager.resetColor(); + this.drawModalRectWithCustomSizedTexture(exportButtonX, exportButtonY, x, y, 20, 20, 64, 64); + + //GlStateManager.resetColor(); + + //Place Keyframe Button + hover = false; + x = 0; + y = 0; + + if(FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { + if(mouseX >= place_ButtonX && mouseX <= place_ButtonX + 20 + && mouseY >= place_ButtonY && mouseY <= place_ButtonY + 20) { + hover = true; + } + } + + if(hover) { + x = 20; + } + + if(ReplayHandler.getSelected() != null && ReplayHandler.getSelected() instanceof PositionKeyframe) { + y += 20; + } + + mc.renderEngine.bindTexture(extended_gui); + + if(hover && Mouse.isButtonDown(0) && isClick() && FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class) + && !ReplayHandler.isInPath()) { + if(ReplayHandler.getSelected() == null || !(ReplayHandler.getSelected() instanceof PositionKeyframe)) { + addPlaceKeyframe(); + } else { + ReplayHandler.removeKeyframe(ReplayHandler.getSelected()); + } + } + + GlStateManager.resetColor(); + this.drawModalRectWithCustomSizedTexture(place_ButtonX, place_ButtonY, x, y, 20, 20, 64, 64); + + + //Time Keyframe Button + hover = false; + x = 0; + y = 40; + + boolean timeSelected = false; + if(ReplayHandler.getSelected() != null && ReplayHandler.getSelected() instanceof TimeKeyframe) { + timeSelected = true; + x = 40; + y = 0; + } + + if(FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { + if(mouseX >= time_ButtonX && mouseX <= time_ButtonX + 20 + && mouseY >= time_ButtonY && mouseY <= time_ButtonY + 20) { + hover = true; + } + } + + if(hover) { + if(timeSelected) { + y = 20; + } else { + x = 20; + } + } + + mc.renderEngine.bindTexture(extended_gui); + + if(hover && Mouse.isButtonDown(0) && isClick() && FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { + if(ReplayHandler.getSelected() == null || !(ReplayHandler.getSelected() instanceof TimeKeyframe) && !ReplayHandler.isInPath()) { + addTimeKeyframe(); + } else { + ReplayHandler.removeKeyframe(ReplayHandler.getSelected()); + } + } + + GlStateManager.resetColor(); + this.drawModalRectWithCustomSizedTexture(time_ButtonX, time_ButtonY, x, y, 20, 20, 64, 64); + + if(mouseX >= (timelineX + 4) && mouseX <= width - 18 && mouseY >= 11 && mouseY <= 29) { + double tot = (width - 18) - (timelineX + 4); + double perc = (mouseX - (timelineX + 4)) / tot; + long time = Math.round(perc * (double) ReplayMod.replaySender.replayLength()); + + String timestamp = (String.format("%02d:%02ds", + TimeUnit.MILLISECONDS.toMinutes(time), + TimeUnit.MILLISECONDS.toSeconds(time) - + TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time)) + )); + + this.drawCenteredString(mc.fontRendererObj, timestamp, mouseX, mouseY + 5, Color.WHITE.getRGB()); + } + + if(mc.inGameHasFocus) { + Mouse.setCursorPosition(width / 2, height / 2); + } + + try { + speedSlider.drawButton(mc, mouseX, mouseY); + } catch(Exception e) { + } + + GlStateManager.resetColor(); + + Entity player = ReplayHandler.getCameraEntity(); + if(player != null) { + player.setVelocity(0, 0, 0); + } + + if(!Mouse.isButtonDown(0)) isClick(); + } + + private void drawTimeline(int minX, int maxX, int y) { + int zero = minX + tl_begin_width; + int full = maxX - tl_end_width; + + GlStateManager.resetColor(); + mc.renderEngine.bindTexture(replay_gui); + this.drawModalRectWithCustomSizedTexture(minX, y, tl_begin_x, tl_y, tl_begin_width, 22, 64, 64); + + for(int i = minX + tl_begin_width; i < maxX - tl_end_width; i += tl_end_x - tl_begin_width) { + this.drawModalRectWithCustomSizedTexture(i, y, tl_begin_x + tl_begin_width + , tl_y, Math.min(tl_end_x - tl_begin_width, maxX - tl_end_width - i) + , 22, 64, 64); + } + + this.drawModalRectWithCustomSizedTexture(maxX - tl_end_width, y, tl_end_x, tl_y, tl_end_width, 22, 64, 64); + + //Cursor + double width = full - zero; + double perc = (double) ReplayMod.replaySender.currentTimeStamp() / (double) ReplayMod.replaySender.replayLength(); + + int cursorX = (int) Math.round(zero + (perc * width)); + this.drawModalRectWithCustomSizedTexture(cursorX - 3, y + 3, 44, 0, 8, 16, 64, 64); + } + + private void drawRealTimeline(int minX, int maxX, int y, int mouseX, int mouseY) { + int zero = minX + tl_begin_width; + int full = maxX - tl_end_width; + + //the real timeline + GlStateManager.resetColor(); + mc.renderEngine.bindTexture(replay_gui); + this.drawModalRectWithCustomSizedTexture(minX, y, tl_begin_x, tl_y, tl_begin_width, 22, 64, 64); + + for(int i = minX + tl_begin_width; i < maxX - tl_end_width; i += tl_end_x - tl_begin_width) { + this.drawModalRectWithCustomSizedTexture(i, y, tl_begin_x + tl_begin_width + , tl_y, Math.min(tl_end_x - tl_begin_width, maxX - tl_end_width - i) + , 22, 64, 64); + } + + this.drawModalRectWithCustomSizedTexture(maxX - tl_end_width, y, tl_end_x, tl_y, tl_end_width, 22, 64, 64); + + //Time Slider + int yo = y + 22 + 1; + GlStateManager.resetColor(); + mc.renderEngine.bindTexture(timeline_icons); + this.drawModalRectWithCustomSizedTexture(minX, yo, sl_begin_x, sl_y, 2, 9, 64, 64); + + for(int i = minX + 2; i < maxX - 1; i += sl_end_x - 2) { + this.drawModalRectWithCustomSizedTexture(i, yo, 2, sl_y, + Math.min(sl_end_x - 2, maxX - 1 - i), 9, 64, 64); + } + + this.drawModalRectWithCustomSizedTexture(maxX - 1, yo, sl_end_x, sl_y, 1, 9, 64, 64); + + //Timeline Pos Slider + int sl_y = yo + 1; + int minPos = minX + 1; + int maxPos = maxX - 2; + int tlWidth = maxPos - minPos; + + int slider_min = minPos + Math.round(pos_left * tlWidth); + int slider_width = Math.round(zoom_scale * tlWidth); + + int sl_max = slider_min + slider_width; + + this.drawModalRectWithCustomSizedTexture(slider_min, sl_y, slider_begin_x, slider_y, slider_begin_width, slider_height, 64, 64); + + for(int i = slider_min + slider_begin_width; i < sl_max - slider_end_width; i += slider_end_x - slider_begin_width - slider_begin_x) { + this.drawModalRectWithCustomSizedTexture(i, sl_y, slider_begin_x + slider_begin_width, slider_y, + Math.min(slider_end_x - slider_end_width - slider_begin_x, sl_max - slider_end_width - i), slider_height, 64, 64); + } + + this.drawModalRectWithCustomSizedTexture(sl_max - slider_end_width, sl_y, slider_end_x, slider_y, + slider_end_width, slider_height, 64, 64); + + //Slider dragging + if(Mouse.isButtonDown(0) && FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class) && (mouseX >= slider_min && mouseX <= sl_max && mouseY >= sl_y && mouseY <= sl_y + slider_height || wasSliding)) { + wasSliding = true; + float dx = ((float) Mouse.getDX() * (float) new ScaledResolution(mc, mc.displayWidth, mc.displayHeight).getScaledWidth() / mc.displayWidth); + this.pos_left = Math.min(1f - this.zoom_scale, Math.max(0f, this.pos_left + (dx / (float) tlWidth))); + } + + if(!Mouse.isButtonDown(0)) { + wasSliding = false; + } + + //Timeline Buttons + //+- Buttons + boolean hover = false; + int px = plus_x; + if(FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { + if(mouseX >= maxX + 2 && mouseX <= maxX + 2 + 9 + && mouseY >= y + 1 && mouseY <= y + 1 + 9) { + hover = true; + } + } + + if(hover) { + px += 9; + } + + this.drawModalRectWithCustomSizedTexture(maxX + 2, y + 1, px, plus_y, 9, 9, 64, 64); + + if(hover && Mouse.isButtonDown(0) && FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { + zoomIn(); + } + + hover = false; + int mx = minus_x; + + if(FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { + if(mouseX >= maxX + 2 && mouseX <= maxX + 2 + 9 + && mouseY >= y + 9 + 3 && mouseY <= y + 9 + 3 + 9) { + hover = true; + } + } + + if(hover) { + mx += 9; + } + + this.drawModalRectWithCustomSizedTexture(maxX + 2, y + 9 + 3, mx, minus_y, 9, 9, 64, 64); + + if(hover && Mouse.isButtonDown(0) && FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { + zoomOut(); + } + + //show Time String + if(mouseX >= zero && mouseX <= full && mouseY >= y && mouseY <= y + 22) { + long tot = Math.round((double) timelineLength * zoom_scale); + double perc = (mouseX - (realTimelineX + 4)) / (double) (full - zero); + + long time = Math.round(this.pos_left * (double) timelineLength) + Math.round(perc * (double) tot); + + String timestamp = (String.format("%02d:%02ds", + TimeUnit.MILLISECONDS.toMinutes(time), + TimeUnit.MILLISECONDS.toSeconds(time) - + TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time)) + )); + this.drawCenteredString(mc.fontRendererObj, timestamp, mouseX, mouseY + 5, Color.WHITE.getRGB()); + } + + //draw Markers on timeline + MarkerType mt = MarkerType.getMarkerType(zoom_scale, timelineLength); + + //every x seconds, draw small marker + long left_real = Math.round(pos_left * (double) timelineLength); + long right_real = left_real + (Math.round(zoom_scale * timelineLength)); + long tot = Math.round((double) timelineLength * zoom_scale); + + for(int s = 0; s <= timelineLength; s += mt.getSmallDistance()) { + if(s > right_real) break; + if(s >= left_real) { + //calculate absolute position on screen + long relative = (s) - (left_real); + double perc = ((double) relative / (double) tot); + + long real_width = full - zero; + long rel_x = Math.round(perc * (double) real_width); + + long real_x = zero + rel_x; + + this.drawVerticalLine((int) real_x, y + 19 - 3, y + 19, Color.WHITE.getRGB()); + } + } + + //every x seconds, draw big marker + for(int s = 0; s <= timelineLength; s += mt.getDistance()) { + if(s > right_real) break; + if(s >= left_real) { + //calculate absolute position on screen + long relative = s - (left_real); + double perc = ((double) relative / (double) tot); + + long real_width = full - zero; + long rel_x = Math.round(perc * (double) real_width); + + long real_x = zero + rel_x; + + this.drawVerticalLine((int) real_x, y + 19 - 7, y + 19, Color.LIGHT_GRAY.getRGB()); + + //write text + int time = s; + String timestamp = (String.format("%02d:%02d", + TimeUnit.MILLISECONDS.toMinutes(time), + TimeUnit.MILLISECONDS.toSeconds(time) - + TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time)) + )); + + this.drawCenteredString(mc.fontRendererObj, timestamp, (int) real_x, y - 8, Color.WHITE.getRGB()); + } + } + + //handle Mouse clicks on realTimeLine + if(Mouse.isButtonDown(0) && FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class) && !wasSliding && mouseX >= minX + tl_begin_width && mouseX <= maxX - tl_end_width && + mouseY >= y && mouseY <= y + 22) { + + //calculate real time and set cursor accordingly + int width = (maxX - tl_end_width) - (minX + tl_begin_width); + int rel_x = mouseX - (minX + tl_begin_width); + + float rel_pos = (float) rel_x / (float) width; + + float abs_width = (zoom_scale * (float) timelineLength); + int real_pos = Math.round(left_real + ((rel_pos) * abs_width)); + + ReplayHandler.setRealTimelineCursor(real_pos); + + //Keyframe click handling here + if(isClick()) { + //tolerance is 2 pixels multiplied with the timespan of one pixel + int tolerance = 2 * Math.round(abs_width / (float) width); + + if(mouseY >= y + 9) { + TimeKeyframe close = ReplayHandler.getClosestTimeKeyframeForRealTime(ReplayHandler.getRealTimelineCursor(), tolerance); + ReplayHandler.selectKeyframe(close); //can be null, deselects keyframe + } else { + PositionKeyframe close = ReplayHandler.getClosestPlaceKeyframeForRealTime(ReplayHandler.getRealTimelineCursor(), tolerance); + ReplayHandler.selectKeyframe(close); //can be null, deselects keyframe + } + } + } + + //Draw Realtime Cursor + if(ReplayHandler.getRealTimelineCursor() >= left_real && ReplayHandler.getRealTimelineCursor() <= right_real) { + long rel_pos = ReplayHandler.getRealTimelineCursor() - left_real; + long rel_width = right_real - left_real; + double perc = (double) rel_pos / (double) rel_width; + + int real_width = (maxX - tl_end_width) - (minX + tl_begin_width); + double rel_x = (float) real_width * perc; + + int real_x = (int) Math.round((minX + tl_begin_width) + rel_x); + mc.renderEngine.bindTexture(this.replay_gui); + + GL11.glEnable(GL11.GL_BLEND); + this.drawModalRectWithCustomSizedTexture(real_x - 3, y + 3, 44, 0, 8, 16, 64, 64); + //this.drawModalRectWithCustomSizedTexture(real_x, sl_y, u, v, width, height, textureWidth, textureHeight) + } + + + //Draw Keyframe logos + mc.renderEngine.bindTexture(timeline_icons); + for(Keyframe kf : ReplayHandler.getKeyframes()) { + if(kf.getRealTimestamp() > right_real) break; + if(kf.getRealTimestamp() >= left_real) { + int dx = 18; + int dy = 0; + + int ry = y + 3; + + if(kf instanceof TimeKeyframe) { + dy = 5; + ry += 5; + } + if(ReplayHandler.isSelected(kf)) { + dx += 5; + } + + long relative = kf.getRealTimestamp() - (left_real); + double perc = ((double) relative / (double) tot); + + long real_width = full - zero; + long rel_x = Math.round(perc * (double) real_width); + + long real_x = zero + rel_x - 2; + + this.drawModalRectWithCustomSizedTexture((int) real_x, ry, dx, dy, 5, 5, 64, 64); + } + } + + //Draw Play/Pause Button + //Play/Pause button + + int dx = 0; + int dy = 0; + + boolean play = ReplayHandler.isInPath(); + hover = false; + + if(FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { + if(mouseX >= r_ppButtonX && mouseX <= r_ppButtonX + 20 + && mouseY >= r_ppButtonY && mouseY <= r_ppButtonY + 20) { + hover = true; + } + } + + if(play) { + dy = 20; + } + if(hover) { + dx = 20; + } + + mc.renderEngine.bindTexture(replay_gui); + + GlStateManager.resetColor(); + this.drawModalRectWithCustomSizedTexture(r_ppButtonX, r_ppButtonY, dx, dy, 20, 20, 64, 64); + + //Handling the click on the Replay starter + if(hover && Mouse.isButtonDown(0) && isClick() && FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { + if(ReplayHandler.isInPath()) { + ReplayHandler.interruptReplay(); + } else { + ReplayHandler.startPath(false); + } + } + + } + + private void addPlaceKeyframe() { + Entity cam = mc.getRenderViewEntity(); + if(cam == null) return; + ReplayHandler.addKeyframe(new PositionKeyframe(ReplayHandler.getRealTimelineCursor(), new Position(cam.posX, cam.posY, cam.posZ, cam.rotationPitch, cam.rotationYaw))); + } + + private void addTimeKeyframe() { + ReplayHandler.addKeyframe(new TimeKeyframe(ReplayHandler.getRealTimelineCursor(), ReplayMod.replaySender.currentTimeStamp())); + } + + private void zoomIn() { + if(!isClick()) return; + this.zoom_scale = Math.max(0.025f, zoom_scale - zoom_steps); + } + + private void zoomOut() { + if(!isClick()) return; + this.zoom_scale = Math.min(1f, zoom_scale + zoom_steps); + this.pos_left = Math.min(pos_left, 1f - zoom_scale); + } + + private boolean isClick() { + if(Mouse.isButtonDown(0)) { + boolean bef = new Boolean(mouseDwn); + mouseDwn = true; + return !bef; + } else { + mouseDwn = false; + return false; + } + } + + private enum MarkerType { + + ONE_S(1 * 1000, 100), + FIVE_S(5 * 1000, 1 * 1000), + QUARTER_M(15 * 1000, 3 * 1000), + HALF_M(30 * 1000, 5 * 1000), + ONE_M(60 * 1000, 10 * 1000), + FIVE_M(5 * 60 * 1000, 50 * 1000); + + int minimum; + int small_min; + int maximum = 10; + + MarkerType(int minimum, int small_min) { + this.minimum = minimum; + this.small_min = small_min; + } + + public static MarkerType getMarkerType(float scale, long totalLength) { + long visible = Math.round((double) totalLength * scale); + long seconds = visible; + + for(MarkerType mt : values()) { + if(seconds / mt.getDistance() <= 10) { + return mt; + } + } + + return FIVE_M; + } + + int getDistance() { + return minimum; + } + + int getSmallDistance() { + return small_min; + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/events/KeyInputHandler.java b/src/main/java/eu/crushedpixel/replaymod/events/KeyInputHandler.java index 87556c35..bb2ab584 100755 --- a/src/main/java/eu/crushedpixel/replaymod/events/KeyInputHandler.java +++ b/src/main/java/eu/crushedpixel/replaymod/events/KeyInputHandler.java @@ -1,119 +1,113 @@ package eu.crushedpixel.replaymod.events; -import org.lwjgl.input.Keyboard; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiIngame; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.gui.GuiYesNoCallback; -import net.minecraft.client.settings.KeyBinding; -import net.minecraftforge.fml.client.FMLClientHandler; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.common.gameevent.InputEvent.KeyInputEvent; import eu.crushedpixel.replaymod.ReplayMod; import eu.crushedpixel.replaymod.entities.CameraEntity.MoveDirection; import eu.crushedpixel.replaymod.gui.GuiCancelRender; -import eu.crushedpixel.replaymod.gui.elements.GuiMouseInput; +import eu.crushedpixel.replaymod.gui.GuiMouseInput; import eu.crushedpixel.replaymod.registry.KeybindRegistry; import eu.crushedpixel.replaymod.replay.ReplayHandler; import eu.crushedpixel.replaymod.replay.ReplayProcess; import eu.crushedpixel.replaymod.replay.spectate.SpectateHandler; -import eu.crushedpixel.replaymod.video.ReplayScreenshot; +import net.minecraft.client.Minecraft; +import net.minecraft.client.settings.KeyBinding; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.gameevent.InputEvent.KeyInputEvent; +import org.lwjgl.input.Keyboard; public class KeyInputHandler { - private Minecraft mc = Minecraft.getMinecraft(); - - private boolean escDown = false; - - @SubscribeEvent - public void onKeyInput(KeyInputEvent event) { + private final Minecraft mc = Minecraft.getMinecraft(); - if(!ReplayHandler.isInReplay()) return; - if(mc.currentScreen != null) { - return; - } - - if(Keyboard.getEventKeyState() && !Keyboard.isRepeatEvent() && Keyboard.isKeyDown(Keyboard.KEY_ESCAPE) - && ReplayHandler.isInPath() && ReplayProcess.isVideoRecording() - && mc.currentScreen == null && !escDown) { - mc.displayGuiScreen(new GuiCancelRender()); - } - - escDown = Keyboard.isKeyDown(Keyboard.KEY_ESCAPE) && Keyboard.getEventKeyState(); - - boolean found = false; - - KeyBinding[] keyBindings = Minecraft.getMinecraft().gameSettings.keyBindings; - for(KeyBinding kb : keyBindings) { - if(!kb.isKeyDown()) { - continue; - } - try { - boolean speedup = false; - - if(ReplayHandler.isCamera()) { - if(kb.getKeyDescription().equals("key.forward")) { - ReplayHandler.getCameraEntity().setMovement(MoveDirection.FORWARD); - speedup = true; - } + private boolean escDown = false; - if(kb.getKeyDescription().equals("key.back")) { - ReplayHandler.getCameraEntity().setMovement(MoveDirection.BACKWARD); - speedup = true; - } + @SubscribeEvent + public void onKeyInput(KeyInputEvent event) { - if(kb.getKeyDescription().equals("key.jump")) { - ReplayHandler.getCameraEntity().setMovement(MoveDirection.UP); - speedup = true; - } + if(!ReplayHandler.isInReplay()) return; + if(mc.currentScreen != null) { + return; + } - if(kb.getKeyDescription().equals("key.left")) { - ReplayHandler.getCameraEntity().setMovement(MoveDirection.LEFT); - speedup = true; - } + if(Keyboard.getEventKeyState() && !Keyboard.isRepeatEvent() && Keyboard.isKeyDown(Keyboard.KEY_ESCAPE) + && ReplayHandler.isInPath() && ReplayProcess.isVideoRecording() + && mc.currentScreen == null && !escDown) { + mc.displayGuiScreen(new GuiCancelRender()); + } - if(kb.getKeyDescription().equals("key.right")) { - ReplayHandler.getCameraEntity().setMovement(MoveDirection.RIGHT); - speedup = true; - } - } - if(kb.getKeyDescription().equals("key.sneak")) { - if(ReplayHandler.isCamera()) { - ReplayHandler.getCameraEntity().setMovement(MoveDirection.DOWN); - speedup = true; - } else { - ReplayHandler.spectateCamera(); - } - } - - if(speedup) { - ReplayHandler.getCameraEntity().speedUp(); - } + escDown = Keyboard.isKeyDown(Keyboard.KEY_ESCAPE) && Keyboard.getEventKeyState(); - if(kb.getKeyDescription().equals("key.chat")) { - mc.displayGuiScreen(new GuiMouseInput()); - break; - } + boolean found = false; - //Custom registered handlers - if(kb.getKeyDescription().equals(KeybindRegistry.KEY_THUMBNAIL) && kb.isPressed() && !found) { - TickAndRenderListener.requestScreenshot(); - //TODO: Make this properly work - } + KeyBinding[] keyBindings = Minecraft.getMinecraft().gameSettings.keyBindings; + for(KeyBinding kb : keyBindings) { + if(!kb.isKeyDown()) { + continue; + } + try { + boolean speedup = false; - if(kb.getKeyDescription().equals(KeybindRegistry.KEY_SPECTATE) && kb.isPressed() && !found) { - SpectateHandler.openSpectateSelection(); - } + if(ReplayHandler.isCamera()) { + if(kb.getKeyDescription().equals("key.forward")) { + ReplayHandler.getCameraEntity().setMovement(MoveDirection.FORWARD); + speedup = true; + } - if(kb.getKeyDescription().equals(KeybindRegistry.KEY_LIGHTING) && kb.isPressed()) { - ReplayMod.replaySettings.setLightingEnabled(!ReplayMod.replaySettings.isLightingEnabled()); - } + if(kb.getKeyDescription().equals("key.back")) { + ReplayHandler.getCameraEntity().setMovement(MoveDirection.BACKWARD); + speedup = true; + } - } catch(Exception e) { - e.printStackTrace(); - } - found = true; - } - } + if(kb.getKeyDescription().equals("key.jump")) { + ReplayHandler.getCameraEntity().setMovement(MoveDirection.UP); + speedup = true; + } + + if(kb.getKeyDescription().equals("key.left")) { + ReplayHandler.getCameraEntity().setMovement(MoveDirection.LEFT); + speedup = true; + } + + if(kb.getKeyDescription().equals("key.right")) { + ReplayHandler.getCameraEntity().setMovement(MoveDirection.RIGHT); + speedup = true; + } + } + if(kb.getKeyDescription().equals("key.sneak")) { + if(ReplayHandler.isCamera()) { + ReplayHandler.getCameraEntity().setMovement(MoveDirection.DOWN); + speedup = true; + } else { + ReplayHandler.spectateCamera(); + } + } + + if(speedup) { + ReplayHandler.getCameraEntity().speedUp(); + } + + if(kb.getKeyDescription().equals("key.chat")) { + mc.displayGuiScreen(new GuiMouseInput()); + break; + } + + //Custom registered handlers + if(kb.getKeyDescription().equals(KeybindRegistry.KEY_THUMBNAIL) && kb.isPressed() && !found) { + TickAndRenderListener.requestScreenshot(); + //TODO: Make this properly work + } + + if(kb.getKeyDescription().equals(KeybindRegistry.KEY_SPECTATE) && kb.isPressed() && !found) { + SpectateHandler.openSpectateSelection(); + } + + if(kb.getKeyDescription().equals(KeybindRegistry.KEY_LIGHTING) && kb.isPressed()) { + ReplayMod.replaySettings.setLightingEnabled(!ReplayMod.replaySettings.isLightingEnabled()); + } + + } catch(Exception e) { + e.printStackTrace(); + } + found = true; + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/events/MinecraftTicker.java b/src/main/java/eu/crushedpixel/replaymod/events/MinecraftTicker.java index 83a76390..4ca24331 100755 --- a/src/main/java/eu/crushedpixel/replaymod/events/MinecraftTicker.java +++ b/src/main/java/eu/crushedpixel/replaymod/events/MinecraftTicker.java @@ -1,10 +1,6 @@ package eu.crushedpixel.replaymod.events; -import java.io.IOException; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - +import eu.crushedpixel.replaymod.reflection.MCPNames; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiChat; import net.minecraft.client.gui.GuiScreen; @@ -17,425 +13,344 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.play.client.C16PacketClientStatus; import net.minecraft.util.MathHelper; import net.minecraft.util.ReportedException; - import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; -import org.lwjgl.opengl.Display; -import eu.crushedpixel.replaymod.entities.CameraEntity; -import eu.crushedpixel.replaymod.reflection.MCPNames; -import eu.crushedpixel.replaymod.replay.ReplayHandler; +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; public class MinecraftTicker { - private static Field debugCrashKeyPressTime, rightClickDelayTimer, systemTime, leftClickCounter; - private static Method getSystemTime, updateDebugProfilerName, - clickMouse, middleClickMouse, rightClickMouse, sendClickBlockToController; - - private static Minecraft mc = Minecraft.getMinecraft(); - - private static float camPitch, camYaw, smoothCamPartialTicks, - smoothCamFilterX, smoothCamFilterY; - - static { - try { - debugCrashKeyPressTime = Minecraft.class.getDeclaredField(MCPNames.field("field_83002_am")); - debugCrashKeyPressTime.setAccessible(true); - - rightClickDelayTimer = Minecraft.class.getDeclaredField(MCPNames.field("field_71467_ac")); - rightClickDelayTimer.setAccessible(true); - - systemTime = Minecraft.class.getDeclaredField(MCPNames.field("field_71423_H")); - systemTime.setAccessible(true); - - leftClickCounter = Minecraft.class.getDeclaredField(MCPNames.field("field_71429_W")); - leftClickCounter.setAccessible(true); - - getSystemTime = Minecraft.class.getDeclaredMethod(MCPNames.method("func_71386_F")); - getSystemTime.setAccessible(true); - - updateDebugProfilerName = Minecraft.class.getDeclaredMethod(MCPNames.method("func_71383_b"), int.class); - updateDebugProfilerName.setAccessible(true); - - clickMouse = Minecraft.class.getDeclaredMethod(MCPNames.method("func_147116_af")); - clickMouse.setAccessible(true); - - rightClickMouse = Minecraft.class.getDeclaredMethod(MCPNames.method("func_147121_ag")); - rightClickMouse.setAccessible(true); - - middleClickMouse = Minecraft.class.getDeclaredMethod(MCPNames.method("func_147112_ai")); - middleClickMouse.setAccessible(true); - - sendClickBlockToController = Minecraft.class.getDeclaredMethod(MCPNames.method("func_147115_a"), boolean.class); - sendClickBlockToController.setAccessible(true); - - } catch(Exception e) { - e.printStackTrace(); - } - } - - public static void runMouseKeyboardTick(Minecraft mc) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException { - - if(mc.thePlayer == null) return; - try { - mc.mcProfiler.endStartSection("mouse"); - int i; - while(Mouse.next()) { - i = Mouse.getEventButton(); - KeyBinding.setKeyBindState(i - 100, Mouse.getEventButtonState()); - - if (Mouse.getEventButtonState()) - { - if (mc.thePlayer.isSpectator() && i == 2) - { - mc.ingameGUI.func_175187_g().func_175261_b(); - } - else - { - KeyBinding.onTick(i - 100); - } - } - - long k = (Long)getSystemTime.invoke(mc) - (Long)systemTime.get(mc); - - if (k <= 200L) - { - int j = Mouse.getEventDWheel(); - - if (j != 0) - { - if (mc.thePlayer.isSpectator()) - { - j = j < 0 ? -1 : 1; - - if (mc.ingameGUI.func_175187_g().func_175262_a()) - { - mc.ingameGUI.func_175187_g().func_175259_b(-j); - } - else - { - float f = MathHelper.clamp_float(mc.thePlayer.capabilities.getFlySpeed() + (float)j * 0.005F, 0.0F, 0.2F); - mc.thePlayer.capabilities.setFlySpeed(f); - } - } - else - { - mc.thePlayer.inventory.changeCurrentItem(j); - } - } - - if (mc.currentScreen == null) - { - if (!mc.inGameHasFocus && Mouse.getEventButtonState()) - { - mc.setIngameFocus(); - } - } - else - { - mc.currentScreen.handleMouseInput(); - } - } - net.minecraftforge.fml.common.FMLCommonHandler.instance().fireMouseInput(); - } - - if ((Integer)leftClickCounter.get(mc) > 0) - { - leftClickCounter.set(mc, (Integer)leftClickCounter.get(mc) - 1); - } - mc.mcProfiler.endStartSection("keyboard"); - - while (Keyboard.next()) - { - i = Keyboard.getEventKey() == 0 ? Keyboard.getEventCharacter() + 256 : Keyboard.getEventKey(); - KeyBinding.setKeyBindState(i, Keyboard.getEventKeyState()); - - if (Keyboard.getEventKeyState()) - { - KeyBinding.onTick(i); - } - - if ((Long)debugCrashKeyPressTime.get(mc) > 0L) - { - if ((Long)getSystemTime.invoke(mc) - (Long)debugCrashKeyPressTime.get(mc) >= 6000L) - { - throw new ReportedException(new CrashReport("Manually triggered debug crash", new Throwable())); - } - - if (!Keyboard.isKeyDown(46) || !Keyboard.isKeyDown(61)) - { - debugCrashKeyPressTime.set(mc, -1); - } - } - else if (Keyboard.isKeyDown(46) && Keyboard.isKeyDown(61)) - { - debugCrashKeyPressTime.set(mc, getSystemTime.invoke(mc)); - } - - mc.dispatchKeypresses(); - - if (Keyboard.getEventKeyState()) - { - if (i == 62 && mc.entityRenderer != null) - { - mc.entityRenderer.switchUseShader(); - } - - if (mc.currentScreen != null) - { - mc.currentScreen.handleKeyboardInput(); - } - else - { - if (i == 1) - { - mc.displayInGameMenu(); - } - - if (i == 32 && Keyboard.isKeyDown(61) && mc.ingameGUI != null) - { - mc.ingameGUI.getChatGUI().clearChatMessages(); - } - - if (i == 31 && Keyboard.isKeyDown(61)) - { - mc.refreshResources(); - } - - if (i == 17 && Keyboard.isKeyDown(61)) - { - ; - } - - if (i == 18 && Keyboard.isKeyDown(61)) - { - ; - } - - if (i == 47 && Keyboard.isKeyDown(61)) - { - ; - } - - if (i == 38 && Keyboard.isKeyDown(61)) - { - ; - } - - if (i == 22 && Keyboard.isKeyDown(61)) - { - ; - } - - if (i == 20 && Keyboard.isKeyDown(61)) - { - mc.refreshResources(); - } - - if (i == 33 && Keyboard.isKeyDown(61)) - { - boolean flag1 = Keyboard.isKeyDown(42) | Keyboard.isKeyDown(54); - mc.gameSettings.setOptionValue(GameSettings.Options.RENDER_DISTANCE, flag1 ? -1 : 1); - } - - if (i == 30 && Keyboard.isKeyDown(61)) - { - mc.renderGlobal.loadRenderers(); - } - - if (i == 35 && Keyboard.isKeyDown(61)) - { - mc.gameSettings.advancedItemTooltips = !mc.gameSettings.advancedItemTooltips; - mc.gameSettings.saveOptions(); - } - - if (i == 48 && Keyboard.isKeyDown(61)) - { - mc.getRenderManager().setDebugBoundingBox(!mc.getRenderManager().isDebugBoundingBox()); - } - - if (i == 25 && Keyboard.isKeyDown(61)) - { - mc.gameSettings.pauseOnLostFocus = !mc.gameSettings.pauseOnLostFocus; - mc.gameSettings.saveOptions(); - } - - if (i == 59) - { - mc.gameSettings.hideGUI = !mc.gameSettings.hideGUI; - } - - if (i == 61) - { - mc.gameSettings.showDebugInfo = !mc.gameSettings.showDebugInfo; - mc.gameSettings.showDebugProfilerChart = GuiScreen.isShiftKeyDown(); - } - - if (mc.gameSettings.keyBindTogglePerspective.isPressed()) - { - ++mc.gameSettings.thirdPersonView; - - if (mc.gameSettings.thirdPersonView > 2) - { - mc.gameSettings.thirdPersonView = 0; - } - - if (mc.gameSettings.thirdPersonView == 0) - { - mc.entityRenderer.loadEntityShader(mc.getRenderViewEntity()); - } - else if (mc.gameSettings.thirdPersonView == 1) - { - mc.entityRenderer.loadEntityShader((Entity)null); - } - } - - if (mc.gameSettings.keyBindSmoothCamera.isPressed()) - { - mc.gameSettings.smoothCamera = !mc.gameSettings.smoothCamera; - } - } - - if (mc.gameSettings.showDebugInfo && mc.gameSettings.showDebugProfilerChart) - { - if (i == 11) - { - updateDebugProfilerName.invoke(mc, 0); - } - - for (int l = 0; l < 9; ++l) - { - if (i == 2 + l) - { - updateDebugProfilerName.invoke(mc, l+1); - } - } - } - } - net.minecraftforge.fml.common.FMLCommonHandler.instance().fireKeyInput(); - } - - for (i = 0; i < 9; ++i) - { - if (mc.gameSettings.keyBindsHotbar[i].isPressed()) - { - if (mc.thePlayer.isSpectator()) - { - mc.ingameGUI.func_175187_g().func_175260_a(i); - } - else - { - mc.thePlayer.inventory.currentItem = i; - } - } - } - - boolean flag = mc.gameSettings.chatVisibility != EntityPlayer.EnumChatVisibility.HIDDEN; - - while (mc.gameSettings.keyBindInventory.isPressed()) - { - if (mc.playerController.isRidingHorse()) - { - mc.thePlayer.sendHorseInventory(); - } - else - { - mc.getNetHandler().addToSendQueue(new C16PacketClientStatus(C16PacketClientStatus.EnumState.OPEN_INVENTORY_ACHIEVEMENT)); - mc.displayGuiScreen(new GuiInventory(mc.thePlayer)); - } - } - - while (mc.gameSettings.keyBindDrop.isPressed()) - { - if (!mc.thePlayer.isSpectator()) - { - mc.thePlayer.dropOneItem(GuiScreen.isCtrlKeyDown()); - } - } - - while (mc.gameSettings.keyBindChat.isPressed() && flag) - { - mc.displayGuiScreen(new GuiChat()); - } - - if (mc.currentScreen == null && mc.gameSettings.keyBindCommand.isPressed() && flag) - { - mc.displayGuiScreen(new GuiChat("/")); - } - - if (mc.thePlayer != null && mc.thePlayer.isUsingItem()) - { - if (!mc.gameSettings.keyBindUseItem.isKeyDown()) - { - mc.playerController.onStoppedUsingItem(mc.thePlayer); - } - - label435: - - while (true) - { - if (!mc.gameSettings.keyBindAttack.isPressed()) - { - while (mc.gameSettings.keyBindUseItem.isPressed()) - { - ; - } - - while (true) - { - if (mc.gameSettings.keyBindPickBlock.isPressed()) - { - continue; - } - - break label435; - } - } - } - } - else - { - while (mc.gameSettings.keyBindAttack.isPressed()) - { - if(mc != null) - try { - clickMouse.invoke(mc); - } catch(Exception e) {} - - } - - while (mc.gameSettings.keyBindUseItem.isPressed()) - { - if(mc != null) - try { - rightClickMouse.invoke(mc); - } catch(Exception e) {} - } - - while (mc.gameSettings.keyBindPickBlock.isPressed()) - { - if(mc != null) - try { - middleClickMouse.invoke(mc); - } catch(Exception e) {} - } - } - - if (mc.gameSettings.keyBindUseItem.isKeyDown() && (Integer)rightClickDelayTimer.get(mc) == 0 && !mc.thePlayer.isUsingItem()) - { - if(mc != null) - try { - rightClickMouse.invoke(mc); - } catch(Exception e) {} - } - - if(mc != null) - try { - sendClickBlockToController.invoke(mc, mc.currentScreen == null && mc.gameSettings.keyBindAttack.isKeyDown() && mc.inGameHasFocus); - } catch(Exception e) {} - - if(mc != null) - systemTime.set(mc, getSystemTime.invoke(mc)); - } catch(Exception e) {} - } + private static Field debugCrashKeyPressTime, rightClickDelayTimer, systemTime, leftClickCounter; + private static Method getSystemTime, updateDebugProfilerName, + clickMouse, middleClickMouse, rightClickMouse, sendClickBlockToController; + + static { + try { + debugCrashKeyPressTime = Minecraft.class.getDeclaredField(MCPNames.field("field_83002_am")); + debugCrashKeyPressTime.setAccessible(true); + + rightClickDelayTimer = Minecraft.class.getDeclaredField(MCPNames.field("field_71467_ac")); + rightClickDelayTimer.setAccessible(true); + + systemTime = Minecraft.class.getDeclaredField(MCPNames.field("field_71423_H")); + systemTime.setAccessible(true); + + leftClickCounter = Minecraft.class.getDeclaredField(MCPNames.field("field_71429_W")); + leftClickCounter.setAccessible(true); + + getSystemTime = Minecraft.class.getDeclaredMethod(MCPNames.method("func_71386_F")); + getSystemTime.setAccessible(true); + + updateDebugProfilerName = Minecraft.class.getDeclaredMethod(MCPNames.method("func_71383_b"), int.class); + updateDebugProfilerName.setAccessible(true); + + clickMouse = Minecraft.class.getDeclaredMethod(MCPNames.method("func_147116_af")); + clickMouse.setAccessible(true); + + rightClickMouse = Minecraft.class.getDeclaredMethod(MCPNames.method("func_147121_ag")); + rightClickMouse.setAccessible(true); + + middleClickMouse = Minecraft.class.getDeclaredMethod(MCPNames.method("func_147112_ai")); + middleClickMouse.setAccessible(true); + + sendClickBlockToController = Minecraft.class.getDeclaredMethod(MCPNames.method("func_147115_a"), boolean.class); + sendClickBlockToController.setAccessible(true); + + } catch(Exception e) { + e.printStackTrace(); + } + } + + public static void runMouseKeyboardTick(Minecraft mc) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException { + + if(mc.thePlayer == null) return; + try { + mc.mcProfiler.endStartSection("mouse"); + int i; + while(Mouse.next()) { + i = Mouse.getEventButton(); + KeyBinding.setKeyBindState(i - 100, Mouse.getEventButtonState()); + + if(Mouse.getEventButtonState()) { + if(mc.thePlayer.isSpectator() && i == 2) { + mc.ingameGUI.func_175187_g().func_175261_b(); + } else { + KeyBinding.onTick(i - 100); + } + } + + long k = (Long) getSystemTime.invoke(mc) - (Long) systemTime.get(mc); + + if(k <= 200L) { + int j = Mouse.getEventDWheel(); + + if(j != 0) { + if(mc.thePlayer.isSpectator()) { + j = j < 0 ? -1 : 1; + + if(mc.ingameGUI.func_175187_g().func_175262_a()) { + mc.ingameGUI.func_175187_g().func_175259_b(-j); + } else { + float f = MathHelper.clamp_float(mc.thePlayer.capabilities.getFlySpeed() + (float) j * 0.005F, 0.0F, 0.2F); + mc.thePlayer.capabilities.setFlySpeed(f); + } + } else { + mc.thePlayer.inventory.changeCurrentItem(j); + } + } + + if(mc.currentScreen == null) { + if(!mc.inGameHasFocus && Mouse.getEventButtonState()) { + mc.setIngameFocus(); + } + } else { + mc.currentScreen.handleMouseInput(); + } + } + net.minecraftforge.fml.common.FMLCommonHandler.instance().fireMouseInput(); + } + + if((Integer) leftClickCounter.get(mc) > 0) { + leftClickCounter.set(mc, (Integer) leftClickCounter.get(mc) - 1); + } + mc.mcProfiler.endStartSection("keyboard"); + + while(Keyboard.next()) { + i = Keyboard.getEventKey() == 0 ? Keyboard.getEventCharacter() + 256 : Keyboard.getEventKey(); + KeyBinding.setKeyBindState(i, Keyboard.getEventKeyState()); + + if(Keyboard.getEventKeyState()) { + KeyBinding.onTick(i); + } + + if((Long) debugCrashKeyPressTime.get(mc) > 0L) { + if((Long) getSystemTime.invoke(mc) - (Long) debugCrashKeyPressTime.get(mc) >= 6000L) { + throw new ReportedException(new CrashReport("Manually triggered debug crash", new Throwable())); + } + + if(!Keyboard.isKeyDown(46) || !Keyboard.isKeyDown(61)) { + debugCrashKeyPressTime.set(mc, -1); + } + } else if(Keyboard.isKeyDown(46) && Keyboard.isKeyDown(61)) { + debugCrashKeyPressTime.set(mc, getSystemTime.invoke(mc)); + } + + mc.dispatchKeypresses(); + + if(Keyboard.getEventKeyState()) { + if(i == 62 && mc.entityRenderer != null) { + mc.entityRenderer.switchUseShader(); + } + + if(mc.currentScreen != null) { + mc.currentScreen.handleKeyboardInput(); + } else { + if(i == 1) { + mc.displayInGameMenu(); + } + + if(i == 32 && Keyboard.isKeyDown(61) && mc.ingameGUI != null) { + mc.ingameGUI.getChatGUI().clearChatMessages(); + } + + if(i == 31 && Keyboard.isKeyDown(61)) { + mc.refreshResources(); + } + + if(i == 17 && Keyboard.isKeyDown(61)) { + ; + } + + if(i == 18 && Keyboard.isKeyDown(61)) { + ; + } + + if(i == 47 && Keyboard.isKeyDown(61)) { + ; + } + + if(i == 38 && Keyboard.isKeyDown(61)) { + ; + } + + if(i == 22 && Keyboard.isKeyDown(61)) { + ; + } + + if(i == 20 && Keyboard.isKeyDown(61)) { + mc.refreshResources(); + } + + if(i == 33 && Keyboard.isKeyDown(61)) { + boolean flag1 = Keyboard.isKeyDown(42) | Keyboard.isKeyDown(54); + mc.gameSettings.setOptionValue(GameSettings.Options.RENDER_DISTANCE, flag1 ? -1 : 1); + } + + if(i == 30 && Keyboard.isKeyDown(61)) { + mc.renderGlobal.loadRenderers(); + } + + if(i == 35 && Keyboard.isKeyDown(61)) { + mc.gameSettings.advancedItemTooltips = !mc.gameSettings.advancedItemTooltips; + mc.gameSettings.saveOptions(); + } + + if(i == 48 && Keyboard.isKeyDown(61)) { + mc.getRenderManager().setDebugBoundingBox(!mc.getRenderManager().isDebugBoundingBox()); + } + + if(i == 25 && Keyboard.isKeyDown(61)) { + mc.gameSettings.pauseOnLostFocus = !mc.gameSettings.pauseOnLostFocus; + mc.gameSettings.saveOptions(); + } + + if(i == 59) { + mc.gameSettings.hideGUI = !mc.gameSettings.hideGUI; + } + + if(i == 61) { + mc.gameSettings.showDebugInfo = !mc.gameSettings.showDebugInfo; + mc.gameSettings.showDebugProfilerChart = GuiScreen.isShiftKeyDown(); + } + + if(mc.gameSettings.keyBindTogglePerspective.isPressed()) { + ++mc.gameSettings.thirdPersonView; + + if(mc.gameSettings.thirdPersonView > 2) { + mc.gameSettings.thirdPersonView = 0; + } + + if(mc.gameSettings.thirdPersonView == 0) { + mc.entityRenderer.loadEntityShader(mc.getRenderViewEntity()); + } else if(mc.gameSettings.thirdPersonView == 1) { + mc.entityRenderer.loadEntityShader((Entity) null); + } + } + + if(mc.gameSettings.keyBindSmoothCamera.isPressed()) { + mc.gameSettings.smoothCamera = !mc.gameSettings.smoothCamera; + } + } + + if(mc.gameSettings.showDebugInfo && mc.gameSettings.showDebugProfilerChart) { + if(i == 11) { + updateDebugProfilerName.invoke(mc, 0); + } + + for(int l = 0; l < 9; ++l) { + if(i == 2 + l) { + updateDebugProfilerName.invoke(mc, l + 1); + } + } + } + } + net.minecraftforge.fml.common.FMLCommonHandler.instance().fireKeyInput(); + } + + for(i = 0; i < 9; ++i) { + if(mc.gameSettings.keyBindsHotbar[i].isPressed()) { + if(mc.thePlayer.isSpectator()) { + mc.ingameGUI.func_175187_g().func_175260_a(i); + } else { + mc.thePlayer.inventory.currentItem = i; + } + } + } + + boolean flag = mc.gameSettings.chatVisibility != EntityPlayer.EnumChatVisibility.HIDDEN; + + while(mc.gameSettings.keyBindInventory.isPressed()) { + if(mc.playerController.isRidingHorse()) { + mc.thePlayer.sendHorseInventory(); + } else { + mc.getNetHandler().addToSendQueue(new C16PacketClientStatus(C16PacketClientStatus.EnumState.OPEN_INVENTORY_ACHIEVEMENT)); + mc.displayGuiScreen(new GuiInventory(mc.thePlayer)); + } + } + + while(mc.gameSettings.keyBindDrop.isPressed()) { + if(!mc.thePlayer.isSpectator()) { + mc.thePlayer.dropOneItem(GuiScreen.isCtrlKeyDown()); + } + } + + while(mc.gameSettings.keyBindChat.isPressed() && flag) { + mc.displayGuiScreen(new GuiChat()); + } + + if(mc.currentScreen == null && mc.gameSettings.keyBindCommand.isPressed() && flag) { + mc.displayGuiScreen(new GuiChat("/")); + } + + if(mc.thePlayer != null && mc.thePlayer.isUsingItem()) { + if(!mc.gameSettings.keyBindUseItem.isKeyDown()) { + mc.playerController.onStoppedUsingItem(mc.thePlayer); + } + + label435: + + while(true) { + if(!mc.gameSettings.keyBindAttack.isPressed()) { + while(mc.gameSettings.keyBindUseItem.isPressed()) { + ; + } + + while(true) { + if(mc.gameSettings.keyBindPickBlock.isPressed()) { + continue; + } + + break label435; + } + } + } + } else { + while(mc.gameSettings.keyBindAttack.isPressed()) { + if(mc != null) + try { + clickMouse.invoke(mc); + } catch(Exception e) { + } + + } + + while(mc.gameSettings.keyBindUseItem.isPressed()) { + if(mc != null) + try { + rightClickMouse.invoke(mc); + } catch(Exception e) { + } + } + + while(mc.gameSettings.keyBindPickBlock.isPressed()) { + if(mc != null) + try { + middleClickMouse.invoke(mc); + } catch(Exception e) { + } + } + } + + if(mc.gameSettings.keyBindUseItem.isKeyDown() && (Integer) rightClickDelayTimer.get(mc) == 0 && !mc.thePlayer.isUsingItem()) { + if(mc != null) + try { + rightClickMouse.invoke(mc); + } catch(Exception e) { + } + } + + if(mc != null) + try { + sendClickBlockToController.invoke(mc, mc.currentScreen == null && mc.gameSettings.keyBindAttack.isKeyDown() && mc.inGameHasFocus); + } catch(Exception e) { + } + + if(mc != null) + systemTime.set(mc, getSystemTime.invoke(mc)); + } catch(Exception e) { + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/events/RecordingHandler.java b/src/main/java/eu/crushedpixel/replaymod/events/RecordingHandler.java index 92df6d1f..008b64fc 100755 --- a/src/main/java/eu/crushedpixel/replaymod/events/RecordingHandler.java +++ b/src/main/java/eu/crushedpixel/replaymod/events/RecordingHandler.java @@ -1,31 +1,17 @@ package eu.crushedpixel.replaymod.events; +import eu.crushedpixel.replaymod.recording.ConnectionEventHandler; +import eu.crushedpixel.replaymod.reflection.MCPNames; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.List; - import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; -import net.minecraft.network.play.server.S04PacketEntityEquipment; -import net.minecraft.network.play.server.S0APacketUseBed; -import net.minecraft.network.play.server.S0BPacketAnimation; -import net.minecraft.network.play.server.S0CPacketSpawnPlayer; -import net.minecraft.network.play.server.S0DPacketCollectItem; -import net.minecraft.network.play.server.S12PacketEntityVelocity; -import net.minecraft.network.play.server.S13PacketDestroyEntities; +import net.minecraft.network.play.server.*; import net.minecraft.network.play.server.S14PacketEntity.S17PacketEntityLookMove; -import net.minecraft.network.play.server.S18PacketEntityTeleport; -import net.minecraft.network.play.server.S19PacketEntityHeadLook; -import net.minecraft.network.play.server.S19PacketEntityStatus; -import net.minecraft.network.play.server.S1BPacketEntityAttach; -import net.minecraft.network.play.server.S38PacketPlayerListItem; import net.minecraft.network.play.server.S38PacketPlayerListItem.Action; import net.minecraft.util.MathHelper; import net.minecraftforge.event.entity.EntityJoinWorldEvent; @@ -38,190 +24,190 @@ import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.ItemPickupEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerRespawnEvent; import net.minecraftforge.fml.common.gameevent.TickEvent.PlayerTickEvent; -import eu.crushedpixel.replaymod.recording.ConnectionEventHandler; -import eu.crushedpixel.replaymod.reflection.MCPNames; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; public class RecordingHandler { - private Minecraft mc = Minecraft.getMinecraft(); + public static final int entityID = Integer.MIN_VALUE + 9001; + private static Field dataWatcherField; - public static final int entityID = Integer.MIN_VALUE+9001; + static { + try { + dataWatcherField = S0CPacketSpawnPlayer.class.getDeclaredField(MCPNames.field("field_148960_i")); + dataWatcherField.setAccessible(true); + } catch(Exception e) { + e.printStackTrace(); + } + } - @SubscribeEvent - public void onPlayerJoin(EntityJoinWorldEvent e) { - try { - if(e.entity != mc.thePlayer) return; - if(!ConnectionEventHandler.isRecording()) return; + private final Minecraft mc = Minecraft.getMinecraft(); + private Double lastX = null, lastY = null, lastZ = null; + private List lastEffects = new ArrayList(); + private ItemStack[] playerItems = new ItemStack[5]; + private int ticksSinceLastCorrection = 0; + private boolean wasSleeping = false; + private int lastRiding = -1; - EntityPlayer player = (EntityPlayer)e.entity; + @SubscribeEvent + public void onPlayerJoin(EntityJoinWorldEvent e) { + try { + if(e.entity != mc.thePlayer) return; + if(!ConnectionEventHandler.isRecording()) return; - S38PacketPlayerListItem ppli = new S38PacketPlayerListItem(); - ByteBuf buf = Unpooled.buffer(); - PacketBuffer pbuf = new PacketBuffer(buf); + EntityPlayer player = (EntityPlayer) e.entity; - pbuf.writeEnumValue(Action.ADD_PLAYER); - pbuf.writeVarIntToBuffer(1); - pbuf.writeUuid(e.entity.getUniqueID()); + S38PacketPlayerListItem ppli = new S38PacketPlayerListItem(); + ByteBuf buf = Unpooled.buffer(); + PacketBuffer pbuf = new PacketBuffer(buf); - pbuf.writeString(player.getName()); - pbuf.writeVarIntToBuffer(0); - pbuf.writeVarIntToBuffer(mc.playerController.getCurrentGameType().getID()); - pbuf.writeVarIntToBuffer(0); + pbuf.writeEnumValue(Action.ADD_PLAYER); + pbuf.writeVarIntToBuffer(1); + pbuf.writeUuid(e.entity.getUniqueID()); - pbuf.writeBoolean(true); - pbuf.writeChatComponent(player.getDisplayName()); + pbuf.writeString(player.getName()); + pbuf.writeVarIntToBuffer(0); + pbuf.writeVarIntToBuffer(mc.playerController.getCurrentGameType().getID()); + pbuf.writeVarIntToBuffer(0); - ppli.readPacketData(pbuf); - ConnectionEventHandler.insertPacket(ppli); + pbuf.writeBoolean(true); + pbuf.writeChatComponent(player.getDisplayName()); - ConnectionEventHandler.insertPacket(spawnPlayer(mc.thePlayer)); - } catch(Exception e1) { - e1.printStackTrace(); - } - } + ppli.readPacketData(pbuf); + ConnectionEventHandler.insertPacket(ppli); - private static Field dataWatcherField; + ConnectionEventHandler.insertPacket(spawnPlayer(mc.thePlayer)); + } catch(Exception e1) { + e1.printStackTrace(); + } + } - static { - try { - dataWatcherField = S0CPacketSpawnPlayer.class.getDeclaredField(MCPNames.field("field_148960_i")); - dataWatcherField.setAccessible(true); - } catch(Exception e) { - e.printStackTrace(); - } - } - - private S0CPacketSpawnPlayer spawnPlayer(EntityPlayer player) { - try { - S0CPacketSpawnPlayer packet = new S0CPacketSpawnPlayer(); + private S0CPacketSpawnPlayer spawnPlayer(EntityPlayer player) { + try { + S0CPacketSpawnPlayer packet = new S0CPacketSpawnPlayer(); - ByteBuf bb = Unpooled.buffer(); - PacketBuffer pb = new PacketBuffer(bb); + ByteBuf bb = Unpooled.buffer(); + PacketBuffer pb = new PacketBuffer(bb); - pb.writeVarIntToBuffer(entityID); - pb.writeUuid(player.getUUID(player.getGameProfile())); + pb.writeVarIntToBuffer(entityID); + pb.writeUuid(player.getUUID(player.getGameProfile())); - pb.writeInt(MathHelper.floor_double(player.posX * 32.0D)); - pb.writeInt(MathHelper.floor_double(player.posY * 32.0D)); - pb.writeInt(MathHelper.floor_double(player.posZ * 32.0D)); - pb.writeByte((byte)((int)(player.rotationYaw * 256.0F / 360.0F))); - pb.writeByte((byte)((int)(player.rotationPitch * 256.0F / 360.0F))); + pb.writeInt(MathHelper.floor_double(player.posX * 32.0D)); + pb.writeInt(MathHelper.floor_double(player.posY * 32.0D)); + pb.writeInt(MathHelper.floor_double(player.posZ * 32.0D)); + pb.writeByte((byte) ((int) (player.rotationYaw * 256.0F / 360.0F))); + pb.writeByte((byte) ((int) (player.rotationPitch * 256.0F / 360.0F))); - ItemStack itemstack = player.inventory.getCurrentItem(); - pb.writeShort(itemstack == null ? 0 : Item.getIdFromItem(itemstack.getItem())); - - player.getDataWatcher().writeTo(pb); + ItemStack itemstack = player.inventory.getCurrentItem(); + pb.writeShort(itemstack == null ? 0 : Item.getIdFromItem(itemstack.getItem())); - packet.readPacketData(pb); - - dataWatcherField.set(packet, player.getDataWatcher()); - - return packet; - } catch(Exception e) { - e.printStackTrace(); - return null; - } - } + player.getDataWatcher().writeTo(pb); - private Double lastX = null, lastY = null, lastZ = null; - private List lastEffects = new ArrayList(); + packet.readPacketData(pb); - private ItemStack[] playerItems = new ItemStack[5]; + dataWatcherField.set(packet, player.getDataWatcher()); - public void resetVars() { - lastX = lastY = lastZ = null; - lastEffects = new ArrayList(); - playerItems = new ItemStack[5]; - } + return packet; + } catch(Exception e) { + e.printStackTrace(); + return null; + } + } - private int ticksSinceLastCorrection = 0; + public void resetVars() { + lastX = lastY = lastZ = null; + lastEffects = new ArrayList(); + playerItems = new ItemStack[5]; + } - @SubscribeEvent - public void onPlayerTick(PlayerTickEvent e) { - if(!ConnectionEventHandler.isRecording()) return; - try { - if(e.player != mc.thePlayer) return; - if(!ConnectionEventHandler.isRecording()) return; + @SubscribeEvent + public void onPlayerTick(PlayerTickEvent e) { + if(!ConnectionEventHandler.isRecording()) return; + try { + if(e.player != mc.thePlayer) return; + if(!ConnectionEventHandler.isRecording()) return; - boolean force = false; - if(lastX == null || lastY == null || lastZ == null) { - force = true; - lastX = e.player.posX; - lastY = e.player.posY; - lastZ = e.player.posZ; - } + boolean force = false; + if(lastX == null || lastY == null || lastZ == null) { + force = true; + lastX = e.player.posX; + lastY = e.player.posY; + lastZ = e.player.posZ; + } - ticksSinceLastCorrection++; - if(ticksSinceLastCorrection >= 100) { - ticksSinceLastCorrection = 0; - force = true; - } + ticksSinceLastCorrection++; + if(ticksSinceLastCorrection >= 100) { + ticksSinceLastCorrection = 0; + force = true; + } - double dx = e.player.posX - lastX; - double dy = e.player.posY - lastY; - double dz = e.player.posZ - lastZ; + double dx = e.player.posX - lastX; + double dy = e.player.posY - lastY; + double dz = e.player.posZ - lastZ; - lastX = e.player.posX; - lastY = e.player.posY; - lastZ = e.player.posZ; + lastX = e.player.posX; + lastY = e.player.posY; + lastZ = e.player.posZ; - Packet packet = null; - if(force || Math.abs(dx) > 4.0 || Math.abs(dy) > 4.0 || Math.abs(dz) > 4.0) { - int x = MathHelper.floor_double(e.player.posX * 32.0D); - int y = MathHelper.floor_double(e.player.posY * 32.0D); - int z = MathHelper.floor_double(e.player.posZ * 32.0D); - byte yaw = (byte)((int)(e.player.rotationYaw * 256.0F / 360.0F)); - byte pitch = (byte)((int)(e.player.rotationPitch * 256.0F / 360.0F)); - packet = new S18PacketEntityTeleport(entityID, x, y, z, yaw, pitch, e.player.onGround); - } else { - byte oldYaw = (byte)((int)(e.player.prevRotationYaw * 256.0F / 360.0F)); - byte newYaw = (byte)((int)(e.player.rotationYaw * 256.0F / 360.0F)); - byte oldPitch = (byte)((int)(e.player.prevRotationPitch * 256.0F / 360.0F)); - byte newPitch = (byte)((int)(e.player.rotationPitch * 256.0F / 360.0F)); + Packet packet = null; + if(force || Math.abs(dx) > 4.0 || Math.abs(dy) > 4.0 || Math.abs(dz) > 4.0) { + int x = MathHelper.floor_double(e.player.posX * 32.0D); + int y = MathHelper.floor_double(e.player.posY * 32.0D); + int z = MathHelper.floor_double(e.player.posZ * 32.0D); + byte yaw = (byte) ((int) (e.player.rotationYaw * 256.0F / 360.0F)); + byte pitch = (byte) ((int) (e.player.rotationPitch * 256.0F / 360.0F)); + packet = new S18PacketEntityTeleport(entityID, x, y, z, yaw, pitch, e.player.onGround); + } else { + byte oldYaw = (byte) ((int) (e.player.prevRotationYaw * 256.0F / 360.0F)); + byte newYaw = (byte) ((int) (e.player.rotationYaw * 256.0F / 360.0F)); + byte oldPitch = (byte) ((int) (e.player.prevRotationPitch * 256.0F / 360.0F)); + byte newPitch = (byte) ((int) (e.player.rotationPitch * 256.0F / 360.0F)); - byte dPitch = (byte)(newPitch-oldPitch); - byte dYaw = (byte)(newYaw-oldYaw); + byte dPitch = (byte) (newPitch - oldPitch); + byte dYaw = (byte) (newYaw - oldYaw); - packet = new S17PacketEntityLookMove(entityID, - (byte)Math.round(dx*32), (byte)Math.round(dy*32), (byte)Math.round(dz*32), - newYaw, newPitch, e.player.onGround); - } + packet = new S17PacketEntityLookMove(entityID, + (byte) Math.round(dx * 32), (byte) Math.round(dy * 32), (byte) Math.round(dz * 32), + newYaw, newPitch, e.player.onGround); + } - ConnectionEventHandler.insertPacket(packet); + ConnectionEventHandler.insertPacket(packet); - //HEAD POS - S19PacketEntityHeadLook head = new S19PacketEntityHeadLook(); - ByteBuf bb1 = Unpooled.buffer(); - PacketBuffer pb1 = new PacketBuffer(bb1); + //HEAD POS + S19PacketEntityHeadLook head = new S19PacketEntityHeadLook(); + ByteBuf bb1 = Unpooled.buffer(); + PacketBuffer pb1 = new PacketBuffer(bb1); - pb1.writeVarIntToBuffer(entityID); - pb1.writeByte(((int)(e.player.rotationYawHead * 256.0F / 360.0F))); + pb1.writeVarIntToBuffer(entityID); + pb1.writeByte(((int) (e.player.rotationYawHead * 256.0F / 360.0F))); - head.readPacketData(pb1); + head.readPacketData(pb1); - ConnectionEventHandler.insertPacket(head); + ConnectionEventHandler.insertPacket(head); - S12PacketEntityVelocity vel = new S12PacketEntityVelocity(entityID, e.player.motionX, e.player.motionY, e.player.motionZ); - ConnectionEventHandler.insertPacket(vel); + S12PacketEntityVelocity vel = new S12PacketEntityVelocity(entityID, e.player.motionX, e.player.motionY, e.player.motionZ); + ConnectionEventHandler.insertPacket(vel); - //Animation Packets - //Swing Animation - if(e.player.swingProgressInt == 1) { - S0BPacketAnimation pac = new S0BPacketAnimation(); + //Animation Packets + //Swing Animation + if(e.player.swingProgressInt == 1) { + S0BPacketAnimation pac = new S0BPacketAnimation(); - ByteBuf bb = Unpooled.buffer(); - PacketBuffer pb = new PacketBuffer(bb); + ByteBuf bb = Unpooled.buffer(); + PacketBuffer pb = new PacketBuffer(bb); - pb.writeVarIntToBuffer(entityID); - pb.writeByte(0); + pb.writeVarIntToBuffer(entityID); + pb.writeByte(0); - pac.readPacketData(pb); + pac.readPacketData(pb); - ConnectionEventHandler.insertPacket(pac); - } + ConnectionEventHandler.insertPacket(pac); + } /* - //Potion Effect Handling + //Potion Effect Handling List found = new ArrayList(); for(PotionEffect pe : (Collection)e.player.getActivePotionEffects()) { found.add(pe.getPotionID()); @@ -240,243 +226,243 @@ public class RecordingHandler { lastEffects = found; */ - //Inventory Handling - if(playerItems[0] != mc.thePlayer.getHeldItem()) { - playerItems[0] = mc.thePlayer.getHeldItem(); - S04PacketEntityEquipment pee = new S04PacketEntityEquipment(entityID, 0, playerItems[0]); - ConnectionEventHandler.insertPacket(pee); - } + //Inventory Handling + if(playerItems[0] != mc.thePlayer.getHeldItem()) { + playerItems[0] = mc.thePlayer.getHeldItem(); + S04PacketEntityEquipment pee = new S04PacketEntityEquipment(entityID, 0, playerItems[0]); + ConnectionEventHandler.insertPacket(pee); + } - if(playerItems[1] != mc.thePlayer.inventory.armorInventory[0]) { - playerItems[1] = mc.thePlayer.inventory.armorInventory[0]; - S04PacketEntityEquipment pee = new S04PacketEntityEquipment(entityID, 1, playerItems[1]); - ConnectionEventHandler.insertPacket(pee); - } + if(playerItems[1] != mc.thePlayer.inventory.armorInventory[0]) { + playerItems[1] = mc.thePlayer.inventory.armorInventory[0]; + S04PacketEntityEquipment pee = new S04PacketEntityEquipment(entityID, 1, playerItems[1]); + ConnectionEventHandler.insertPacket(pee); + } - if(playerItems[2] != mc.thePlayer.inventory.armorInventory[1]) { - playerItems[2] = mc.thePlayer.inventory.armorInventory[1]; - S04PacketEntityEquipment pee = new S04PacketEntityEquipment(entityID, 2, playerItems[2]); - ConnectionEventHandler.insertPacket(pee); - } + if(playerItems[2] != mc.thePlayer.inventory.armorInventory[1]) { + playerItems[2] = mc.thePlayer.inventory.armorInventory[1]; + S04PacketEntityEquipment pee = new S04PacketEntityEquipment(entityID, 2, playerItems[2]); + ConnectionEventHandler.insertPacket(pee); + } - if(playerItems[3] != mc.thePlayer.inventory.armorInventory[2]) { - playerItems[3] = mc.thePlayer.inventory.armorInventory[2]; - S04PacketEntityEquipment pee = new S04PacketEntityEquipment(entityID, 3, playerItems[3]); - ConnectionEventHandler.insertPacket(pee); - } + if(playerItems[3] != mc.thePlayer.inventory.armorInventory[2]) { + playerItems[3] = mc.thePlayer.inventory.armorInventory[2]; + S04PacketEntityEquipment pee = new S04PacketEntityEquipment(entityID, 3, playerItems[3]); + ConnectionEventHandler.insertPacket(pee); + } - if(playerItems[4] != mc.thePlayer.inventory.armorInventory[3]) { - playerItems[4] = mc.thePlayer.inventory.armorInventory[3]; - S04PacketEntityEquipment pee = new S04PacketEntityEquipment(entityID, 4, playerItems[4]); - ConnectionEventHandler.insertPacket(pee); - } + if(playerItems[4] != mc.thePlayer.inventory.armorInventory[3]) { + playerItems[4] = mc.thePlayer.inventory.armorInventory[3]; + S04PacketEntityEquipment pee = new S04PacketEntityEquipment(entityID, 4, playerItems[4]); + ConnectionEventHandler.insertPacket(pee); + } - //Leaving Ride + //Leaving Ride - if((!mc.thePlayer.isRiding() && lastRiding != -1) || - (mc.thePlayer.isRiding() && lastRiding != mc.thePlayer.ridingEntity.getEntityId())) { - if(!mc.thePlayer.isRiding()) { - lastRiding = -1; - } else { - lastRiding = mc.thePlayer.ridingEntity.getEntityId(); - } + if((!mc.thePlayer.isRiding() && lastRiding != -1) || + (mc.thePlayer.isRiding() && lastRiding != mc.thePlayer.ridingEntity.getEntityId())) { + if(!mc.thePlayer.isRiding()) { + lastRiding = -1; + } else { + lastRiding = mc.thePlayer.ridingEntity.getEntityId(); + } - S1BPacketEntityAttach pea = new S1BPacketEntityAttach(); + S1BPacketEntityAttach pea = new S1BPacketEntityAttach(); - ByteBuf buf = Unpooled.buffer(); - PacketBuffer pbuf = new PacketBuffer(buf); + ByteBuf buf = Unpooled.buffer(); + PacketBuffer pbuf = new PacketBuffer(buf); - pbuf.writeInt(entityID); - pbuf.writeInt(lastRiding); - pbuf.writeBoolean(false); + pbuf.writeInt(entityID); + pbuf.writeInt(lastRiding); + pbuf.writeBoolean(false); - pea.readPacketData(pbuf); + pea.readPacketData(pbuf); - ConnectionEventHandler.insertPacket(pea); - } - - //Sleeping - if(!mc.thePlayer.isPlayerSleeping() && wasSleeping) { - S0BPacketAnimation pac = new S0BPacketAnimation(); + ConnectionEventHandler.insertPacket(pea); + } - ByteBuf bb = Unpooled.buffer(); - PacketBuffer pb = new PacketBuffer(bb); + //Sleeping + if(!mc.thePlayer.isPlayerSleeping() && wasSleeping) { + S0BPacketAnimation pac = new S0BPacketAnimation(); - pb.writeVarIntToBuffer(entityID); - pb.writeByte(2); + ByteBuf bb = Unpooled.buffer(); + PacketBuffer pb = new PacketBuffer(bb); - pac.readPacketData(pb); + pb.writeVarIntToBuffer(entityID); + pb.writeByte(2); - ConnectionEventHandler.insertPacket(pac); - - wasSleeping = false; - } + pac.readPacketData(pb); - } catch(Exception e1) { - e1.printStackTrace(); - } - } + ConnectionEventHandler.insertPacket(pac); - @SubscribeEvent - public void onPickupItem(ItemPickupEvent event) { - if(!ConnectionEventHandler.isRecording()) return; - try { - ConnectionEventHandler.insertPacket(new S0DPacketCollectItem(event.pickedUp.getEntityId(), entityID)); - } catch(Exception e) { - e.printStackTrace(); - } - } + wasSleeping = false; + } - @SubscribeEvent - public void onRespawn(PlayerRespawnEvent event) { - if(!ConnectionEventHandler.isRecording()) return; - try { - //destroy entity, then respawn - ConnectionEventHandler.insertPacket(new S13PacketDestroyEntities(entityID)); - ConnectionEventHandler.insertPacket(spawnPlayer(mc.thePlayer)); - } catch(Exception e) { - e.printStackTrace(); - } - } + } catch(Exception e1) { + e1.printStackTrace(); + } + } - @SubscribeEvent - public void onHurt(LivingHurtEvent event) { - if(!ConnectionEventHandler.isRecording()) return; - try { - if(event.entity.getEntityId() != mc.thePlayer.getEntityId()) { - return; - }; + @SubscribeEvent + public void onPickupItem(ItemPickupEvent event) { + if(!ConnectionEventHandler.isRecording()) return; + try { + ConnectionEventHandler.insertPacket(new S0DPacketCollectItem(event.pickedUp.getEntityId(), entityID)); + } catch(Exception e) { + e.printStackTrace(); + } + } - S19PacketEntityStatus packet = new S19PacketEntityStatus(); + @SubscribeEvent + public void onRespawn(PlayerRespawnEvent event) { + if(!ConnectionEventHandler.isRecording()) return; + try { + //destroy entity, then respawn + ConnectionEventHandler.insertPacket(new S13PacketDestroyEntities(entityID)); + ConnectionEventHandler.insertPacket(spawnPlayer(mc.thePlayer)); + } catch(Exception e) { + e.printStackTrace(); + } + } - ByteBuf buf = Unpooled.buffer(); - PacketBuffer pbuf = new PacketBuffer(buf); + @SubscribeEvent + public void onHurt(LivingHurtEvent event) { + if(!ConnectionEventHandler.isRecording()) return; + try { + if(event.entity.getEntityId() != mc.thePlayer.getEntityId()) { + return; + } + ; - pbuf.writeInt(entityID); - pbuf.writeByte(2); + S19PacketEntityStatus packet = new S19PacketEntityStatus(); - packet.readPacketData(pbuf); + ByteBuf buf = Unpooled.buffer(); + PacketBuffer pbuf = new PacketBuffer(buf); - ConnectionEventHandler.insertPacket(packet); + pbuf.writeInt(entityID); + pbuf.writeByte(2); - //Damage Animation - S0BPacketAnimation pac = new S0BPacketAnimation(); + packet.readPacketData(pbuf); - ByteBuf bb = Unpooled.buffer(); - PacketBuffer pb = new PacketBuffer(bb); + ConnectionEventHandler.insertPacket(packet); - pb.writeVarIntToBuffer(entityID); - pb.writeByte(1); + //Damage Animation + S0BPacketAnimation pac = new S0BPacketAnimation(); - pac.readPacketData(pb); + ByteBuf bb = Unpooled.buffer(); + PacketBuffer pb = new PacketBuffer(bb); - ConnectionEventHandler.insertPacket(pac); - } catch(Exception e) { - e.printStackTrace(); - } - } + pb.writeVarIntToBuffer(entityID); + pb.writeByte(1); - @SubscribeEvent - public void onDeath(LivingDeathEvent event) { - if(!ConnectionEventHandler.isRecording()) return; - try { - if(event.entity.getEntityId() != mc.thePlayer.getEntityId()) { - return; - }; + pac.readPacketData(pb); - S19PacketEntityStatus packet = new S19PacketEntityStatus(); + ConnectionEventHandler.insertPacket(pac); + } catch(Exception e) { + e.printStackTrace(); + } + } - ByteBuf buf = Unpooled.buffer(); - PacketBuffer pbuf = new PacketBuffer(buf); + @SubscribeEvent + public void onDeath(LivingDeathEvent event) { + if(!ConnectionEventHandler.isRecording()) return; + try { + if(event.entity.getEntityId() != mc.thePlayer.getEntityId()) { + return; + } + ; - pbuf.writeInt(entityID); - pbuf.writeByte(3); + S19PacketEntityStatus packet = new S19PacketEntityStatus(); - packet.readPacketData(pbuf); + ByteBuf buf = Unpooled.buffer(); + PacketBuffer pbuf = new PacketBuffer(buf); - ConnectionEventHandler.insertPacket(packet); - } catch(Exception e) { - e.printStackTrace(); - } - } + pbuf.writeInt(entityID); + pbuf.writeByte(3); - @SubscribeEvent - public void onStartEating(PlayerUseItemEvent.Start event) { - if(!ConnectionEventHandler.isRecording()) return; - try { - if(!event.entityPlayer.isEating()) return; - S0BPacketAnimation packet = new S0BPacketAnimation(); + packet.readPacketData(pbuf); - ByteBuf bb = Unpooled.buffer(); - PacketBuffer pb = new PacketBuffer(bb); + ConnectionEventHandler.insertPacket(packet); + } catch(Exception e) { + e.printStackTrace(); + } + } - pb.writeVarIntToBuffer(entityID); - pb.writeByte(3); + @SubscribeEvent + public void onStartEating(PlayerUseItemEvent.Start event) { + if(!ConnectionEventHandler.isRecording()) return; + try { + if(!event.entityPlayer.isEating()) return; + S0BPacketAnimation packet = new S0BPacketAnimation(); - packet.readPacketData(pb); + ByteBuf bb = Unpooled.buffer(); + PacketBuffer pb = new PacketBuffer(bb); - ConnectionEventHandler.insertPacket(packet); - } catch(Exception e) { - e.printStackTrace(); - } - } - - private boolean wasSleeping = false; + pb.writeVarIntToBuffer(entityID); + pb.writeByte(3); - @SubscribeEvent - public void onSleep(PlayerSleepInBedEvent event) { - if(!ConnectionEventHandler.isRecording()) return; - try { - if(event.entityPlayer != mc.thePlayer) { - return; - }; + packet.readPacketData(pb); - System.out.println(event.getResult()); - S0APacketUseBed pub = new S0APacketUseBed(); + ConnectionEventHandler.insertPacket(packet); + } catch(Exception e) { + e.printStackTrace(); + } + } - ByteBuf buf = Unpooled.buffer(); - PacketBuffer pbuf = new PacketBuffer(buf); + @SubscribeEvent + public void onSleep(PlayerSleepInBedEvent event) { + if(!ConnectionEventHandler.isRecording()) return; + try { + if(event.entityPlayer != mc.thePlayer) { + return; + } + ; - pbuf.writeVarIntToBuffer(entityID); - pbuf.writeBlockPos(event.pos); + System.out.println(event.getResult()); + S0APacketUseBed pub = new S0APacketUseBed(); - pub.readPacketData(pbuf); + ByteBuf buf = Unpooled.buffer(); + PacketBuffer pbuf = new PacketBuffer(buf); - ConnectionEventHandler.insertPacket(pub); + pbuf.writeVarIntToBuffer(entityID); + pbuf.writeBlockPos(event.pos); - wasSleeping = true; + pub.readPacketData(pbuf); - } catch(Exception e) { - e.printStackTrace(); - } - } + ConnectionEventHandler.insertPacket(pub); - private int lastRiding = -1; + wasSleeping = true; - @SubscribeEvent - public void enterMinecart(MinecartInteractEvent event) { - if(!ConnectionEventHandler.isRecording()) return; - try { - if(event.player != mc.thePlayer) { - return; - }; + } catch(Exception e) { + e.printStackTrace(); + } + } - S1BPacketEntityAttach pea = new S1BPacketEntityAttach(); + @SubscribeEvent + public void enterMinecart(MinecartInteractEvent event) { + if(!ConnectionEventHandler.isRecording()) return; + try { + if(event.player != mc.thePlayer) { + return; + } + ; - ByteBuf buf = Unpooled.buffer(); - PacketBuffer pbuf = new PacketBuffer(buf); + S1BPacketEntityAttach pea = new S1BPacketEntityAttach(); - pbuf.writeInt(entityID); - pbuf.writeInt(event.minecart.getEntityId()); - pbuf.writeBoolean(false); + ByteBuf buf = Unpooled.buffer(); + PacketBuffer pbuf = new PacketBuffer(buf); - pea.readPacketData(pbuf); + pbuf.writeInt(entityID); + pbuf.writeInt(event.minecart.getEntityId()); + pbuf.writeBoolean(false); - ConnectionEventHandler.insertPacket(pea); + pea.readPacketData(pbuf); - lastRiding = event.minecart.getEntityId(); - } catch(Exception e) { - e.printStackTrace(); - } - } + ConnectionEventHandler.insertPacket(pea); + + lastRiding = event.minecart.getEntityId(); + } catch(Exception e) { + e.printStackTrace(); + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/events/TickAndRenderListener.java b/src/main/java/eu/crushedpixel/replaymod/events/TickAndRenderListener.java index 6a40c4f4..1fcf84d2 100644 --- a/src/main/java/eu/crushedpixel/replaymod/events/TickAndRenderListener.java +++ b/src/main/java/eu/crushedpixel/replaymod/events/TickAndRenderListener.java @@ -1,14 +1,13 @@ package eu.crushedpixel.replaymod.events; -import java.io.IOException; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; - -import eu.crushedpixel.replaymod.chat.ChatMessageRequests; -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; -import org.lwjgl.opengl.Display; - +import eu.crushedpixel.replaymod.ReplayMod; +import eu.crushedpixel.replaymod.chat.ChatMessageHandler; +import eu.crushedpixel.replaymod.gui.GuiCancelRender; +import eu.crushedpixel.replaymod.gui.GuiMouseInput; +import eu.crushedpixel.replaymod.reflection.MCPNames; +import eu.crushedpixel.replaymod.replay.ReplayHandler; +import eu.crushedpixel.replaymod.replay.ReplayProcess; +import eu.crushedpixel.replaymod.video.ReplayScreenshot; import net.minecraft.client.Minecraft; import net.minecraftforge.client.event.MouseEvent; import net.minecraftforge.client.event.RenderWorldLastEvent; @@ -16,92 +15,82 @@ import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.InputEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; -import eu.crushedpixel.replaymod.gui.GuiCancelRender; -import eu.crushedpixel.replaymod.gui.elements.GuiMouseInput; -import eu.crushedpixel.replaymod.reflection.MCPNames; -import eu.crushedpixel.replaymod.replay.ReplayHandler; -import eu.crushedpixel.replaymod.replay.ReplayProcess; -import eu.crushedpixel.replaymod.video.ReplayScreenshot; +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.Display; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; public class TickAndRenderListener { - private static Minecraft mc = Minecraft.getMinecraft(); - - private double lastX, lastY, lastZ; - private float lastPitch, lastYaw; - - private static Field isGamePaused; + private static Minecraft mc = Minecraft.getMinecraft(); - static { - try { - isGamePaused = Minecraft.class.getDeclaredField(MCPNames.field("field_71445_n")); - isGamePaused.setAccessible(true); - } catch(Exception e) { - e.printStackTrace(); - } - } + private static Field isGamePaused; + private static int requestScreenshot = 0; - @SubscribeEvent - public void onRenderWorld(RenderWorldLastEvent event) throws - InvocationTargetException, IOException, IllegalAccessException, IllegalArgumentException { - if(!ReplayHandler.isInReplay()) return; //If not in Replay, cancel + static { + try { + isGamePaused = Minecraft.class.getDeclaredField(MCPNames.field("field_71445_n")); + isGamePaused.setAccessible(true); + } catch(Exception e) { + e.printStackTrace(); + } + } - if(requestScreenshot == 1) { - mc.addScheduledTask(new Runnable() { - @Override - public void run() { - ChatMessageRequests.addChatMessage("Saving Thumbnail...", ChatMessageRequests.ChatMessageType.INFORMATION); - ReplayScreenshot.prepareScreenshot(); - requestScreenshot = 2; - } - }); - } else if(requestScreenshot == 2) { - mc.addScheduledTask(new Runnable() { - @Override - public void run() { - ReplayScreenshot.saveScreenshot(); - } - }); - } + //private boolean f1Down = false; - if(ReplayHandler.isInPath()) ReplayProcess.unblockAndTick(false); - if(ReplayHandler.isCamera()) ReplayHandler.setCameraEntity(ReplayHandler.getCameraEntity()); - if(ReplayHandler.isInReplay() && ReplayHandler.isPaused()) { - if(mc != null && mc.thePlayer != null) - MinecraftTicker.runMouseKeyboardTick(mc); - } - if((mc.getRenderViewEntity() == mc.thePlayer || !mc.getRenderViewEntity().isEntityAlive()) - && ReplayHandler.getCameraEntity() != null && !ReplayHandler.isInPath()) { - ReplayHandler.spectateCamera(); - } else if(!ReplayHandler.isCamera()) { - lastX = mc.getRenderViewEntity().posX; - lastY = mc.getRenderViewEntity().posY; - lastZ = mc.getRenderViewEntity().posZ; - lastPitch = mc.getRenderViewEntity().rotationPitch; - lastYaw = mc.getRenderViewEntity().rotationYaw; - } + public static void requestScreenshot() { + if(requestScreenshot == 0) requestScreenshot = 1; + } - if(mc.isGamePaused() && ReplayHandler.isInPath()) { - isGamePaused.set(mc, false); - } - } - - //private boolean f1Down = false; + public static void finishScreenshot() { + requestScreenshot = 0; + } - private static int requestScreenshot = 0; + @SubscribeEvent + public void onRenderWorld(RenderWorldLastEvent event) throws + InvocationTargetException, IOException, IllegalAccessException, IllegalArgumentException { + if(!ReplayHandler.isInReplay()) return; //If not in Replay, cancel - public static void requestScreenshot() { - if(requestScreenshot == 0) requestScreenshot = 1; - } + if(requestScreenshot == 1) { + mc.addScheduledTask(new Runnable() { + @Override + public void run() { + ReplayMod.chatMessageHandler.addChatMessage("Saving Thumbnail...", ChatMessageHandler.ChatMessageType.INFORMATION); + ReplayScreenshot.prepareScreenshot(); + requestScreenshot = 2; + } + }); + } else if(requestScreenshot == 2) { + mc.addScheduledTask(new Runnable() { + @Override + public void run() { + ReplayScreenshot.saveScreenshot(); + } + }); + } - public static void finishScreenshot() { - requestScreenshot = 0; - } + if(ReplayHandler.isInPath()) ReplayProcess.unblockAndTick(false); + if(ReplayHandler.isCamera()) ReplayHandler.setCameraEntity(ReplayHandler.getCameraEntity()); + if(ReplayHandler.isInReplay() && ReplayMod.replaySender.paused()) { + if(mc != null && mc.thePlayer != null) + MinecraftTicker.runMouseKeyboardTick(mc); + } + if((mc.getRenderViewEntity() == mc.thePlayer || !mc.getRenderViewEntity().isEntityAlive()) + && ReplayHandler.getCameraEntity() != null && !ReplayHandler.isInPath()) { + ReplayHandler.spectateCamera(); + } + + if(mc.isGamePaused() && ReplayHandler.isInPath()) { + isGamePaused.set(mc, false); + } + } + + @SubscribeEvent + public void tick(TickEvent event) { + if(!ReplayHandler.isInReplay()) return; - @SubscribeEvent - public void tick(TickEvent event) { - if(!ReplayHandler.isInReplay()) return; - /* if(Keyboard.getEventKeyState() && Keyboard.isKeyDown(Keyboard.KEY_F1) && ReplayHandler.isInPath() && !ReplayProcess.isVideoRecording() @@ -111,52 +100,48 @@ public class TickAndRenderListener { f1Down = Keyboard.isKeyDown(Keyboard.KEY_F1) && Keyboard.getEventKeyState(); */ - - if(ReplayHandler.getCameraEntity() != null) - ReplayHandler.getCameraEntity().updateMovement(); - if(ReplayHandler.isInPath()) { - ReplayProcess.unblockAndTick(true); - if(ReplayProcess.isVideoRecording() && - !(mc.currentScreen instanceof GuiMouseInput || mc.currentScreen instanceof GuiCancelRender)) { - mc.displayGuiScreen(new GuiMouseInput()); - } - } - else onMouseMove(new MouseEvent()); - FMLCommonHandler.instance().bus().post(new InputEvent.KeyInputEvent()); - } - - @SubscribeEvent - public void onMouseMove(MouseEvent event) { - if(!ReplayHandler.isInReplay()) return; - boolean flag = Display.isActive(); - flag = true; - mc.mcProfiler.startSection("mouse"); + if(ReplayHandler.getCameraEntity() != null) + ReplayHandler.getCameraEntity().updateMovement(); + if(ReplayHandler.isInPath()) { + ReplayProcess.unblockAndTick(true); + if(ReplayProcess.isVideoRecording() && + !(mc.currentScreen instanceof GuiMouseInput || mc.currentScreen instanceof GuiCancelRender)) { + mc.displayGuiScreen(new GuiMouseInput()); + } + } else onMouseMove(new MouseEvent()); + FMLCommonHandler.instance().bus().post(new InputEvent.KeyInputEvent()); + } - if (flag && Minecraft.isRunningOnMac && mc.inGameHasFocus && !Mouse.isInsideWindow()) - { - Mouse.setGrabbed(false); - Mouse.setCursorPosition(Display.getWidth() / 2, Display.getHeight() / 2); - Mouse.setGrabbed(true); - } + @SubscribeEvent + public void onMouseMove(MouseEvent event) { + if(!ReplayHandler.isInReplay()) return; + boolean flag = Display.isActive(); + flag = true; - if (mc.inGameHasFocus && flag && !(ReplayHandler.isInPath())) - { - mc.mouseHelper.mouseXYChange(); - float f1 = mc.gameSettings.mouseSensitivity * 0.6F + 0.2F; - float f2 = f1 * f1 * f1 * 8.0F; - float f3 = (float)mc.mouseHelper.deltaX * f2; - float f4 = (float)mc.mouseHelper.deltaY * f2; - byte b0 = 1; + mc.mcProfiler.startSection("mouse"); - if (mc.gameSettings.invertMouse) - { - b0 = -1; - } + if(flag && Minecraft.isRunningOnMac && mc.inGameHasFocus && !Mouse.isInsideWindow()) { + Mouse.setGrabbed(false); + Mouse.setCursorPosition(Display.getWidth() / 2, Display.getHeight() / 2); + Mouse.setGrabbed(true); + } - if(ReplayHandler.getCameraEntity() != null) { - ReplayHandler.getCameraEntity().setAngles(f3, f4 * (float)b0); - } - } - } + if(mc.inGameHasFocus && flag && !(ReplayHandler.isInPath())) { + mc.mouseHelper.mouseXYChange(); + float f1 = mc.gameSettings.mouseSensitivity * 0.6F + 0.2F; + float f2 = f1 * f1 * f1 * 8.0F; + float f3 = (float) mc.mouseHelper.deltaX * f2; + float f4 = (float) mc.mouseHelper.deltaY * f2; + byte b0 = 1; + + if(mc.gameSettings.invertMouse) { + b0 = -1; + } + + if(ReplayHandler.getCameraEntity() != null) { + ReplayHandler.getCameraEntity().setAngles(f3, f4 * (float) b0); + } + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/GuiCancelRender.java b/src/main/java/eu/crushedpixel/replaymod/gui/GuiCancelRender.java index ac2b868f..ad9ae6c7 100644 --- a/src/main/java/eu/crushedpixel/replaymod/gui/GuiCancelRender.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/GuiCancelRender.java @@ -2,27 +2,26 @@ package eu.crushedpixel.replaymod.gui; import eu.crushedpixel.replaymod.replay.ReplayProcess; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiYesNo; import net.minecraft.client.gui.GuiYesNoCallback; public class GuiCancelRender extends GuiYesNo { - private static Minecraft mc = Minecraft.getMinecraft(); - - private static GuiYesNoCallback callback = new GuiYesNoCallback() { - - @Override - public void confirmClicked(boolean result, int id) { - if(result) { - ReplayProcess.stopReplayProcess(false); - } - mc.displayGuiScreen(null); - } - }; - - public GuiCancelRender() { - super(callback, "Cancel Rendering", "Are you sure that you want to cancel the current rendering process?", 0); - } + private static Minecraft mc = Minecraft.getMinecraft(); + + private static GuiYesNoCallback callback = new GuiYesNoCallback() { + + @Override + public void confirmClicked(boolean result, int id) { + if(result) { + ReplayProcess.stopReplayProcess(false); + } + mc.displayGuiScreen(null); + } + }; + + public GuiCancelRender() { + super(callback, "Cancel Rendering", "Are you sure that you want to cancel the current rendering process?", 0); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/GuiConstants.java b/src/main/java/eu/crushedpixel/replaymod/gui/GuiConstants.java index 5813efa2..f3623e9b 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/GuiConstants.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/GuiConstants.java @@ -2,47 +2,47 @@ package eu.crushedpixel.replaymod.gui; public class GuiConstants { - public static final int CENTER_MY_REPLAYS_BUTTON = 2001; - public static final int CENTER_SEARCH_BUTTON = 2002; - public static final int CENTER_BACK_BUTTON = 2003; - public static final int CENTER_LOGOUT_BUTTON = 2004; - public static final int CENTER_RECENT_BUTTON = 2005; - public static final int CENTER_BEST_BUTTON = 2006; - public static final int CENTER_MANAGER_BUTTON = 2007; - - public static final int UPLOAD_NAME_INPUT = 3001; - public static final int UPLOAD_CATEGORY_BUTTON = 3002; - public static final int UPLOAD_START_BUTTON = 3003; - public static final int UPLOAD_CANCEL_BUTTON = 3004; - public static final int UPLOAD_BACK_BUTTON = 3005; - public static final int UPLOAD_INFO_FIELD = 3006; - public static final int UPLOAD_TAG_INPUT = 3007; - public static final int UPLOAD_TAG_PLACEHOLDER = 3008; - - public static final int EXIT_REPLAY_BUTTON = 4001; - - public static final int REPLAY_OPTIONS_BUTTON_ID = 8000; - - public static final int REPLAY_MANAGER_BUTTON_ID = 9001; - public static final int REPLAY_EDITOR_BUTTON_ID = 9002; - public static final int REPLAY_CENTER_BUTTON_ID = 9003; - public static final int REPLAY_CENTER_LOGIN_TEXT_ID = 9004; - public static final int REPLAY_CENTER_PASSWORD_TEXT_ID = 9005; - - public static final int LOGIN_OKAY_BUTTON = 1100; - public static final int LOGIN_CANCEL_BUTTON = 1101; - - public static final int REPLAY_EDITOR_TRIM_TAB = 5000; - public static final int REPLAY_EDITOR_CONNECT_TAB = 5001; - public static final int REPLAY_EDITOR_MODIFY_TAB = 5002; - - public static final int REPLAY_EDITOR_SAVEMODE_BUTTON = 5003; - public static final int REPLAY_EDITOR_SAVE_BUTTON = 5004; - public static final int REPLAY_EDITOR_BACK_BUTTON = 5005; - - public static final int REPLAY_EDITOR_UP_BUTTON = 5006; - public static final int REPLAY_EDITOR_DOWN_BUTTON = 5007; - - public static final int REPLAY_EDITOR_REMOVE_BUTTON = 5008; - public static final int REPLAY_EDITOR_ADD_BUTTON = 5009; + public static final int CENTER_MY_REPLAYS_BUTTON = 2001; + public static final int CENTER_SEARCH_BUTTON = 2002; + public static final int CENTER_BACK_BUTTON = 2003; + public static final int CENTER_LOGOUT_BUTTON = 2004; + public static final int CENTER_RECENT_BUTTON = 2005; + public static final int CENTER_BEST_BUTTON = 2006; + public static final int CENTER_MANAGER_BUTTON = 2007; + + public static final int UPLOAD_NAME_INPUT = 3001; + public static final int UPLOAD_CATEGORY_BUTTON = 3002; + public static final int UPLOAD_START_BUTTON = 3003; + public static final int UPLOAD_CANCEL_BUTTON = 3004; + public static final int UPLOAD_BACK_BUTTON = 3005; + public static final int UPLOAD_INFO_FIELD = 3006; + public static final int UPLOAD_TAG_INPUT = 3007; + public static final int UPLOAD_TAG_PLACEHOLDER = 3008; + + public static final int EXIT_REPLAY_BUTTON = 4001; + + public static final int REPLAY_OPTIONS_BUTTON_ID = 8000; + + public static final int REPLAY_MANAGER_BUTTON_ID = 9001; + public static final int REPLAY_EDITOR_BUTTON_ID = 9002; + public static final int REPLAY_CENTER_BUTTON_ID = 9003; + public static final int REPLAY_CENTER_LOGIN_TEXT_ID = 9004; + public static final int REPLAY_CENTER_PASSWORD_TEXT_ID = 9005; + + public static final int LOGIN_OKAY_BUTTON = 1100; + public static final int LOGIN_CANCEL_BUTTON = 1101; + + public static final int REPLAY_EDITOR_TRIM_TAB = 5000; + public static final int REPLAY_EDITOR_CONNECT_TAB = 5001; + public static final int REPLAY_EDITOR_MODIFY_TAB = 5002; + + public static final int REPLAY_EDITOR_SAVEMODE_BUTTON = 5003; + public static final int REPLAY_EDITOR_SAVE_BUTTON = 5004; + public static final int REPLAY_EDITOR_BACK_BUTTON = 5005; + + public static final int REPLAY_EDITOR_UP_BUTTON = 5006; + public static final int REPLAY_EDITOR_DOWN_BUTTON = 5007; + + public static final int REPLAY_EDITOR_REMOVE_BUTTON = 5008; + public static final int REPLAY_EDITOR_ADD_BUTTON = 5009; } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/GuiMouseInput.java b/src/main/java/eu/crushedpixel/replaymod/gui/GuiMouseInput.java new file mode 100755 index 00000000..98a52ffc --- /dev/null +++ b/src/main/java/eu/crushedpixel/replaymod/gui/GuiMouseInput.java @@ -0,0 +1,7 @@ +package eu.crushedpixel.replaymod.gui; + +import net.minecraft.client.gui.GuiScreen; + +public class GuiMouseInput extends GuiScreen { + +} diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/GuiReplaySaving.java b/src/main/java/eu/crushedpixel/replaymod/gui/GuiReplaySaving.java index 08b96139..2eb79f47 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/GuiReplaySaving.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/GuiReplaySaving.java @@ -1,33 +1,27 @@ package eu.crushedpixel.replaymod.gui; -import java.awt.Color; - -import eu.crushedpixel.replaymod.gui.replayviewer.GuiReplayViewer; -import eu.crushedpixel.replaymod.recording.ConnectionEventHandler; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiIngameMenu; import net.minecraft.client.gui.GuiScreen; -import net.minecraftforge.fml.client.FMLClientHandler; public class GuiReplaySaving extends GuiScreen { - - public static boolean replaySaving = false; - - private GuiScreen waiting = null; - - public GuiReplaySaving(GuiScreen waiting) { - this.waiting = waiting; - } - - @Override - public void drawScreen(int mouseX, int mouseY, float partialTicks) { - this.drawDefaultBackground(); - this.drawCenteredString(this.fontRendererObj, "Saving Replay File...", this.width / 2, 20, 16777215); - this.drawCenteredString(this.fontRendererObj, "Please wait while your recent Replay is being saved.", this.width / 2, 40, 16777215); - super.drawScreen(mouseX, mouseY, partialTicks); - if(!replaySaving) { - Minecraft.getMinecraft().displayGuiScreen(waiting); - } - } - + + public static boolean replaySaving = false; + + private GuiScreen waiting = null; + + public GuiReplaySaving(GuiScreen waiting) { + this.waiting = waiting; + } + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + this.drawDefaultBackground(); + this.drawCenteredString(this.fontRendererObj, "Saving Replay File...", this.width / 2, 20, 16777215); + this.drawCenteredString(this.fontRendererObj, "Please wait while your recent Replay is being saved.", this.width / 2, 40, 16777215); + super.drawScreen(mouseX, mouseY, partialTicks); + if(!replaySaving) { + Minecraft.getMinecraft().displayGuiScreen(waiting); + } + } + } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/GuiReplaySettings.java b/src/main/java/eu/crushedpixel/replaymod/gui/GuiReplaySettings.java index b8b21c1f..9dbb59c0 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/GuiReplaySettings.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/GuiReplaySettings.java @@ -1,192 +1,188 @@ package eu.crushedpixel.replaymod.gui; -import java.awt.Color; -import java.io.IOException; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.resources.I18n; -import net.minecraftforge.fml.client.FMLClientHandler; import eu.crushedpixel.replaymod.ReplayMod; import eu.crushedpixel.replaymod.settings.ReplaySettings; import eu.crushedpixel.replaymod.settings.ReplaySettings.RecordingOptions; import eu.crushedpixel.replaymod.settings.ReplaySettings.RenderOptions; import eu.crushedpixel.replaymod.settings.ReplaySettings.ReplayOptions; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.resources.I18n; +import net.minecraftforge.fml.client.FMLClientHandler; + +import java.awt.*; +import java.io.IOException; public class GuiReplaySettings extends GuiScreen { - private GuiScreen parentGuiScreen; - protected String screenTitle = "Replay Mod Settings"; + //TODO: Move to GuiConstants + private static final int QUALITY_SLIDER_ID = 9003; + private static final int RECORDSERVER_ID = 9004; + private static final int RECORDSP_ID = 9005; + private static final int SEND_CHAT = 9006; + private static final int FORCE_LINEAR = 9007; + private static final int ENABLE_LIGHTING = 9008; + private static final int FRAMERATE_SLIDER_ID = 9009; + private static final int RESOURCEPACK_ID = 9010; + private static final int WAITFORCHUNKS_ID = 9011; + private static final int INDICATOR_ID = 9012; + protected String screenTitle = "Replay Mod Settings"; + private GuiScreen parentGuiScreen; + private GuiButton recordServerButton, recordSPButton, sendChatButton, linearButton, lightingButton, + resourcePackButton, waitForChunksButton, showIndicatorButton; - //TODO: Move to GuiConstants - private static final int QUALITY_SLIDER_ID = 9003; - private static final int RECORDSERVER_ID = 9004; - private static final int RECORDSP_ID = 9005; - private static final int SEND_CHAT = 9006; - private static final int FORCE_LINEAR = 9007; - private static final int ENABLE_LIGHTING = 9008; - private static final int FRAMERATE_SLIDER_ID = 9009; - private static final int RESOURCEPACK_ID = 9010; - private static final int WAITFORCHUNKS_ID = 9011; - private static final int INDICATOR_ID = 9012; + public GuiReplaySettings(GuiScreen parentGuiScreen) { + this.parentGuiScreen = parentGuiScreen; + } - private GuiButton recordServerButton, recordSPButton, sendChatButton, linearButton, lightingButton, - resourcePackButton, waitForChunksButton, showIndicatorButton; + public void initGui() { + this.screenTitle = I18n.format("Replay Mod Settings", new Object[0]); + this.buttonList.clear(); + this.buttonList.add(new GuiButton(200, this.width / 2 - 100, this.height - 27, I18n.format("gui.done", new Object[0]))); - public GuiReplaySettings(GuiScreen parentGuiScreen) { - this.parentGuiScreen = parentGuiScreen; - } + ReplaySettings settings = ReplayMod.replaySettings; - public void initGui() { - this.screenTitle = I18n.format("Replay Mod Settings", new Object[0]); - this.buttonList.clear(); - this.buttonList.add(new GuiButton(200, this.width / 2 - 100, this.height - 27, I18n.format("gui.done", new Object[0]))); + int k = 0; + int i = 0; - ReplaySettings settings = ReplayMod.replaySettings; + for(RecordingOptions o : RecordingOptions.values()) { + if(o == RecordingOptions.notifications) { + this.buttonList.add(sendChatButton = new GuiButton(SEND_CHAT, + this.width / 2 - 155 + i % 2 * 160, this.height / 6 + 24 * (i >> 1), 150, 20, + "Enable Notifications: " + onOff(settings.isShowNotifications()))); + } else if(o == RecordingOptions.recordServer) { + this.buttonList.add(recordServerButton = new GuiButton(RECORDSERVER_ID, + this.width / 2 - 155 + i % 2 * 160, this.height / 6 + 24 * (i >> 1), 150, 20, "Record Server: " + + onOff(settings.isEnableRecordingServer()))); + } else if(o == RecordingOptions.recordSingleplayer) { + this.buttonList.add(recordSPButton = new GuiButton(RECORDSP_ID, this.width / 2 - 155 + i % 2 * 160, + this.height / 6 + 24 * (i >> 1), 150, 20, "Record Singleplayer: " + onOff(settings.isEnableRecordingSingleplayer()))); + } else if(o == RecordingOptions.indicator) { + this.buttonList.add(showIndicatorButton = new GuiButton(INDICATOR_ID, this.width / 2 - 155 + i % 2 * 160, + this.height / 6 + 24 * (i >> 1), 150, 20, "Show Recording Indicator: " + onOff(settings.showRecordingIndicator()))); + } - int k = 0; - int i = 0; - - for(RecordingOptions o : RecordingOptions.values()) { - if(o == RecordingOptions.notifications) { - this.buttonList.add(sendChatButton = new GuiButton(SEND_CHAT, - this.width / 2 - 155 + i % 2 * 160, this.height / 6 + 24 * (i >> 1), 150, 20, - "Enable Notifications: "+onOff(settings.isShowNotifications()))); - } else if(o == RecordingOptions.recordServer) { - this.buttonList.add(recordServerButton = new GuiButton(RECORDSERVER_ID, - this.width / 2 - 155 + i % 2 * 160, this.height / 6 + 24 * (i >> 1), 150, 20, "Record Server: " - +onOff(settings.isEnableRecordingServer()))); - } else if(o == RecordingOptions.recordSingleplayer) { - this.buttonList.add(recordSPButton = new GuiButton(RECORDSP_ID, this.width / 2 - 155 + i % 2 * 160, - this.height / 6 + 24 * (i >> 1), 150, 20, "Record Singleplayer: "+onOff(settings.isEnableRecordingSingleplayer()))); - } else if(o == RecordingOptions.indicator) { - this.buttonList.add(showIndicatorButton = new GuiButton(INDICATOR_ID, this.width / 2 - 155 + i % 2 * 160, - this.height / 6 + 24 * (i >> 1), 150, 20, "Show Recording Indicator: "+onOff(settings.showRecordingIndicator()))); - } - - ++i; - ++k; - } - - - if (i % 2 == 1) - { - ++i; - } - - for(ReplayOptions o : ReplayOptions.values()) { - if(o == ReplayOptions.lighting) { - this.buttonList.add(lightingButton = new GuiButton(ENABLE_LIGHTING, this.width / 2 - 155 + i % 2 * 160, - this.height / 6 + 24 * (i >> 1), 150, 20, "Enable Lighting: "+onOff(settings.isLightingEnabled()))); - } else if(o == ReplayOptions.linear) { - this.buttonList.add(linearButton = new GuiButton(FORCE_LINEAR, this.width / 2 - 155 + i % 2 * 160, - this.height / 6 + 24 * (i >> 1), 150, 20, "Camera Path: "+linearOnOff(settings.isLinearMovement()))); - } else if(o == ReplayOptions.useResources) { - this.buttonList.add(resourcePackButton = new GuiButton(RESOURCEPACK_ID, this.width / 2 - 155 + i % 2 * 160, - this.height / 6 + 24 * (i >> 1), 150, 20, "Server Resource Packs: "+onOff(settings.getUseResourcePacks()))); - } - - ++i; - ++k; - } - - if (i % 2 == 1) - { - ++i; - } - - for(RenderOptions o : RenderOptions.values()) { - if(o == RenderOptions.videoFramerate) { - this.buttonList.add(new GuiVideoFramerateSlider(FRAMERATE_SLIDER_ID, - this.width / 2 - 155 + i % 2 * 160, this.height / 6 + 24 * (i >> 1), settings.getVideoFramerate(), "Video Framerate")); - } else if(o == RenderOptions.videoQuality) { - this.buttonList.add(new GuiVideoQualitySlider(QUALITY_SLIDER_ID, - this.width / 2 - 155 + i % 2 * 160, this.height / 6 + 24 * (i >> 1), (float)settings.getVideoQuality(), "Video Quality")); - } else if(o == RenderOptions.waitForChunks) { - this.buttonList.add(resourcePackButton = new GuiButton(WAITFORCHUNKS_ID, this.width / 2 - 155 + i % 2 * 160, - this.height / 6 + 24 * (i >> 1), 150, 20, "Force Render Chunks: "+onOff(settings.getWaitForChunks()))); - } - - ++i; - ++k; - } - } - - private String onOff(boolean on) { - return on ? "ON" : "OFF"; - } - - private String linearOnOff(boolean on) { - return on ? "Linear" : "Cubic"; - } - - @Override - public void drawScreen(int mouseX, int mouseY, float partialTicks) { - this.drawDefaultBackground(); - this.drawCenteredString(this.fontRendererObj, "Replay Mod Settings", this.width / 2, 20, 16777215); - if (FMLClientHandler.instance().getClient().thePlayer != null) { - this.drawCenteredString(this.fontRendererObj, "WARNING: Recording settings are going to be", this.width / 2, 180, Color.RED.getRGB()); - this.drawCenteredString(this.fontRendererObj, "applied the next time you join a world.", this.width / 2, 190, Color.RED.getRGB()); - } - super.drawScreen(mouseX, mouseY, partialTicks); - } + ++i; + ++k; + } - protected void actionPerformed(GuiButton button) throws IOException { - if (button.enabled) { - switch(button.id) { - case 200: - this.mc.displayGuiScreen(this.parentGuiScreen); - break; - case RECORDSERVER_ID: - boolean enabled = ReplayMod.replaySettings.isEnableRecordingServer(); - enabled = !enabled; - recordServerButton.displayString = "Record Server: "+onOff(enabled); - ReplayMod.replaySettings.setEnableRecordingServer(enabled); - break; - case RECORDSP_ID: - enabled = ReplayMod.replaySettings.isEnableRecordingSingleplayer(); - enabled = !enabled; - recordSPButton.displayString = "Record Singleplayer: "+onOff(enabled); - ReplayMod.replaySettings.setEnableRecordingSingleplayer(enabled); - break; - case SEND_CHAT: - enabled = ReplayMod.replaySettings.isShowNotifications(); - enabled = !enabled; - sendChatButton.displayString = "Enable Notifications: "+onOff(enabled); - ReplayMod.replaySettings.setShowNotifications(enabled); - break; - case FORCE_LINEAR: - enabled = ReplayMod.replaySettings.isLinearMovement(); - enabled = !enabled; - linearButton.displayString = "Camera Path: "+linearOnOff(enabled); - ReplayMod.replaySettings.setLinearMovement(enabled); - break; - case ENABLE_LIGHTING: - enabled = ReplayMod.replaySettings.isLightingEnabled(); - enabled = !enabled; - lightingButton.displayString = "Enable Lighting: "+onOff(enabled); - ReplayMod.replaySettings.setLightingEnabled(enabled); - break; - case RESOURCEPACK_ID: - enabled = ReplayMod.replaySettings.getUseResourcePacks(); - enabled = !enabled; - resourcePackButton.displayString = "Server Resource Packs: "+onOff(enabled); - ReplayMod.replaySettings.setUseResourcePacks(enabled); - break; - case WAITFORCHUNKS_ID: - enabled = ReplayMod.replaySettings.getWaitForChunks(); - enabled = !enabled; - resourcePackButton.displayString = "Force Render Chunks: "+onOff(enabled); - ReplayMod.replaySettings.setWaitForChunks(enabled); - break; - case INDICATOR_ID: - enabled = ReplayMod.replaySettings.showRecordingIndicator(); - enabled = !enabled; - showIndicatorButton.displayString = "Show Recording Indicator: "+onOff(enabled); - ReplayMod.replaySettings.setEnableIndicator(enabled); - break; - } - } - } + if(i % 2 == 1) { + ++i; + } + + for(ReplayOptions o : ReplayOptions.values()) { + if(o == ReplayOptions.lighting) { + this.buttonList.add(lightingButton = new GuiButton(ENABLE_LIGHTING, this.width / 2 - 155 + i % 2 * 160, + this.height / 6 + 24 * (i >> 1), 150, 20, "Enable Lighting: " + onOff(settings.isLightingEnabled()))); + } else if(o == ReplayOptions.linear) { + this.buttonList.add(linearButton = new GuiButton(FORCE_LINEAR, this.width / 2 - 155 + i % 2 * 160, + this.height / 6 + 24 * (i >> 1), 150, 20, "Camera Path: " + linearOnOff(settings.isLinearMovement()))); + } else if(o == ReplayOptions.useResources) { + this.buttonList.add(resourcePackButton = new GuiButton(RESOURCEPACK_ID, this.width / 2 - 155 + i % 2 * 160, + this.height / 6 + 24 * (i >> 1), 150, 20, "Server Resource Packs: " + onOff(settings.getUseResourcePacks()))); + } + + ++i; + ++k; + } + + if(i % 2 == 1) { + ++i; + } + + for(RenderOptions o : RenderOptions.values()) { + if(o == RenderOptions.videoFramerate) { + this.buttonList.add(new GuiVideoFramerateSlider(FRAMERATE_SLIDER_ID, + this.width / 2 - 155 + i % 2 * 160, this.height / 6 + 24 * (i >> 1), settings.getVideoFramerate(), "Video Framerate")); + } else if(o == RenderOptions.videoQuality) { + this.buttonList.add(new GuiVideoQualitySlider(QUALITY_SLIDER_ID, + this.width / 2 - 155 + i % 2 * 160, this.height / 6 + 24 * (i >> 1), (float) settings.getVideoQuality(), "Video Quality")); + } else if(o == RenderOptions.waitForChunks) { + this.buttonList.add(resourcePackButton = new GuiButton(WAITFORCHUNKS_ID, this.width / 2 - 155 + i % 2 * 160, + this.height / 6 + 24 * (i >> 1), 150, 20, "Force Render Chunks: " + onOff(settings.getWaitForChunks()))); + } + + ++i; + ++k; + } + } + + private String onOff(boolean on) { + return on ? "ON" : "OFF"; + } + + private String linearOnOff(boolean on) { + return on ? "Linear" : "Cubic"; + } + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + this.drawDefaultBackground(); + this.drawCenteredString(this.fontRendererObj, "Replay Mod Settings", this.width / 2, 20, 16777215); + if(FMLClientHandler.instance().getClient().thePlayer != null) { + this.drawCenteredString(this.fontRendererObj, "WARNING: Recording settings are going to be", this.width / 2, 180, Color.RED.getRGB()); + this.drawCenteredString(this.fontRendererObj, "applied the next time you join a world.", this.width / 2, 190, Color.RED.getRGB()); + } + super.drawScreen(mouseX, mouseY, partialTicks); + } + + + protected void actionPerformed(GuiButton button) throws IOException { + if(button.enabled) { + switch(button.id) { + case 200: + this.mc.displayGuiScreen(this.parentGuiScreen); + break; + case RECORDSERVER_ID: + boolean enabled = ReplayMod.replaySettings.isEnableRecordingServer(); + enabled = !enabled; + recordServerButton.displayString = "Record Server: " + onOff(enabled); + ReplayMod.replaySettings.setEnableRecordingServer(enabled); + break; + case RECORDSP_ID: + enabled = ReplayMod.replaySettings.isEnableRecordingSingleplayer(); + enabled = !enabled; + recordSPButton.displayString = "Record Singleplayer: " + onOff(enabled); + ReplayMod.replaySettings.setEnableRecordingSingleplayer(enabled); + break; + case SEND_CHAT: + enabled = ReplayMod.replaySettings.isShowNotifications(); + enabled = !enabled; + sendChatButton.displayString = "Enable Notifications: " + onOff(enabled); + ReplayMod.replaySettings.setShowNotifications(enabled); + break; + case FORCE_LINEAR: + enabled = ReplayMod.replaySettings.isLinearMovement(); + enabled = !enabled; + linearButton.displayString = "Camera Path: " + linearOnOff(enabled); + ReplayMod.replaySettings.setLinearMovement(enabled); + break; + case ENABLE_LIGHTING: + enabled = ReplayMod.replaySettings.isLightingEnabled(); + enabled = !enabled; + lightingButton.displayString = "Enable Lighting: " + onOff(enabled); + ReplayMod.replaySettings.setLightingEnabled(enabled); + break; + case RESOURCEPACK_ID: + enabled = ReplayMod.replaySettings.getUseResourcePacks(); + enabled = !enabled; + resourcePackButton.displayString = "Server Resource Packs: " + onOff(enabled); + ReplayMod.replaySettings.setUseResourcePacks(enabled); + break; + case WAITFORCHUNKS_ID: + enabled = ReplayMod.replaySettings.getWaitForChunks(); + enabled = !enabled; + resourcePackButton.displayString = "Force Render Chunks: " + onOff(enabled); + ReplayMod.replaySettings.setWaitForChunks(enabled); + break; + case INDICATOR_ID: + enabled = ReplayMod.replaySettings.showRecordingIndicator(); + enabled = !enabled; + showIndicatorButton.displayString = "Show Recording Indicator: " + onOff(enabled); + ReplayMod.replaySettings.setEnableIndicator(enabled); + break; + } + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/GuiReplaySpeedSlider.java b/src/main/java/eu/crushedpixel/replaymod/gui/GuiReplaySpeedSlider.java index 0134af5a..13915232 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/GuiReplaySpeedSlider.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/GuiReplaySpeedSlider.java @@ -1,190 +1,170 @@ package eu.crushedpixel.replaymod.gui; import eu.crushedpixel.replaymod.ReplayMod; -import eu.crushedpixel.replaymod.gui.elements.GuiMouseInput; -import eu.crushedpixel.replaymod.replay.ReplayHandler; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.settings.GameSettings; import net.minecraft.util.MathHelper; import net.minecraftforge.fml.client.FMLClientHandler; public class GuiReplaySpeedSlider extends GuiButton { - private float sliderValue; + private float sliderValue; - private float valueStep, valueMin, valueMax; - private String displayKey; - private boolean dragging = false; + private float valueStep, valueMin, valueMax; + private String displayKey; + private boolean dragging = false; - public GuiReplaySpeedSlider(int buttonId, int p_i45017_2_, int p_i45017_3_, String displayKey) - { - super(buttonId, p_i45017_2_, p_i45017_3_, 150, 20, ""); - sliderValue = (9f/38f); + public GuiReplaySpeedSlider(int buttonId, int p_i45017_2_, int p_i45017_3_, String displayKey) { + super(buttonId, p_i45017_2_, p_i45017_3_, 150, 20, ""); + sliderValue = (9f / 38f); - this.width = 100; - this.valueMin = 1; - this.valueMax = 38; - this.valueStep = 1; - this.displayString = displayKey+": 1x"; - this.displayKey = displayKey; + this.width = 100; + this.valueMin = 1; + this.valueMax = 38; + this.valueStep = 1; + this.displayString = displayKey + ": 1x"; + this.displayKey = displayKey; - Minecraft.getMinecraft().getTextureManager().bindTexture(buttonTextures); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - this.drawTexturedModalRect(this.xPosition + (int)(sliderValue * (float)(this.width - 8)), this.yPosition, 0, 66, 4, 20); - this.drawTexturedModalRect(this.xPosition + (int)(sliderValue * (float)(this.width - 8)) + 4, this.yPosition, 196, 66, 4, 20); - } + Minecraft.getMinecraft().getTextureManager().bindTexture(buttonTextures); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.drawTexturedModalRect(this.xPosition + (int) (sliderValue * (float) (this.width - 8)), this.yPosition, 0, 66, 4, 20); + this.drawTexturedModalRect(this.xPosition + (int) (sliderValue * (float) (this.width - 8)) + 4, this.yPosition, 196, 66, 4, 20); + } - @Override - protected int getHoverState(boolean mouseOver) { - return 0; - } + public static float convertScaleRet(float value) { + if(value <= 1) { + return Math.round(value * 10); + } + float steps = value - 1; + return Math.round(steps / 0.25f); + } - @Override - public void drawButton(Minecraft mc, int mouseX, int mouseY) - { - if (this.visible) - { - try { - FontRenderer fontrenderer = mc.fontRendererObj; - mc.getTextureManager().bindTexture(buttonTextures); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - this.hovered = mouseX >= this.xPosition && mouseY >= this.yPosition && mouseX < this.xPosition + this.width && mouseY < this.yPosition + this.height; - int k = this.getHoverState(this.hovered); - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); - GlStateManager.blendFunc(770, 771); - this.drawTexturedModalRect(this.xPosition, this.yPosition, 0, 46 + k * 20, this.width / 2, this.height); - this.drawTexturedModalRect(this.xPosition + this.width / 2, this.yPosition, 200 - this.width / 2, 46 + k * 20, this.width / 2, this.height); - this.mouseDragged(mc, mouseX, mouseY); - int l = 14737632; + public static float convertScale(float value) { + if(value == 10) { + return 1; + } + if(value <= 9) { + return value / 10f; + } + return 1 + (0.25f * (value - 10)); + } - if (packedFGColour != 0) - { - l = packedFGColour; - } - else if (!this.enabled) - { - l = 10526880; - } - else if (this.hovered && FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) - { - l = 16777120; - } + @Override + protected int getHoverState(boolean mouseOver) { + return 0; + } - this.drawCenteredString(fontrenderer, this.displayString, this.xPosition + this.width / 2, this.yPosition + (this.height - 8) / 2, l); - } catch(Exception e) {} - } - } + @Override + public void drawButton(Minecraft mc, int mouseX, int mouseY) { + if(this.visible) { + try { + FontRenderer fontrenderer = mc.fontRendererObj; + mc.getTextureManager().bindTexture(buttonTextures); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.hovered = mouseX >= this.xPosition && mouseY >= this.yPosition && mouseX < this.xPosition + this.width && mouseY < this.yPosition + this.height; + int k = this.getHoverState(this.hovered); + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); + GlStateManager.blendFunc(770, 771); + this.drawTexturedModalRect(this.xPosition, this.yPosition, 0, 46 + k * 20, this.width / 2, this.height); + this.drawTexturedModalRect(this.xPosition + this.width / 2, this.yPosition, 200 - this.width / 2, 46 + k * 20, this.width / 2, this.height); + this.mouseDragged(mc, mouseX, mouseY); + int l = 14737632; - private String translate(float f) { - return f+"x"; - } + if(packedFGColour != 0) { + l = packedFGColour; + } else if(!this.enabled) { + l = 10526880; + } else if(this.hovered && FMLClientHandler.instance().isGUIOpen(GuiMouseInput.class)) { + l = 16777120; + } - public static float convertScaleRet(float value) { - if(value <= 1) { - return Math.round(value*10); - } - float steps = value-1; - return Math.round(steps/0.25f); - } + this.drawCenteredString(fontrenderer, this.displayString, this.xPosition + this.width / 2, this.yPosition + (this.height - 8) / 2, l); + } catch(Exception e) { + } + } + } - public static float convertScale(float value) { - if(value == 10) { - return 1; - } - if(value <= 9) { - return value/10f; - } - return 1+(0.25f*(value-10)); - } + private String translate(float f) { + return f + "x"; + } + public double getSliderValue() { + return convertScale(normalizedToReal(sliderValue)); + } - public double getSliderValue() { - return convertScale(normalizedToReal(sliderValue)); - } + @Override + protected void mouseDragged(Minecraft mc, int mouseX, int mouseY) { + if(this.visible) { + try { + if(this.dragging) { + sliderValue = (float) (mouseX - (this.xPosition + 4)) / (float) (this.width - 8); + sliderValue = MathHelper.clamp_float(sliderValue, 0.0F, 1.0F); + float f = denormalizeValue(sliderValue); + sliderValue = normalizeValue(f); + if(ReplayMod.replaySender.getReplaySpeed() != 0) { + ReplayMod.replaySender.setReplaySpeed(convertScale(normalizedToReal(sliderValue))); + } + this.displayString = displayKey + ": " + translate(convertScale(normalizedToReal(sliderValue))); + } - @Override - protected void mouseDragged(Minecraft mc, int mouseX, int mouseY) { - if (this.visible) { - try { - if(this.dragging) { - sliderValue = (float)(mouseX - (this.xPosition + 4)) / (float)(this.width - 8); - sliderValue = MathHelper.clamp_float(sliderValue, 0.0F, 1.0F); - float f = denormalizeValue(sliderValue); - sliderValue = normalizeValue(f); - if(ReplayHandler.getSpeed() != 0) { - ReplayHandler.setSpeed(convertScale(normalizedToReal(sliderValue))); - } - this.displayString = displayKey+": "+translate(convertScale(normalizedToReal(sliderValue))); - } + mc.getTextureManager().bindTexture(buttonTextures); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.drawTexturedModalRect(this.xPosition + (int) (sliderValue * (float) (this.width - 8)), this.yPosition, 0, 66, 4, 20); + this.drawTexturedModalRect(this.xPosition + (int) (sliderValue * (float) (this.width - 8)) + 4, this.yPosition, 196, 66, 4, 20); + } catch(Exception e) { + } + } + } - mc.getTextureManager().bindTexture(buttonTextures); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - this.drawTexturedModalRect(this.xPosition + (int)(sliderValue * (float)(this.width - 8)), this.yPosition, 0, 66, 4, 20); - this.drawTexturedModalRect(this.xPosition + (int)(sliderValue * (float)(this.width - 8)) + 4, this.yPosition, 196, 66, 4, 20); - } catch(Exception e) {} - } - } + public float normalizeValue(float p_148266_1_) { + return MathHelper.clamp_float((this.snapToStepClamp(p_148266_1_) - this.valueMin) / (this.valueMax - this.valueMin), 0.0F, 1.0F); + } - public float normalizeValue(float p_148266_1_) - { - return MathHelper.clamp_float((this.snapToStepClamp(p_148266_1_) - this.valueMin) / (this.valueMax - this.valueMin), 0.0F, 1.0F); - } + public float realToNormalized(float value) { + float min = 0 - valueMin; + float max = valueMax + min; - public float realToNormalized(float value) { - float min = 0 - valueMin; - float max = valueMax + min; + return value / (max) - min; + } - return value/(max) - min; - } + public float denormalizeValue(float p_148262_1_) { + return this.snapToStepClamp(this.valueMin + (this.valueMax - this.valueMin) * MathHelper.clamp_float(p_148262_1_, 0.0F, 1.0F)); + } - public float denormalizeValue(float p_148262_1_) - { - return this.snapToStepClamp(this.valueMin + (this.valueMax - this.valueMin) * MathHelper.clamp_float(p_148262_1_, 0.0F, 1.0F)); - } + public float snapToStepClamp(float p_148268_1_) { + p_148268_1_ = this.snapToStep(p_148268_1_); + return MathHelper.clamp_float(p_148268_1_, this.valueMin, this.valueMax); + } - public float snapToStepClamp(float p_148268_1_) - { - p_148268_1_ = this.snapToStep(p_148268_1_); - return MathHelper.clamp_float(p_148268_1_, this.valueMin, this.valueMax); - } + protected float snapToStep(float p_148264_1_) { + if(this.valueStep > 0.0F) { + p_148264_1_ = this.valueStep * (float) Math.round(p_148264_1_ / this.valueStep); + } - protected float snapToStep(float p_148264_1_) - { - if (this.valueStep > 0.0F) - { - p_148264_1_ = this.valueStep * (float)Math.round(p_148264_1_ / this.valueStep); - } + return p_148264_1_; + } - return p_148264_1_; - } + public float normalizedToReal(float value) { + float min = 0 - valueMin; + float max = valueMax + min; - public float normalizedToReal(float value) { - float min = 0 - valueMin; - float max = valueMax + min; + return Math.round(value * (max) - min); + } - return Math.round(value*(max) - min); - } + public boolean mousePressed(Minecraft mc, int mouseX, int mouseY) { + if(super.mousePressed(mc, mouseX, mouseY)) { + this.dragging = true; + return true; + } else { + return false; + } + } - public boolean mousePressed(Minecraft mc, int mouseX, int mouseY) - { - if (super.mousePressed(mc, mouseX, mouseY)) - { - this.dragging = true; - return true; - } - else - { - return false; - } - } - - public void mouseReleased(int mouseX, int mouseY) - { - this.dragging = false; - } + public void mouseReleased(int mouseX, int mouseY) { + this.dragging = false; + } } \ No newline at end of file diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/GuiSpectateSelection.java b/src/main/java/eu/crushedpixel/replaymod/gui/GuiSpectateSelection.java index c74bf388..7c73eaf6 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/GuiSpectateSelection.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/GuiSpectateSelection.java @@ -1,14 +1,8 @@ package eu.crushedpixel.replaymod.gui; -import java.awt.Color; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import org.lwjgl.input.Mouse; - +import com.mojang.realmsclient.util.Pair; +import eu.crushedpixel.replaymod.ReplayMod; +import eu.crushedpixel.replaymod.replay.ReplayHandler; import net.minecraft.client.entity.AbstractClientPlayer; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiScreen; @@ -17,199 +11,200 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EnumPlayerModelParts; import net.minecraft.potion.Potion; import net.minecraft.util.ResourceLocation; +import org.lwjgl.input.Mouse; -import com.mojang.realmsclient.util.Pair; - -import eu.crushedpixel.replaymod.replay.ReplayHandler; +import java.awt.*; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; public class GuiSpectateSelection extends GuiScreen { - private List> players; - private int playerCount; - private int upperPlayer = 0; + private List> players; + private int playerCount; + private int upperPlayer = 0; - private int upperBound = 30; - private int lowerBound; - - private double prevSpeed; + private int upperBound = 30; + private int lowerBound; - private class PlayerComparator implements Comparator { + private double prevSpeed; + private boolean drag = false; + private int lastY = 0; + private int fitting = 0; - @Override - public int compare(EntityPlayer o1, EntityPlayer o2) { - if(isSpectator(o1) && !isSpectator(o2)) { - return 1; - } else if(isSpectator(o2) && !isSpectator(o1)) { - return -1; - } else { - return o1.getName().compareToIgnoreCase(o2.getName()); - } - } - - } - - private boolean isSpectator(EntityPlayer e) { - return e.isInvisible() && e.getActivePotionEffect(Potion.invisibility) == null; - } - - public GuiSpectateSelection(List players) { - this.prevSpeed = ReplayHandler.getSpeed(); - - Collections.sort(players, new PlayerComparator()); - - this.players = new ArrayList>(); + public GuiSpectateSelection(List players) { + this.prevSpeed = ReplayMod.replaySender.getReplaySpeed(); - for(EntityPlayer p : players) { - ResourceLocation loc = new ResourceLocation("/temp-skins/"+p.getGameProfile().getName()); - AbstractClientPlayer.getDownloadImageSkin(loc, p.getName()); - this.players.add(Pair.of(p, loc)); - } + Collections.sort(players, new PlayerComparator()); - playerCount = players.size(); - - ReplayHandler.setSpeed(0); - } + this.players = new ArrayList>(); - private boolean drag = false; + for(EntityPlayer p : players) { + ResourceLocation loc = new ResourceLocation("/temp-skins/" + p.getGameProfile().getName()); + AbstractClientPlayer.getDownloadImageSkin(loc, p.getName()); + this.players.add(Pair.of(p, loc)); + } - @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseButton) - throws IOException { + playerCount = players.size(); - if(fitting < playerCount) { - float visiblePerc = (float)fitting/(float)playerCount; + ReplayMod.replaySender.setReplaySpeed(0); + } - int h = this.height-32-32; - int offset = Math.round((upperPlayer/(fitting))*visiblePerc*h); + private boolean isSpectator(EntityPlayer e) { + return e.isInvisible() && e.getActivePotionEffect(Potion.invisibility) == null; + } - int lower = Math.round(32+offset+(h*visiblePerc))-2; + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseButton) + throws IOException { - int k2 = (int)(this.width*0.4); + if(fitting < playerCount) { + float visiblePerc = (float) fitting / (float) playerCount; - if(mouseX >= k2-16 && mouseX <= k2-12 && mouseY >= 32-2+offset && mouseY <= lower) { - lastY = mouseY; - drag = true; - return; - } - } - int k2 = (int)(this.width*0.4); - int l2 = 30; - - if(mouseX >= k2 && mouseX <= (this.width*0.6) && mouseY >= 30 && mouseY <= lowerBound) { - int off = mouseY-30; - int p = (off/21) + upperPlayer; - ReplayHandler.spectateEntity(players.get(p).first()); - ReplayHandler.setSpeed(prevSpeed); - mc.displayGuiScreen(null); - } - } + int h = this.height - 32 - 32; + int offset = Math.round((upperPlayer / (fitting)) * visiblePerc * h); - private int lastY = 0; + int lower = Math.round(32 + offset + (h * visiblePerc)) - 2; - @Override - protected void mouseClickMove(int mouseX, int mouseY, - int clickedMouseButton, long timeSinceLastClick) { + int k2 = (int) (this.width * 0.4); - if(drag) { - float step = 1f/(float)playerCount; + if(mouseX >= k2 - 16 && mouseX <= k2 - 12 && mouseY >= 32 - 2 + offset && mouseY <= lower) { + lastY = mouseY; + drag = true; + return; + } + } + int k2 = (int) (this.width * 0.4); + int l2 = 30; - int diff = mouseY-lastY; - int h = this.height-32-32; + if(mouseX >= k2 && mouseX <= (this.width * 0.6) && mouseY >= 30 && mouseY <= lowerBound) { + int off = mouseY - 30; + int p = (off / 21) + upperPlayer; + ReplayHandler.spectateEntity(players.get(p).first()); + ReplayMod.replaySender.setReplaySpeed(prevSpeed); + mc.displayGuiScreen(null); + } + } - float percDiff = (float)diff/(float)h; - if(Math.abs(percDiff) > Math.abs(step)) { - int s = (int)(percDiff/step); - lastY = mouseY; - upperPlayer += s; - if(upperPlayer > playerCount-fitting) { - upperPlayer = playerCount-fitting; - } else if(upperPlayer < 0) { - upperPlayer = 0; - } - } - } + @Override + protected void mouseClickMove(int mouseX, int mouseY, + int clickedMouseButton, long timeSinceLastClick) { - super.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick); - } - - @Override - public void onGuiClosed() { - ReplayHandler.setSpeed(prevSpeed); - } + if(drag) { + float step = 1f / (float) playerCount; - @Override - protected void mouseReleased(int mouseX, int mouseY, int state) { - drag = false; + int diff = mouseY - lastY; + int h = this.height - 32 - 32; - super.mouseReleased(mouseX, mouseY, state); - } + float percDiff = (float) diff / (float) h; + if(Math.abs(percDiff) > Math.abs(step)) { + int s = (int) (percDiff / step); + lastY = mouseY; + upperPlayer += s; + if(upperPlayer > playerCount - fitting) { + upperPlayer = playerCount - fitting; + } else if(upperPlayer < 0) { + upperPlayer = 0; + } + } + } - @Override - public void initGui() { - upperPlayer = 0; - lowerBound = this.height-10; - } + super.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick); + } - private int fitting = 0; + @Override + public void onGuiClosed() { + ReplayMod.replaySender.setReplaySpeed(prevSpeed); + } - @Override - public void drawScreen(int mouseX, int mouseY, float partialTicks) { - this.drawCenteredString(fontRendererObj, "Spectate Player", this.width/2, 5, Color.WHITE.getRGB()); - int k2 = (int)(this.width*0.4); - int l2 = 30; + @Override + protected void mouseReleased(int mouseX, int mouseY, int state) { + drag = false; - drawGradientRect(k2-10, l2-10, (int)(this.width*0.6)+20, this.height-30-2+10, -1072689136, -804253680); + super.mouseReleased(mouseX, mouseY, state); + } - fitting = 0; + @Override + public void initGui() { + upperPlayer = 0; + lowerBound = this.height - 10; + } - int sk = 0; - for(Pair p : players) { - if(sk < upperPlayer) { - sk++; - continue; - } - boolean spec = isSpectator(p.first()); - - this.drawString(fontRendererObj, p.first().getName(), k2+16+5, l2+8-(fontRendererObj.FONT_HEIGHT/2), - spec ? Color.DARK_GRAY.getRGB() : Color.WHITE.getRGB()); - - mc.getTextureManager().bindTexture(p.second()); - - this.drawScaledCustomSizeModalRect(k2, l2, 8.0F, 8.0F, 8, 8, 16, 16, 64.0F, 64.0F); - if(p.first().func_175148_a(EnumPlayerModelParts.HAT)) - Gui.drawScaledCustomSizeModalRect(k2, l2, 40.0F, 8.0F, 8, 8, 16, 16, 64.0F, 64.0F); + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + this.drawCenteredString(fontRendererObj, "Spectate Player", this.width / 2, 5, Color.WHITE.getRGB()); + int k2 = (int) (this.width * 0.4); + int l2 = 30; - GlStateManager.resetColor(); - - l2 += 16+5; - fitting++; - if(l2+32 > lowerBound) { - break; - } - } - - int dw = Mouse.getDWheel(); - if(dw > 0) { - dw = -1; - } else if(dw < 0) { - dw = 1; - } - - upperPlayer = Math.max(Math.min(upperPlayer+dw, playerCount-fitting), 0); + drawGradientRect(k2 - 10, l2 - 10, (int) (this.width * 0.6) + 20, this.height - 30 - 2 + 10, -1072689136, -804253680); - if(fitting < playerCount) { - float visiblePerc = ((float)fitting)/playerCount; - int barHeight = (int)(visiblePerc*(height-32-32)); + fitting = 0; - float posPerc = ((float)upperPlayer)/playerCount; - int barY = (int)(posPerc*(height-32-32)); + int sk = 0; + for(Pair p : players) { + if(sk < upperPlayer) { + sk++; + continue; + } + boolean spec = isSpectator(p.first()); - this.drawRect(k2-18, 30-2, k2-10, this.height-30-2, Color.BLACK.getRGB()); - this.drawRect(k2-16, 32-2+barY, k2-12, 32-1+barY+barHeight, Color.LIGHT_GRAY.getRGB()); - } else { + this.drawString(fontRendererObj, p.first().getName(), k2 + 16 + 5, l2 + 8 - (fontRendererObj.FONT_HEIGHT / 2), + spec ? Color.DARK_GRAY.getRGB() : Color.WHITE.getRGB()); - } + mc.getTextureManager().bindTexture(p.second()); - super.drawScreen(mouseX, mouseY, partialTicks); - } + this.drawScaledCustomSizeModalRect(k2, l2, 8.0F, 8.0F, 8, 8, 16, 16, 64.0F, 64.0F); + if(p.first().func_175148_a(EnumPlayerModelParts.HAT)) + Gui.drawScaledCustomSizeModalRect(k2, l2, 40.0F, 8.0F, 8, 8, 16, 16, 64.0F, 64.0F); + + GlStateManager.resetColor(); + + l2 += 16 + 5; + fitting++; + if(l2 + 32 > lowerBound) { + break; + } + } + + int dw = Mouse.getDWheel(); + if(dw > 0) { + dw = -1; + } else if(dw < 0) { + dw = 1; + } + + upperPlayer = Math.max(Math.min(upperPlayer + dw, playerCount - fitting), 0); + + if(fitting < playerCount) { + float visiblePerc = ((float) fitting) / playerCount; + int barHeight = (int) (visiblePerc * (height - 32 - 32)); + + float posPerc = ((float) upperPlayer) / playerCount; + int barY = (int) (posPerc * (height - 32 - 32)); + + this.drawRect(k2 - 18, 30 - 2, k2 - 10, this.height - 30 - 2, Color.BLACK.getRGB()); + this.drawRect(k2 - 16, 32 - 2 + barY, k2 - 12, 32 - 1 + barY + barHeight, Color.LIGHT_GRAY.getRGB()); + } else { + + } + + super.drawScreen(mouseX, mouseY, partialTicks); + } + + private class PlayerComparator implements Comparator { + + @Override + public int compare(EntityPlayer o1, EntityPlayer o2) { + if(isSpectator(o1) && !isSpectator(o2)) { + return 1; + } else if(isSpectator(o2) && !isSpectator(o1)) { + return -1; + } else { + return o1.getName().compareToIgnoreCase(o2.getName()); + } + } + + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/GuiVideoFramerateSlider.java b/src/main/java/eu/crushedpixel/replaymod/gui/GuiVideoFramerateSlider.java index 5d839709..468b74d1 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/GuiVideoFramerateSlider.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/GuiVideoFramerateSlider.java @@ -1,71 +1,69 @@ package eu.crushedpixel.replaymod.gui; +import eu.crushedpixel.replaymod.ReplayMod; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.settings.GameSettings; import net.minecraft.util.MathHelper; -import eu.crushedpixel.replaymod.ReplayMod; public class GuiVideoFramerateSlider extends GuiButton { - public GuiVideoFramerateSlider(int buttonId, int p_i45017_2_, int p_i45017_3_, int initialFramerate, String displayKey) { - super(buttonId, p_i45017_2_, p_i45017_3_, 150, 20, ""); - this.sliderValue = normalizeValue(initialFramerate); - this.displayString = displayKey+": "+translate(initialFramerate); - this.displayKey = displayKey; - } - - private String displayKey; - private float sliderValue; - public boolean dragging; - - private String translate(int value) { - return String.valueOf(value); - } + public boolean dragging; + private String displayKey; + private float sliderValue; + public GuiVideoFramerateSlider(int buttonId, int p_i45017_2_, int p_i45017_3_, int initialFramerate, String displayKey) { + super(buttonId, p_i45017_2_, p_i45017_3_, 150, 20, ""); + this.sliderValue = normalizeValue(initialFramerate); + this.displayString = displayKey + ": " + translate(initialFramerate); + this.displayKey = displayKey; + } - protected int getHoverState(boolean mouseOver) { - return 0; - } + private String translate(int value) { + return String.valueOf(value); + } - @Override - protected void mouseDragged(Minecraft mc, int mouseX, int mouseY) { - if (this.visible) { - if (this.dragging) { - sliderValue = (float)(mouseX - (this.xPosition + 4)) / (float)(this.width - 8); - sliderValue = MathHelper.clamp_float(sliderValue, 0.0F, 1.0F); - int f = denormalizeValue(sliderValue); - this.displayString = displayKey+": "+translate(f); - ReplayMod.replaySettings.setVideoFramerate(f); - } + protected int getHoverState(boolean mouseOver) { + return 0; + } - mc.getTextureManager().bindTexture(buttonTextures); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - this.drawTexturedModalRect(this.xPosition + (int)(sliderValue * (float)(this.width - 8)), this.yPosition, 0, 66, 4, 20); - this.drawTexturedModalRect(this.xPosition + (int)(sliderValue * (float)(this.width - 8)) + 4, this.yPosition, 196, 66, 4, 20); - } - } + @Override + protected void mouseDragged(Minecraft mc, int mouseX, int mouseY) { + if(this.visible) { + if(this.dragging) { + sliderValue = (float) (mouseX - (this.xPosition + 4)) / (float) (this.width - 8); + sliderValue = MathHelper.clamp_float(sliderValue, 0.0F, 1.0F); + int f = denormalizeValue(sliderValue); + this.displayString = displayKey + ": " + translate(f); + ReplayMod.replaySettings.setVideoFramerate(f); + } - private float normalizeValue(int val) { - return (val-10)/110f; - } - - private int denormalizeValue(float val) { - //Transfers the value ranging from 0.0 to 1.0 to the scale of 10 to 120 - float r = 110f*val; - return Math.round(10+r); - } + mc.getTextureManager().bindTexture(buttonTextures); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.drawTexturedModalRect(this.xPosition + (int) (sliderValue * (float) (this.width - 8)), this.yPosition, 0, 66, 4, 20); + this.drawTexturedModalRect(this.xPosition + (int) (sliderValue * (float) (this.width - 8)) + 4, this.yPosition, 196, 66, 4, 20); + } + } - public boolean mousePressed(Minecraft mc, int mouseX, int mouseY) { - if (super.mousePressed(mc, mouseX, mouseY)) { - this.dragging = true; - return true; - } else { - return false; - } - } + private float normalizeValue(int val) { + return (val - 10) / 110f; + } - public void mouseReleased(int mouseX, int mouseY) { - this.dragging = false; - } + private int denormalizeValue(float val) { + //Transfers the value ranging from 0.0 to 1.0 to the scale of 10 to 120 + float r = 110f * val; + return Math.round(10 + r); + } + + public boolean mousePressed(Minecraft mc, int mouseX, int mouseY) { + if(super.mousePressed(mc, mouseX, mouseY)) { + this.dragging = true; + return true; + } else { + return false; + } + } + + public void mouseReleased(int mouseX, int mouseY) { + this.dragging = false; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/GuiVideoQualitySlider.java b/src/main/java/eu/crushedpixel/replaymod/gui/GuiVideoQualitySlider.java index 78489e52..57912a97 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/GuiVideoQualitySlider.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/GuiVideoQualitySlider.java @@ -1,85 +1,83 @@ package eu.crushedpixel.replaymod.gui; +import eu.crushedpixel.replaymod.ReplayMod; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.settings.GameSettings; import net.minecraft.util.MathHelper; -import eu.crushedpixel.replaymod.ReplayMod; public class GuiVideoQualitySlider extends GuiButton { - public GuiVideoQualitySlider(int buttonId, int p_i45017_2_, int p_i45017_3_, float d, String displayKey) { - super(buttonId, p_i45017_2_, p_i45017_3_, 150, 20, ""); - this.sliderValue = normalizeValue(d); - this.displayString = displayKey+": "+translate(d); - this.displayKey = displayKey; - } - - private String displayKey; - private float sliderValue; - public boolean dragging; - - private String translate(float value) { - if(value <= 0.3) { - return "Draft"; - } else if(value <= 0.5) { - return "Normal"; - } else if(value <= 0.7) { - return "Good"; - } - return "Best"; - } + public boolean dragging; + private String displayKey; + private float sliderValue; + public GuiVideoQualitySlider(int buttonId, int p_i45017_2_, int p_i45017_3_, float d, String displayKey) { + super(buttonId, p_i45017_2_, p_i45017_3_, 150, 20, ""); + this.sliderValue = normalizeValue(d); + this.displayString = displayKey + ": " + translate(d); + this.displayKey = displayKey; + } - protected int getHoverState(boolean mouseOver) { - return 0; - } + private String translate(float value) { + if(value <= 0.3) { + return "Draft"; + } else if(value <= 0.5) { + return "Normal"; + } else if(value <= 0.7) { + return "Good"; + } + return "Best"; + } - @Override - protected void mouseDragged(Minecraft mc, int mouseX, int mouseY) { - if (this.visible) { - if (this.dragging) { - sliderValue = (float)(mouseX - (this.xPosition + 4)) / (float)(this.width - 8); - sliderValue = MathHelper.clamp_float(sliderValue, 0.0F, 1.0F); - float f = denormalizeValue(sliderValue); - f = snapValue(f); - sliderValue = normalizeValue(f); - this.displayString = displayKey+": "+translate(f); - ReplayMod.replaySettings.setVideoQuality(f); - } + protected int getHoverState(boolean mouseOver) { + return 0; + } - mc.getTextureManager().bindTexture(buttonTextures); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - this.drawTexturedModalRect(this.xPosition + (int)(sliderValue * (float)(this.width - 8)), this.yPosition, 0, 66, 4, 20); - this.drawTexturedModalRect(this.xPosition + (int)(sliderValue * (float)(this.width - 8)) + 4, this.yPosition, 196, 66, 4, 20); - } - } - - private float snapValue(float val) { - int i = Math.round(val*10); - return i/10f; - } + @Override + protected void mouseDragged(Minecraft mc, int mouseX, int mouseY) { + if(this.visible) { + if(this.dragging) { + sliderValue = (float) (mouseX - (this.xPosition + 4)) / (float) (this.width - 8); + sliderValue = MathHelper.clamp_float(sliderValue, 0.0F, 1.0F); + float f = denormalizeValue(sliderValue); + f = snapValue(f); + sliderValue = normalizeValue(f); + this.displayString = displayKey + ": " + translate(f); + ReplayMod.replaySettings.setVideoQuality(f); + } - private float normalizeValue(float val) { - return (val-0.1f)/0.8f; - } - - private float denormalizeValue(float val) { - //Transfers the value ranging from 0.0 to 1.0 to the scale of 0.1 to 0.9 - float r = 0.8f*val; - return 0.1f+r; - } + mc.getTextureManager().bindTexture(buttonTextures); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.drawTexturedModalRect(this.xPosition + (int) (sliderValue * (float) (this.width - 8)), this.yPosition, 0, 66, 4, 20); + this.drawTexturedModalRect(this.xPosition + (int) (sliderValue * (float) (this.width - 8)) + 4, this.yPosition, 196, 66, 4, 20); + } + } - public boolean mousePressed(Minecraft mc, int mouseX, int mouseY) { - if (super.mousePressed(mc, mouseX, mouseY)) { - this.dragging = true; - return true; - } else { - return false; - } - } + private float snapValue(float val) { + int i = Math.round(val * 10); + return i / 10f; + } - public void mouseReleased(int mouseX, int mouseY) { - this.dragging = false; - } + private float normalizeValue(float val) { + return (val - 0.1f) / 0.8f; + } + + private float denormalizeValue(float val) { + //Transfers the value ranging from 0.0 to 1.0 to the scale of 0.1 to 0.9 + float r = 0.8f * val; + return 0.1f + r; + } + + public boolean mousePressed(Minecraft mc, int mouseX, int mouseY) { + if(super.mousePressed(mc, mouseX, mouseY)) { + this.dragging = true; + return true; + } else { + return false; + } + } + + public void mouseReleased(int mouseX, int mouseY) { + this.dragging = false; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/PasswordTextField.java b/src/main/java/eu/crushedpixel/replaymod/gui/PasswordTextField.java index 7c0b83a2..5abfa56a 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/PasswordTextField.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/PasswordTextField.java @@ -1,46 +1,46 @@ package eu.crushedpixel.replaymod.gui; -import java.lang.reflect.Field; - import eu.crushedpixel.replaymod.reflection.MCPNames; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiTextField; +import java.lang.reflect.Field; + public class PasswordTextField extends GuiTextField { - private static Field text; + private static Field text; - static { - try { - text = GuiTextField.class.getDeclaredField(MCPNames.field("field_146216_j")); - text.setAccessible(true); - } catch(Exception e) { - e.printStackTrace(); - } - } + static { + try { + text = GuiTextField.class.getDeclaredField(MCPNames.field("field_146216_j")); + text.setAccessible(true); + } catch(Exception e) { + e.printStackTrace(); + } + } - public PasswordTextField(int p_i45542_1_, FontRenderer p_i45542_2_, - int p_i45542_3_, int p_i45542_4_, int p_i45542_5_, int p_i45542_6_) { - super(p_i45542_1_, p_i45542_2_, p_i45542_3_, p_i45542_4_, p_i45542_5_, - p_i45542_6_); - } + public PasswordTextField(int p_i45542_1_, FontRenderer p_i45542_2_, + int p_i45542_3_, int p_i45542_4_, int p_i45542_5_, int p_i45542_6_) { + super(p_i45542_1_, p_i45542_2_, p_i45542_3_, p_i45542_4_, p_i45542_5_, + p_i45542_6_); + } - @Override - public void drawTextBox() { - String prev = getText(); + @Override + public void drawTextBox() { + String prev = getText(); - String pw = ""; - for(int i=0; i extends GuiTextField { - private int selectionIndex = -1; - private boolean open = false; + private final int visibleDropout; + private final int dropoutElementHeight = 14; + private final int maxDropoutHeight; + private int selectionIndex = -1; + private boolean open = false; + private Minecraft mc = Minecraft.getMinecraft(); + private List selectionListeners = new ArrayList(); - private Minecraft mc = Minecraft.getMinecraft(); + private int upperIndex = 0; + private List elements = new ArrayList(); - private final int visibleDropout; - private final int dropoutElementHeight = 14; - private final int maxDropoutHeight; + public GuiDropdown(int id, FontRenderer fontRenderer, + int xPos, int yPos, int width, int visibleDropout) { + super(id, fontRenderer, xPos, yPos, width, 20); + this.visibleDropout = visibleDropout; + this.maxDropoutHeight = dropoutElementHeight * visibleDropout; + } - private List selectionListeners = new ArrayList(); - - private int upperIndex = 0; + @Override + public void drawTextBox() { + if(elements.size() > selectionIndex && selectionIndex >= 0) { + setText(mc.fontRendererObj.trimStringToWidth( + elements.get(selectionIndex).toString(), width - 8)); + } else { + setText(""); + } + super.drawTextBox(); - public GuiDropdown(int id, FontRenderer fontRenderer, - int xPos, int yPos, int width, int visibleDropout) { - super(id, fontRenderer, xPos, yPos, width, 20); - this.visibleDropout = visibleDropout; - this.maxDropoutHeight = dropoutElementHeight*visibleDropout; - } - - @Override - public void drawTextBox() { - if(elements.size() > selectionIndex && selectionIndex >= 0) { - setText(mc.fontRendererObj.trimStringToWidth( - elements.get(selectionIndex).toString(), width-8)); - } else { - setText(""); - } - super.drawTextBox(); + //Draw the right part of the Dropdown + drawRect(xPosition + width - height, yPosition, xPosition + width, yPosition + height, -16777216); + drawRect(xPosition + width - height, yPosition, this.xPosition + width - height + 1, yPosition + height, -6250336); - //Draw the right part of the Dropdown - drawRect(xPosition+width-height, yPosition, xPosition+width, yPosition+height, -16777216); - drawRect(xPosition+width-height, yPosition, this.xPosition+width-height+1, yPosition+height, -6250336); + //heroically draw the triangle line by line instead of using a texture + for(int i = 0; i <= Math.ceil(height / 2) - 4; i++) { + drawHorizontalLine(xPosition + width - height + i + 4, xPosition + width - i - 4, yPosition + (height / 4) + i + 2, -6250336); + } - //heroically draw the triangle line by line instead of using a texture - for(int i=0; i<=Math.ceil(height/2)-4; i++) { - drawHorizontalLine(xPosition+width-height+i+4, xPosition+width-i-4, yPosition+(height/4)+i+2, -6250336); - } + if(open && elements.size() > 0) { + //draw the dropout part when opened - if(open && elements.size() > 0) { - //draw the dropout part when opened + boolean drawScrollBar = false; - boolean drawScrollBar = false; + int requiredHeight = elements.size() * dropoutElementHeight; + if(requiredHeight > maxDropoutHeight) { + requiredHeight = maxDropoutHeight; + drawScrollBar = true; + } - int requiredHeight = elements.size()*dropoutElementHeight; - if(requiredHeight > maxDropoutHeight) { - requiredHeight = maxDropoutHeight; - drawScrollBar = true; - } + //The light outline + drawRect(xPosition - 1, yPosition + height, xPosition + width + 1, yPosition + height + requiredHeight + 1, -6250336); - //The light outline - drawRect(xPosition-1, yPosition+height, xPosition+width+1, yPosition+height+requiredHeight+1, -6250336); + //The dark inside + drawRect(xPosition, yPosition + height + 1, xPosition + width, yPosition + height + requiredHeight, -16777216); - //The dark inside - drawRect(xPosition, yPosition+height+1, xPosition+width, yPosition+height+requiredHeight, -16777216); + //The elements + int y = 0; + int i = 0; + for(T obj : elements) { + if(i < upperIndex) { + i++; + continue; + } + drawHorizontalLine(xPosition, xPosition + width, yPosition + height + y, -6250336); + String toWrite = mc.fontRendererObj.trimStringToWidth(obj.toString(), width - 8); + drawString(mc.fontRendererObj, toWrite, xPosition + 4, yPosition + height + y + 4, Color.WHITE.getRGB()); - //The elements - int y = 0; - int i = 0; - for(T obj : elements) { - if(i= requiredHeight) { + break; + } + } - y += dropoutElementHeight; - i++; - if(y >= requiredHeight) { - break; - } - } + if(drawScrollBar) { + //The scroll bar + int dw = Mouse.getDWheel(); + if(dw > 0) { + dw = -1; + } else if(dw < 0) { + dw = 1; + } - if(drawScrollBar) { - //The scroll bar - int dw = Mouse.getDWheel(); - if(dw > 0) { - dw = -1; - } else if(dw < 0) { - dw = 1; - } + upperIndex = Math.max(Math.min(upperIndex + dw, elements.size() - visibleDropout), 0); - upperIndex = Math.max(Math.min(upperIndex+dw, elements.size()-visibleDropout), 0); + drawRect(xPosition + width - 3, yPosition + height + 1, xPosition + width, yPosition + height + requiredHeight, Color.DARK_GRAY.getRGB()); - drawRect(xPosition+width-3, yPosition+height+1, xPosition+width, yPosition+height+requiredHeight, Color.DARK_GRAY.getRGB()); + float visiblePerc = ((float) visibleDropout) / elements.size(); + int barHeight = (int) (visiblePerc * (requiredHeight - 1)); - float visiblePerc = ((float)visibleDropout)/elements.size(); - int barHeight = (int)(visiblePerc*(requiredHeight-1)); + float posPerc = ((float) upperIndex) / elements.size(); + int barY = (int) (posPerc * (requiredHeight - 1)); - float posPerc = ((float)upperIndex)/elements.size(); - int barY = (int)(posPerc*(requiredHeight-1)); + drawRect(xPosition + width - 3, yPosition + height + barY, xPosition + width, yPosition + height + 2 + barY + barHeight, -6250336); + } + } + } - drawRect(xPosition+width-3, yPosition+height+barY, xPosition+width, yPosition+height+2+barY+barHeight, -6250336); - } - } - } + @Override + public void mouseClicked(int xPos, int yPos, int mouseButton) { + if(xPos > xPosition + width - height && xPos < xPosition + width && yPos > yPosition && yPos < yPosition + height) { + open = !open; + } else { + if(xPos > xPosition && xPos < xPosition + width && open) { + int requiredHeight = Math.min(maxDropoutHeight, elements.size() * dropoutElementHeight); + if(yPos > yPosition + height && yPos < yPosition + height + requiredHeight) { + int clickedIndex = (int) Math.floor((yPos - (yPosition + height)) / dropoutElementHeight) + upperIndex; + this.selectionIndex = clickedIndex; + fireSelectionChangeEvent(); + } + open = false; + } else { + open = false; + } + } + } - @Override - public void mouseClicked(int xPos, int yPos, int mouseButton) { - if(xPos > xPosition+width-height && xPos < xPosition+width && yPos > yPosition && yPos < yPosition+height) { - open = !open; - } else { - if(xPos > xPosition && xPos < xPosition+width && open) { - int requiredHeight = Math.min(maxDropoutHeight, elements.size()*dropoutElementHeight); - if(yPos > yPosition+height && yPos < yPosition+height+requiredHeight) { - int clickedIndex = (int)Math.floor((yPos - (yPosition+height)) / dropoutElementHeight) + upperIndex; - this.selectionIndex = clickedIndex; - fireSelectionChangeEvent(); - } - open = false; - } else { - open = false; - } - } - } + @Override + public void setText(String text) { + if(!getText().equals(text)) { + super.setText(text); + } + } - @Override - public void setText(String text) { - if(!getText().equals(text)) { - super.setText(text); - } - } + public void setElements(List elements) { + this.elements = elements; + if(selectionIndex == -1 && elements.size() > 0) { + selectionIndex = 0; + } + } - private List elements = new ArrayList(); + public void clearElements() { + this.elements = new ArrayList(); + selectionIndex = -1; + } - public void setSelectionIndex(int index) { - this.selectionIndex = index; - if(selectionIndex < 0) selectionIndex = -1; - fireSelectionChangeEvent(); - } + public void addElement(T element) { + this.elements.add(element); + if(selectionIndex == -1) { + selectionIndex = 0; + } + } - public void setElements(List elements) { - this.elements = elements; - if(selectionIndex == -1 && elements.size() > 0) { - selectionIndex = 0; - } - } + public T getElement(int index) { + return elements.get(index); + } - public void clearElements() { - this.elements = new ArrayList(); - selectionIndex = -1; - } + public List getAllElements() { + return elements; + } - public void addElement(T element) { - this.elements.add(element); - if(selectionIndex == -1) { - selectionIndex = 0; - } - } + public int getSelectionIndex() { + return selectionIndex; + } - public T getElement(int index) { - return elements.get(index); - } + public void setSelectionIndex(int index) { + this.selectionIndex = index; + if(selectionIndex < 0) selectionIndex = -1; + fireSelectionChangeEvent(); + } - public List getAllElements() { - return elements; - } - - public int getSelectionIndex() { - return selectionIndex; - } + private void fireSelectionChangeEvent() { + for(SelectionListener listener : selectionListeners) { + listener.onSelectionChanged(selectionIndex); + } + } - private void fireSelectionChangeEvent() { - for(SelectionListener listener : selectionListeners) { - listener.onSelectionChanged(selectionIndex); - } - } - - public void addSelectionListener(SelectionListener listener) { - this.selectionListeners.add(listener); - } + public void addSelectionListener(SelectionListener listener) { + this.selectionListeners.add(listener); + } - public void removeSelectionListener(SelectionListener listener) { - this.selectionListeners.remove(listener); - } + public void removeSelectionListener(SelectionListener listener) { + this.selectionListeners.remove(listener); + } - public boolean isExpanded() { - return open; - } + public boolean isExpanded() { + return open; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/elements/GuiEntryList.java b/src/main/java/eu/crushedpixel/replaymod/gui/elements/GuiEntryList.java index 1d6b8db1..2cd7703d 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/elements/GuiEntryList.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/elements/GuiEntryList.java @@ -1,150 +1,146 @@ package eu.crushedpixel.replaymod.gui.elements; -import java.awt.Color; -import java.util.ArrayList; -import java.util.List; - -import org.lwjgl.input.Mouse; - import eu.crushedpixel.replaymod.gui.elements.listeners.SelectionListener; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiTextField; +import org.lwjgl.input.Mouse; + +import java.awt.*; +import java.util.ArrayList; +import java.util.List; public class GuiEntryList extends GuiTextField { - private int selectionIndex = -1; + public final static int elementHeight = 14; + private int selectionIndex = -1; + private Minecraft mc = Minecraft.getMinecraft(); + private int visibleElements; + private int upperIndex = 0; - private Minecraft mc = Minecraft.getMinecraft(); + private List selectionListeners = new ArrayList(); + private List elements = new ArrayList(); - private int visibleElements; - public final static int elementHeight = 14; + public GuiEntryList(int id, FontRenderer fontRenderer, + int xPos, int yPos, int width, int visibleEntries) { + super(id, fontRenderer, xPos, yPos, width, elementHeight * visibleEntries - 1); + this.visibleElements = visibleEntries; + } - private int upperIndex = 0; + public void setVisibleElements(int rows) { + this.visibleElements = rows; + this.height = elementHeight * visibleElements - 1; + } - private List selectionListeners = new ArrayList(); + @Override + public void drawTextBox() { + try { + super.drawTextBox(); + //drawing the entries + for(int i = 0; i - upperIndex < visibleElements; i++) { + if(i < upperIndex) continue; - public GuiEntryList(int id, FontRenderer fontRenderer, - int xPos, int yPos, int width, int visibleEntries) { - super(id, fontRenderer, xPos, yPos, width, elementHeight*visibleEntries-1); - this.visibleElements = visibleEntries; - } + if(i >= elements.size()) break; - public void setVisibleElements(int rows) { - this.visibleElements = rows; - this.height = elementHeight*visibleElements-1; - } + if(i == selectionIndex) { + drawRect(xPosition, yPosition + (i - upperIndex) * elementHeight, xPosition + width, + yPosition + (i + 1 - upperIndex) * elementHeight - 1, Color.GRAY.getRGB()); + } - @Override - public void drawTextBox() { - try { - super.drawTextBox(); - //drawing the entries - for(int i=0; i-upperIndex= elements.size()) break; + //drawing the scroll bar + if(elements.size() > visibleElements) { + //handle scroll events + int dw = Mouse.getDWheel(); + if(dw > 0) { + dw = -1; + } else if(dw < 0) { + dw = 1; + } - if(i == selectionIndex) { - drawRect(xPosition, yPosition+(i-upperIndex)*elementHeight, xPosition+width, - yPosition+(i+1-upperIndex)*elementHeight-1, Color.GRAY.getRGB()); - } + upperIndex = Math.max(Math.min(upperIndex + dw, elements.size() - visibleElements), 0); - drawRect(xPosition, yPosition+(i+1-upperIndex)*elementHeight-1, xPosition+width, - yPosition+(i+1-upperIndex)*elementHeight, -6250336); - drawString(mc.fontRendererObj, mc.fontRendererObj.trimStringToWidth(elements.get(i).toString(), width-4), - xPosition+2, yPosition+(i-upperIndex)*elementHeight+3, Color.WHITE.getRGB()); - } + float visiblePerc = ((float) visibleElements) / elements.size(); + int barHeight = (int) (visiblePerc * (height - 1)); - //drawing the scroll bar - if(elements.size() > visibleElements) { - //handle scroll events - int dw = Mouse.getDWheel(); - if(dw > 0) { - dw = -1; - } else if(dw < 0) { - dw = 1; - } + float posPerc = ((float) upperIndex) / elements.size(); + int barY = (int) (posPerc * (height - 1)); - upperIndex = Math.max(Math.min(upperIndex+dw, elements.size()-visibleElements), 0); + drawRect(xPosition + width - 3, yPosition, xPosition + width, yPosition + height, Color.DARK_GRAY.getRGB()); + drawRect(xPosition + width - 3, yPosition + barY, xPosition + width, yPosition + 1 + barY + barHeight, -6250336); + } + } catch(Exception e) { + e.printStackTrace(); + } + } - float visiblePerc = ((float)visibleElements)/elements.size(); - int barHeight = (int)(visiblePerc*(height-1)); + @Override + public void mouseClicked(int xPos, int yPos, int mouseButton) { + if(!(xPos >= xPosition && xPos <= xPosition + width && yPos >= yPosition && yPos <= yPosition + height)) return; + int clickedIndex = (int) Math.floor((yPos - yPosition) / elementHeight) + upperIndex; + if(clickedIndex < elements.size() && clickedIndex >= 0) { + selectionIndex = clickedIndex; + fireSelectionChangeEvent(); + } + } - float posPerc = ((float)upperIndex)/elements.size(); - int barY = (int)(posPerc*(height-1)); + private void fireSelectionChangeEvent() { + for(SelectionListener listener : selectionListeners) { + listener.onSelectionChanged(selectionIndex); + } + } - drawRect(xPosition+width-3, yPosition, xPosition+width, yPosition+height, Color.DARK_GRAY.getRGB()); - drawRect(xPosition+width-3, yPosition+barY, xPosition+width, yPosition+1+barY+barHeight, -6250336); - } - } catch(Exception e) { - e.printStackTrace(); - } - } + @Override + public void setText(String text) { + } - @Override - public void mouseClicked(int xPos, int yPos, int mouseButton) { - if(!(xPos >= xPosition && xPos <= xPosition+width && yPos >= yPosition && yPos <= yPosition+height)) return; - int clickedIndex = (int)Math.floor((yPos-yPosition) / elementHeight) + upperIndex; - if(clickedIndex < elements.size() && clickedIndex >= 0) { - selectionIndex = clickedIndex; - fireSelectionChangeEvent(); - } - } + public void setElements(List elements) { + this.elements = elements; + if(selectionIndex == -1 && elements.size() > 0) { + selectionIndex = 0; + } + } - private void fireSelectionChangeEvent() { - for(SelectionListener listener : selectionListeners) { - listener.onSelectionChanged(selectionIndex); - } - } + public void clearElements() { + this.elements = new ArrayList(); + selectionIndex = -1; + } - @Override - public void setText(String text) {} + public void addElement(T element) { + this.elements.add(element); + if(selectionIndex == -1) { + selectionIndex = 0; + } + } - private List elements = new ArrayList(); + public T getElement(int index) { + if(index >= 0) { + return elements.get(index); + } + return null; + } - public void setElements(List elements) { - this.elements = elements; - if(selectionIndex == -1 && elements.size() > 0) { - selectionIndex = 0; - } - } + public int getSelectionIndex() { + return selectionIndex; + } - public void clearElements() { - this.elements = new ArrayList(); - selectionIndex = -1; - } + public void setSelectionIndex(int index) { + this.selectionIndex = index; + if(selectionIndex < 0) selectionIndex = -1; + fireSelectionChangeEvent(); + } - public void addElement(T element) { - this.elements.add(element); - if(selectionIndex == -1) { - selectionIndex = 0; - } - } + public void addSelectionListener(SelectionListener listener) { + this.selectionListeners.add(listener); + } - public T getElement(int index) { - if(index >= 0) { - return elements.get(index); - } - return null; - } - - public int getSelectionIndex() { - return selectionIndex; - } - - public void setSelectionIndex(int index) { - this.selectionIndex = index; - if(selectionIndex < 0) selectionIndex = -1; - fireSelectionChangeEvent(); - } - - public void addSelectionListener(SelectionListener listener) { - this.selectionListeners.add(listener); - } - - public void removeSelectionListener(SelectionListener listener) { - this.selectionListeners.remove(listener); - } + public void removeSelectionListener(SelectionListener listener) { + this.selectionListeners.remove(listener); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/elements/GuiMouseInput.java b/src/main/java/eu/crushedpixel/replaymod/gui/elements/GuiMouseInput.java deleted file mode 100755 index 946b4b96..00000000 --- a/src/main/java/eu/crushedpixel/replaymod/gui/elements/GuiMouseInput.java +++ /dev/null @@ -1,10 +0,0 @@ -package eu.crushedpixel.replaymod.gui.elements; - -import org.lwjgl.input.Keyboard; - -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.gui.GuiTextField; - -public class GuiMouseInput extends GuiScreen { - -} diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/elements/GuiNumberInput.java b/src/main/java/eu/crushedpixel/replaymod/gui/elements/GuiNumberInput.java index fddcd64a..a8935bb0 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/elements/GuiNumberInput.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/elements/GuiNumberInput.java @@ -1,26 +1,26 @@ package eu.crushedpixel.replaymod.gui.elements; -import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiTextField; public class GuiNumberInput extends GuiTextField { - private int limit; - - public GuiNumberInput(int id, FontRenderer fontRenderer, - int xPos, int yPos, int width, int limit) { - super(id, fontRenderer, xPos, yPos, width, 20); - this.limit = limit; - } - - @Override - public void writeText(String text) { - try { - Integer.valueOf(text); - if(limit > 0 && (getText()+text).length() > limit) return; - super.writeText(text); - } catch(NumberFormatException e) {} - } + private int limit; + + public GuiNumberInput(int id, FontRenderer fontRenderer, + int xPos, int yPos, int width, int limit) { + super(id, fontRenderer, xPos, yPos, width, 20); + this.limit = limit; + } + + @Override + public void writeText(String text) { + try { + Integer.valueOf(text); + if(limit > 0 && (getText() + text).length() > limit) return; + super.writeText(text); + } catch(NumberFormatException e) { + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/elements/GuiReplayListEntry.java b/src/main/java/eu/crushedpixel/replaymod/gui/elements/GuiReplayListEntry.java index df265ea1..f458693d 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/elements/GuiReplayListEntry.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/elements/GuiReplayListEntry.java @@ -1,5 +1,14 @@ package eu.crushedpixel.replaymod.gui.elements; +import eu.crushedpixel.replaymod.api.client.holders.FileInfo; +import eu.crushedpixel.replaymod.utils.ResourceHelper; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.GuiListExtended.IGuiListEntry; +import net.minecraft.client.renderer.texture.DynamicTexture; +import net.minecraft.util.ResourceLocation; + +import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.text.DateFormat; @@ -9,114 +18,102 @@ import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; -import javax.imageio.ImageIO; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Gui; -import net.minecraft.client.gui.GuiListExtended.IGuiListEntry; -import net.minecraft.client.renderer.texture.DynamicTexture; -import net.minecraft.util.ResourceLocation; -import eu.crushedpixel.replaymod.api.client.holders.FileInfo; -import eu.crushedpixel.replaymod.utils.ResourceHelper; - public class GuiReplayListEntry implements IGuiListEntry { - private Minecraft minecraft = Minecraft.getMinecraft(); - private final DateFormat dateFormat = new SimpleDateFormat(); + private final DateFormat dateFormat = new SimpleDateFormat(); + boolean registered = false; + private Minecraft minecraft = Minecraft.getMinecraft(); + private FileInfo fileInfo; + private ResourceLocation textureResource; + private DynamicTexture dynTex = null; + private File imageFile; + private BufferedImage image = null; + private GuiReplayListExtended parent; - private FileInfo fileInfo; - - private ResourceLocation textureResource; - private DynamicTexture dynTex = null; + public GuiReplayListEntry(GuiReplayListExtended parent, FileInfo fileInfo, File imageFile) { + this.fileInfo = fileInfo; + this.parent = parent; + dynTex = null; + this.imageFile = imageFile; + } - private File imageFile; - private BufferedImage image = null; - private GuiReplayListExtended parent; - - public FileInfo getFileInfo() { - return fileInfo; - } + public FileInfo getFileInfo() { + return fileInfo; + } - public GuiReplayListEntry(GuiReplayListExtended parent, FileInfo fileInfo, File imageFile) { - this.fileInfo = fileInfo; - this.parent = parent; - dynTex = null; - this.imageFile = imageFile; - } + @Override + public void drawEntry(int slotIndex, int x, int y, int listWidth, int slotHeight, int mouseX, int mouseY, boolean isSelected) { + try { + if(fileInfo.getName() == null || fileInfo.getName().length() < 1) { + fileInfo.setName("No Name"); + } + minecraft.fontRendererObj.drawString(fileInfo.getName(), x + 3, y + 1, 16777215); - boolean registered = false; + if(y < -slotHeight || y > parent.height) { + if(registered) { + registered = false; + ResourceHelper.freeResource(textureResource); + textureResource = null; + image = null; + dynTex = null; + } + return; + } else { + if(!registered) { + textureResource = new ResourceLocation("thumbs/" + fileInfo.getName() + fileInfo.getId()); + if(imageFile == null) { + image = ResourceHelper.getDefaultThumbnail(); + } else { + image = ImageIO.read(imageFile); + } + dynTex = new DynamicTexture(image); + minecraft.getTextureManager().loadTexture(textureResource, dynTex); + dynTex.updateDynamicTexture(); + ResourceHelper.registerResource(textureResource); + registered = true; + } - @Override - public void drawEntry(int slotIndex, int x, int y, int listWidth, int slotHeight, int mouseX, int mouseY, boolean isSelected) { - try { - if(fileInfo.getName() == null || fileInfo.getName().length() < 1) { - fileInfo.setName("No Name"); - } - minecraft.fontRendererObj.drawString(fileInfo.getName(), x + 3, y + 1, 16777215); + minecraft.getTextureManager().bindTexture(textureResource); + Gui.drawScaledCustomSizeModalRect(x - 60, y, 0, 0, 1280, 720, 57, 32, 1280, 720); + } - if(y < -slotHeight || y > parent.height) { - if(registered) { - registered = false; - ResourceHelper.freeResource(textureResource); - textureResource = null; - image = null; - dynTex = null; - } - return; - } else { - if(!registered) { - textureResource = new ResourceLocation("thumbs/"+fileInfo.getName()+fileInfo.getId()); - if(imageFile == null) { - image = ResourceHelper.getDefaultThumbnail(); - } else { - image = ImageIO.read(imageFile); - } - dynTex = new DynamicTexture(image); - minecraft.getTextureManager().loadTexture(textureResource, dynTex); - dynTex.updateDynamicTexture(); - ResourceHelper.registerResource(textureResource); - registered = true; - } + List list = new ArrayList(); + list.add(fileInfo.getMetadata().getServerName() + " (" + dateFormat.format(new Date(fileInfo.getMetadata().getDate())) + ")"); - minecraft.getTextureManager().bindTexture(textureResource); - Gui.drawScaledCustomSizeModalRect(x-60, y, 0, 0, 1280, 720, 57, 32, 1280, 720); - } + list.add(String.format("%02dm%02ds", + TimeUnit.MILLISECONDS.toMinutes(fileInfo.getMetadata().getDuration()), + TimeUnit.MILLISECONDS.toSeconds(fileInfo.getMetadata().getDuration()) - + TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(fileInfo.getMetadata().getDuration())) + )); - List list = new ArrayList(); - list.add(fileInfo.getMetadata().getServerName()+" ("+dateFormat.format(new Date(fileInfo.getMetadata().getDate()))+")"); + for(int l1 = 0; l1 < Math.min(list.size(), 2); ++l1) { + minecraft.fontRendererObj.drawString((String) list.get(l1), x + 3, y + 12 + minecraft.fontRendererObj.FONT_HEIGHT * l1, 8421504); + } + } catch(Exception e) { + e.printStackTrace(); + } + } - list.add(String.format("%02dm%02ds", - TimeUnit.MILLISECONDS.toMinutes(fileInfo.getMetadata().getDuration()), - TimeUnit.MILLISECONDS.toSeconds(fileInfo.getMetadata().getDuration()) - - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(fileInfo.getMetadata().getDuration())) - )); + @Override + public void setSelected(int p_178011_1_, int p_178011_2_, int p_178011_3_) { + } - for (int l1 = 0; l1 < Math.min(list.size(), 2); ++l1) { - minecraft.fontRendererObj.drawString((String)list.get(l1), x + 3, y + 12 + minecraft.fontRendererObj.FONT_HEIGHT * l1, 8421504); - } - } catch(Exception e) { - e.printStackTrace(); - } - } + @Override + public boolean mousePressed(int p_148278_1_, int p_148278_2_, + int p_148278_3_, int p_148278_4_, int p_148278_5_, int p_148278_6_) { + for(int slot = 0; slot < parent.getSize(); slot++) { + if(parent.getListEntry(slot) == this) { + parent.elementClicked(slot, false, p_148278_5_, p_148278_6_); + break; + } + } - @Override - public void setSelected(int p_178011_1_, int p_178011_2_, int p_178011_3_) {} + return true; + } - @Override - public boolean mousePressed(int p_148278_1_, int p_148278_2_, - int p_148278_3_, int p_148278_4_, int p_148278_5_, int p_148278_6_) { - for(int slot = 0; slot entries = new ArrayList(); - public int selected = -1; - - @Override - protected void elementClicked(int slotIndex, boolean isDoubleClick, - int mouseX, int mouseY) { - super.elementClicked(slotIndex, isDoubleClick, mouseX, mouseY); - this.selected = slotIndex; - } - - @Override - protected void drawSelectionBox(int p_148120_1_, int p_148120_2_, int p_148120_3_, int p_148120_4_) - { + public GuiReplayListExtended(Minecraft mcIn, int p_i45010_2_, + int p_i45010_3_, int p_i45010_4_, int p_i45010_5_, int p_i45010_6_) { + super(mcIn, p_i45010_2_, p_i45010_3_, p_i45010_4_, p_i45010_5_, p_i45010_6_); + } + + @Override + protected void elementClicked(int slotIndex, boolean isDoubleClick, + int mouseX, int mouseY) { + super.elementClicked(slotIndex, isDoubleClick, mouseX, mouseY); + this.selected = slotIndex; + } + + @Override + protected void drawSelectionBox(int p_148120_1_, int p_148120_2_, int p_148120_3_, int p_148120_4_) { int i1 = this.getSize(); Tessellator tessellator = Tessellator.getInstance(); WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - for (int j1 = 0; j1 < i1; ++j1) - { - + for(int j1 = 0; j1 < i1; ++j1) { + int k1 = p_148120_2_ + j1 * this.slotHeight + this.headerPadding; int l1 = this.slotHeight - 4; - if (k1 > this.bottom || k1 + l1 < this.top) - { + if(k1 > this.bottom || k1 + l1 < this.top) { this.func_178040_a(j1, p_148120_1_, k1); } - if (this.showSelectionBox && selected == j1) - { + if(this.showSelectionBox && selected == j1) { int i2 = this.left + (this.width / 2 - this.getListWidth() / 2); int j2 = this.left + this.width / 2 + this.getListWidth() / 2; GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); GlStateManager.disableTexture2D(); worldrenderer.startDrawingQuads(); worldrenderer.setColorOpaque_I(8421504); - worldrenderer.addVertexWithUV((double)i2, (double)(k1 + l1 + 2), 0.0D, 0.0D, 1.0D); - worldrenderer.addVertexWithUV((double)j2, (double)(k1 + l1 + 2), 0.0D, 1.0D, 1.0D); - worldrenderer.addVertexWithUV((double)j2, (double)(k1 - 2), 0.0D, 1.0D, 0.0D); - worldrenderer.addVertexWithUV((double)i2, (double)(k1 - 2), 0.0D, 0.0D, 0.0D); + worldrenderer.addVertexWithUV((double) i2, (double) (k1 + l1 + 2), 0.0D, 0.0D, 1.0D); + worldrenderer.addVertexWithUV((double) j2, (double) (k1 + l1 + 2), 0.0D, 1.0D, 1.0D); + worldrenderer.addVertexWithUV((double) j2, (double) (k1 - 2), 0.0D, 1.0D, 0.0D); + worldrenderer.addVertexWithUV((double) i2, (double) (k1 - 2), 0.0D, 0.0D, 0.0D); worldrenderer.setColorOpaque_I(0); - worldrenderer.addVertexWithUV((double)(i2 + 1), (double)(k1 + l1 + 1), 0.0D, 0.0D, 1.0D); - worldrenderer.addVertexWithUV((double)(j2 - 1), (double)(k1 + l1 + 1), 0.0D, 1.0D, 1.0D); - worldrenderer.addVertexWithUV((double)(j2 - 1), (double)(k1 - 1), 0.0D, 1.0D, 0.0D); - worldrenderer.addVertexWithUV((double)(i2 + 1), (double)(k1 - 1), 0.0D, 0.0D, 0.0D); + worldrenderer.addVertexWithUV((double) (i2 + 1), (double) (k1 + l1 + 1), 0.0D, 0.0D, 1.0D); + worldrenderer.addVertexWithUV((double) (j2 - 1), (double) (k1 + l1 + 1), 0.0D, 1.0D, 1.0D); + worldrenderer.addVertexWithUV((double) (j2 - 1), (double) (k1 - 1), 0.0D, 1.0D, 0.0D); + worldrenderer.addVertexWithUV((double) (i2 + 1), (double) (k1 - 1), 0.0D, 0.0D, 0.0D); tessellator.draw(); GlStateManager.enableTexture2D(); } - + this.drawSlot(j1, p_148120_1_, k1, l1, p_148120_3_, p_148120_4_); } } - - private List entries = new ArrayList(); - - public void clearEntries() { - entries = new ArrayList(); - } - - public void addEntry(FileInfo fileInfo, File image) { - entries.add(new GuiReplayListEntry(this, fileInfo, image)); - } + public void clearEntries() { + entries = new ArrayList(); + } - @Override - public GuiReplayListEntry getListEntry(int index) { - return entries.get(index); - } + public void addEntry(FileInfo fileInfo, File image) { + entries.add(new GuiReplayListEntry(this, fileInfo, image)); + } - @Override - protected int getSize() { - return entries.size(); - } + @Override + public GuiReplayListEntry getListEntry(int index) { + return entries.get(index); + } + + @Override + protected int getSize() { + return entries.size(); + } - @Override - public void handleMouseInput() - { - if (this.isMouseYWithinSlotBounds(this.mouseY)) - { - if (Mouse.isButtonDown(0)) - { - if (this.initialClickY == -1.0F) - { - int i2 = this.getScrollBarX(); + @Override + public void handleMouseInput() { + if(this.isMouseYWithinSlotBounds(this.mouseY)) { + if(Mouse.isButtonDown(0)) { + if(this.initialClickY == -1.0F) { + int i2 = this.getScrollBarX(); int i1 = i2 + 6; - + boolean flag = true; - if (this.mouseY >= this.top && this.mouseY <= this.bottom && this.mouseX <= i1) - { + if(this.mouseY >= this.top && this.mouseY <= this.bottom && this.mouseX <= i1) { int i = this.width / 2 - this.getListWidth() / 2; int j = this.width / 2 + this.getListWidth() / 2; - int k = this.mouseY - this.top - this.headerPadding + (int)this.amountScrolled - 4; + int k = this.mouseY - this.top - this.headerPadding + (int) this.amountScrolled - 4; int l = k / this.slotHeight; - if (this.mouseX >= i && this.mouseX <= j && l >= 0 && k >= 0 && l < this.getSize()) - { + if(this.mouseX >= i && this.mouseX <= j && l >= 0 && k >= 0 && l < this.getSize()) { boolean flag1 = l == this.selectedElement && Minecraft.getSystemTime() - this.lastClicked < 250L; this.elementClicked(l, flag1, this.mouseX, this.mouseY); this.selectedElement = l; this.lastClicked = Minecraft.getSystemTime(); - } - else if (this.mouseX >= i && this.mouseX <= j && k < 0) - { - this.func_148132_a(this.mouseX - i, this.mouseY - this.top + (int)this.amountScrolled - 4); + } else if(this.mouseX >= i && this.mouseX <= j && k < 0) { + this.func_148132_a(this.mouseX - i, this.mouseY - this.top + (int) this.amountScrolled - 4); flag = false; } - if (this.mouseX >= i2 && this.mouseX <= i1) - { + if(this.mouseX >= i2 && this.mouseX <= i1) { this.scrollMultiplier = -1.0F; int j1 = this.func_148135_f(); - if (j1 < 1) - { + if(j1 < 1) { j1 = 1; } - int k1 = (int)((float)((this.bottom - this.top) * (this.bottom - this.top)) / (float)this.getContentHeight()); + int k1 = (int) ((float) ((this.bottom - this.top) * (this.bottom - this.top)) / (float) this.getContentHeight()); k1 = MathHelper.clamp_int(k1, 32, this.bottom - this.top - 8); - this.scrollMultiplier /= (float)(this.bottom - this.top - k1) / (float)j1; - } - else - { + this.scrollMultiplier /= (float) (this.bottom - this.top - k1) / (float) j1; + } else { this.scrollMultiplier = 1.0F; } - if (flag) - { - this.initialClickY = (float)this.mouseY; - } - else - { + if(flag) { + this.initialClickY = (float) this.mouseY; + } else { this.initialClickY = -2.0F; } - } - else - { + } else { this.initialClickY = -2.0F; } + } else if(this.initialClickY >= 0.0F) { + this.amountScrolled -= ((float) this.mouseY - this.initialClickY) * this.scrollMultiplier; + this.initialClickY = (float) this.mouseY; } - else if (this.initialClickY >= 0.0F) - { - this.amountScrolled -= ((float)this.mouseY - this.initialClickY) * this.scrollMultiplier; - this.initialClickY = (float)this.mouseY; - } - } - else - { + } else { this.initialClickY = -1.0F; } int l1 = Mouse.getEventDWheel(); - if (l1 != 0) - { - if (l1 > 0) - { + if(l1 != 0) { + if(l1 > 0) { l1 = -1; - } - else if (l1 < 0) - { + } else if(l1 < 0) { l1 = 1; } - this.amountScrolled += (float)(l1 * this.slotHeight / 2); + this.amountScrolled += (float) (l1 * this.slotHeight / 2); } } } - + } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/elements/listeners/SelectionListener.java b/src/main/java/eu/crushedpixel/replaymod/gui/elements/listeners/SelectionListener.java index f19ea412..22627420 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/elements/listeners/SelectionListener.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/elements/listeners/SelectionListener.java @@ -1,7 +1,7 @@ package eu.crushedpixel.replaymod.gui.elements.listeners; -public abstract class SelectionListener { +public interface SelectionListener { + + void onSelectionChanged(int selectionIndex); - public abstract void onSelectionChanged(int selectionIndex); - } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/online/GuiLoginPrompt.java b/src/main/java/eu/crushedpixel/replaymod/gui/online/GuiLoginPrompt.java index 79b2a99e..1c87ecdc 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/online/GuiLoginPrompt.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/online/GuiLoginPrompt.java @@ -1,170 +1,163 @@ package eu.crushedpixel.replaymod.gui.online; -import java.awt.Color; -import java.io.IOException; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.gui.GuiTextField; - -import org.lwjgl.input.Keyboard; - import eu.crushedpixel.replaymod.gui.GuiConstants; import eu.crushedpixel.replaymod.gui.PasswordTextField; import eu.crushedpixel.replaymod.online.authentication.AuthenticationHandler; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.GuiTextField; +import org.lwjgl.input.Keyboard; + +import java.awt.*; +import java.io.IOException; public class GuiLoginPrompt extends GuiScreen { - private static final int EMPTY = 0; - private static final int LOGGING_IN = 1; - private static final int INVALID_LOGIN = 2; - private static final int NO_CONNECTION = 3; - - private GuiScreen parent, successScreen; - - private int textState = 0; + private static final int EMPTY = 0; + private static final int LOGGING_IN = 1; + private static final int INVALID_LOGIN = 2; + private static final int NO_CONNECTION = 3; + private static Minecraft mc = Minecraft.getMinecraft(); + private GuiScreen parent, successScreen; + private int textState = 0; + private GuiTextField username; + private PasswordTextField password; + private GuiButton loginButton; + private GuiButton cancelButton; + private int lastMouseX, lastMouseY; + private float lastPartialTicks; - private static Minecraft mc = Minecraft.getMinecraft(); + public GuiLoginPrompt(GuiScreen parent, GuiScreen successScreen) { + this.parent = parent; + this.successScreen = successScreen; + } - private GuiTextField username; - private PasswordTextField password; - private GuiButton loginButton; - private GuiButton cancelButton; + @Override + public void initGui() { + Keyboard.enableRepeatEvents(true); - public GuiLoginPrompt(GuiScreen parent, GuiScreen successScreen) { - this.parent = parent; - this.successScreen = successScreen; - } + username = new GuiTextField(GuiConstants.REPLAY_CENTER_LOGIN_TEXT_ID, fontRendererObj, this.width / 2 - 45, 30, 145, 20); + username.setEnabled(true); + username.setFocused(true); - @Override - public void initGui() { - Keyboard.enableRepeatEvents(true); + password = new PasswordTextField(GuiConstants.REPLAY_CENTER_PASSWORD_TEXT_ID, fontRendererObj, this.width / 2 - 45, 60, 145, 20); + password.setEnabled(true); + password.setFocused(false); - username = new GuiTextField(GuiConstants.REPLAY_CENTER_LOGIN_TEXT_ID, fontRendererObj, this.width/2 - 45, 30, 145, 20); - username.setEnabled(true); - username.setFocused(true); + loginButton = new GuiButton(GuiConstants.LOGIN_OKAY_BUTTON, this.width / 2 - 150 - 2, 110, "Login"); + loginButton.width = 150; + loginButton.enabled = false; + buttonList.add(loginButton); - password = new PasswordTextField(GuiConstants.REPLAY_CENTER_PASSWORD_TEXT_ID, fontRendererObj, this.width/2 - 45, 60, 145, 20); - password.setEnabled(true); - password.setFocused(false); + cancelButton = new GuiButton(GuiConstants.LOGIN_CANCEL_BUTTON, this.width / 2 + 2, 110, "Cancel"); + cancelButton.width = 150; + buttonList.add(cancelButton); + } - loginButton = new GuiButton(GuiConstants.LOGIN_OKAY_BUTTON, this.width/2 - 150 - 2, 110, "Login"); - loginButton.width = 150; - loginButton.enabled = false; - buttonList.add(loginButton); + @Override + protected void actionPerformed(GuiButton button) throws IOException { + if(button.id == GuiConstants.LOGIN_OKAY_BUTTON) { + if(button.enabled) { + //Authenticate + textState = LOGGING_IN; - cancelButton = new GuiButton(GuiConstants.LOGIN_CANCEL_BUTTON, this.width/2 + 2, 110, "Cancel"); - cancelButton.width = 150; - buttonList.add(cancelButton); - } + new Thread(new Runnable() { + @Override + public void run() { + switch(AuthenticationHandler.authenticate(username.getText(), password.getText())) { + case AuthenticationHandler.SUCCESS: + textState = EMPTY; + mc.addScheduledTask(new Runnable() { + @Override + public void run() { + mc.displayGuiScreen(successScreen); + } + }); + break; + case AuthenticationHandler.INVALID: + textState = INVALID_LOGIN; + break; + case AuthenticationHandler.NO_CONNECTION: + textState = NO_CONNECTION; + break; + } + } + }).start(); + } + } else if(button.id == GuiConstants.LOGIN_CANCEL_BUTTON) { + mc.displayGuiScreen(parent); + } + } - @Override - protected void actionPerformed(GuiButton button) throws IOException { - if(button.id == GuiConstants.LOGIN_OKAY_BUTTON) { - if(button.enabled) { - //Authenticate - textState = LOGGING_IN; - - new Thread(new Runnable() { - @Override - public void run() { - switch(AuthenticationHandler.authenticate(username.getText(), password.getText())) { - case AuthenticationHandler.SUCCESS: - textState = EMPTY; - mc.addScheduledTask(new Runnable() { - @Override - public void run() { - mc.displayGuiScreen(successScreen); - } - }); - break; - case AuthenticationHandler.INVALID: - textState = INVALID_LOGIN; - break; - case AuthenticationHandler.NO_CONNECTION: - textState = NO_CONNECTION; - break; - } - } - }).start(); - } - } else if(button.id == GuiConstants.LOGIN_CANCEL_BUTTON) { - mc.displayGuiScreen(parent); - } - } + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + lastMouseX = mouseX; + lastMouseY = mouseY; + lastPartialTicks = partialTicks; - private int lastMouseX, lastMouseY; - private float lastPartialTicks; - - @Override - public void drawScreen(int mouseX, int mouseY, float partialTicks) { - lastMouseX = mouseX; - lastMouseY = mouseY; - lastPartialTicks = partialTicks; - - this.drawDefaultBackground(); - drawCenteredString(fontRendererObj, "Login to ReplayMod.com", this.width/2, 10, Color.WHITE.getRGB()); + this.drawDefaultBackground(); + drawCenteredString(fontRendererObj, "Login to ReplayMod.com", this.width / 2, 10, Color.WHITE.getRGB()); - drawString(fontRendererObj, "Username", this.width/2 - 100, 37, Color.WHITE.getRGB()); - username.drawTextBox(); + drawString(fontRendererObj, "Username", this.width / 2 - 100, 37, Color.WHITE.getRGB()); + username.drawTextBox(); - drawString(fontRendererObj, "Password", this.width/2 - 100, 67, Color.WHITE.getRGB()); - password.drawTextBox(); - - switch(textState) { - case INVALID_LOGIN: - drawCenteredString(fontRendererObj, "Incorrect username or password.", this.width/2, 92, Color.RED.getRGB()); - break; - case LOGGING_IN: - drawCenteredString(fontRendererObj, "Logging in...", this.width/2, 92, Color.WHITE.getRGB()); - break; - case NO_CONNECTION: - drawCenteredString(fontRendererObj, "Could not connect to ReplayMod.com", this.width/2, 92, Color.RED.getRGB()); - break; - } - super.drawScreen(mouseX, mouseY, partialTicks); - } + drawString(fontRendererObj, "Password", this.width / 2 - 100, 67, Color.WHITE.getRGB()); + password.drawTextBox(); - @Override - public void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { - super.mouseClicked(mouseX, mouseY, mouseButton); - username.mouseClicked(mouseX, mouseY, mouseButton); - password.mouseClicked(mouseX, mouseY, mouseButton); - } + switch(textState) { + case INVALID_LOGIN: + drawCenteredString(fontRendererObj, "Incorrect username or password.", this.width / 2, 92, Color.RED.getRGB()); + break; + case LOGGING_IN: + drawCenteredString(fontRendererObj, "Logging in...", this.width / 2, 92, Color.WHITE.getRGB()); + break; + case NO_CONNECTION: + drawCenteredString(fontRendererObj, "Could not connect to ReplayMod.com", this.width / 2, 92, Color.RED.getRGB()); + break; + } + super.drawScreen(mouseX, mouseY, partialTicks); + } - @Override - public void updateScreen() { - username.updateCursorCounter(); - password.updateCursorCounter(); - } + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { + super.mouseClicked(mouseX, mouseY, mouseButton); + username.mouseClicked(mouseX, mouseY, mouseButton); + password.mouseClicked(mouseX, mouseY, mouseButton); + } - @Override - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); - } + @Override + public void updateScreen() { + username.updateCursorCounter(); + password.updateCursorCounter(); + } - @Override - protected void keyTyped(char typedChar, int keyCode) throws IOException { - if(keyCode == Keyboard.KEY_TAB) { - if(password.isFocused()) { - password.setFocused(false); - username.setFocused(true); - } else { - username.setFocused(false); - password.setFocused(true); - } - return; - } - if(keyCode == 28) { //Enter key - actionPerformed(loginButton); - return; - } - if(username.isFocused()) { - username.textboxKeyTyped(typedChar, keyCode); - } else if(password.isFocused()) { - password.textboxKeyTyped(typedChar, keyCode); - } - loginButton.enabled = username.getText().length() > 0 && password.getText().length() > 0; - } + @Override + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); + } + + @Override + protected void keyTyped(char typedChar, int keyCode) throws IOException { + if(keyCode == Keyboard.KEY_TAB) { + if(password.isFocused()) { + password.setFocused(false); + username.setFocused(true); + } else { + username.setFocused(false); + password.setFocused(true); + } + return; + } + if(keyCode == 28) { //Enter key + actionPerformed(loginButton); + return; + } + if(username.isFocused()) { + username.textboxKeyTyped(typedChar, keyCode); + } else if(password.isFocused()) { + password.textboxKeyTyped(typedChar, keyCode); + } + loginButton.enabled = username.getText().length() > 0 && password.getText().length() > 0; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/online/GuiReplayCenter.java b/src/main/java/eu/crushedpixel/replaymod/gui/online/GuiReplayCenter.java index 437f7251..76c6018f 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/online/GuiReplayCenter.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/online/GuiReplayCenter.java @@ -1,22 +1,6 @@ package eu.crushedpixel.replaymod.gui.online; -import java.awt.Color; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiMainMenu; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.gui.GuiYesNo; -import net.minecraft.client.gui.GuiYesNoCallback; -import net.minecraft.client.resources.I18n; - -import org.lwjgl.input.Keyboard; - import eu.crushedpixel.replaymod.ReplayMod; -import eu.crushedpixel.replaymod.api.client.ApiException; import eu.crushedpixel.replaymod.api.client.SearchPagination; import eu.crushedpixel.replaymod.api.client.SearchQuery; import eu.crushedpixel.replaymod.api.client.holders.FileInfo; @@ -24,247 +8,251 @@ import eu.crushedpixel.replaymod.gui.GuiConstants; import eu.crushedpixel.replaymod.gui.elements.GuiReplayListExtended; import eu.crushedpixel.replaymod.gui.replayviewer.GuiReplayViewer; import eu.crushedpixel.replaymod.online.authentication.AuthenticationHandler; +import net.minecraft.client.gui.*; +import net.minecraft.client.resources.I18n; +import org.lwjgl.input.Keyboard; + +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; public class GuiReplayCenter extends GuiScreen implements GuiYesNoCallback { - private enum Tab { - RECENT_FILES, BEST_FILES, MY_FILES, SEARCH; - } + private static final SearchQuery recentFileSearchQuery = new SearchQuery(false, null, null, null, null, null, + null, null, null, null); + private static final SearchQuery bestFileSearchQuery = new SearchQuery(true, null, null, null, null, null, + null, null, null, null); + private static final int LOGOUT_CALLBACK_ID = 1; + private final SearchPagination recentFilePagination = new SearchPagination(recentFileSearchQuery); + private final SearchPagination bestFilePagination = new SearchPagination(bestFileSearchQuery); + private GuiReplayListExtended currentList; + private ReplayFileList recentFileList, bestFileList, myFileList, searchFileList; + private Tab currentTab = Tab.RECENT_FILES; + private SearchPagination myFilePagination; - private GuiReplayListExtended currentList; + public static GuiYesNo getYesNoGui(GuiYesNoCallback p_152129_0_, int p_152129_2_) { + String s1 = I18n.format("Do you really want to log out?", new Object[0]); + GuiYesNo guiyesno = new GuiYesNo(p_152129_0_, s1, "", "Logout", "Cancel", p_152129_2_); + return guiyesno; + } - private ReplayFileList recentFileList, bestFileList, myFileList, searchFileList; + @Override + public void initGui() { + Keyboard.enableRepeatEvents(true); - private Tab currentTab = Tab.RECENT_FILES; + if(AuthenticationHandler.isAuthenticated()) { + SearchQuery query = new SearchQuery(); + query.auth = AuthenticationHandler.getKey(); + query.order = false; + myFilePagination = new SearchPagination(query); + } - private static final SearchQuery recentFileSearchQuery = new SearchQuery(false, null, null, null, null, null, - null, null, null, null); + //Top Button Bar + List buttonBar = new ArrayList(); - private static final SearchQuery bestFileSearchQuery = new SearchQuery(true, null, null, null, null, null, - null, null, null, null); + GuiButton recentButton = new GuiButton(GuiConstants.CENTER_RECENT_BUTTON, 20, 30, "Newest Replays"); + buttonBar.add(recentButton); - private final SearchPagination recentFilePagination = new SearchPagination(recentFileSearchQuery); - private final SearchPagination bestFilePagination = new SearchPagination(bestFileSearchQuery); - private SearchPagination myFilePagination; + GuiButton bestButton = new GuiButton(GuiConstants.CENTER_BEST_BUTTON, 20, 30, "Best Replays"); + buttonBar.add(bestButton); - @Override - public void initGui() { - Keyboard.enableRepeatEvents(true); + GuiButton ownReplayButton = new GuiButton(GuiConstants.CENTER_MY_REPLAYS_BUTTON, 20, 30, "My Replays"); + ownReplayButton.enabled = AuthenticationHandler.isAuthenticated(); + buttonBar.add(ownReplayButton); - if(AuthenticationHandler.isAuthenticated()) { - SearchQuery query = new SearchQuery(); - query.auth = AuthenticationHandler.getKey(); - query.order = false; - myFilePagination = new SearchPagination(query); - } + GuiButton searchButton = new GuiButton(GuiConstants.CENTER_SEARCH_BUTTON, 20, 30, "Search"); + buttonBar.add(searchButton); - //Top Button Bar - List buttonBar = new ArrayList(); + int i = 0; + for(GuiButton b : buttonBar) { + int w = this.width - 30; + int w2 = w / buttonBar.size(); - GuiButton recentButton = new GuiButton(GuiConstants.CENTER_RECENT_BUTTON, 20, 30, "Newest Replays"); - buttonBar.add(recentButton); + int x = 15 + (w2 * i); + b.xPosition = x + 2; + b.yPosition = 20; + b.width = w2 - 4; - GuiButton bestButton = new GuiButton(GuiConstants.CENTER_BEST_BUTTON, 20, 30, "Best Replays"); - buttonBar.add(bestButton); + buttonList.add(b); - GuiButton ownReplayButton = new GuiButton(GuiConstants.CENTER_MY_REPLAYS_BUTTON, 20, 30, "My Replays"); - ownReplayButton.enabled = AuthenticationHandler.isAuthenticated(); - buttonBar.add(ownReplayButton); + i++; + } - GuiButton searchButton = new GuiButton(GuiConstants.CENTER_SEARCH_BUTTON, 20, 30, "Search"); - buttonBar.add(searchButton); + //Bottom Button Bar (dat alliteration) + List bottomBar = new ArrayList(); - int i = 0; - for(GuiButton b : buttonBar) { - int w = this.width - 30; - int w2 = w/buttonBar.size(); + GuiButton exitButton = new GuiButton(GuiConstants.CENTER_BACK_BUTTON, 20, 20, "Main Menu"); + bottomBar.add(exitButton); - int x = 15+(w2*i); - b.xPosition = x+2; - b.yPosition = 20; - b.width = w2-4; + GuiButton managerButton = new GuiButton(GuiConstants.CENTER_MANAGER_BUTTON, 20, 20, "Replay Viewer"); + bottomBar.add(managerButton); - buttonList.add(b); + GuiButton logoutButton = new GuiButton(GuiConstants.CENTER_LOGOUT_BUTTON, 20, 20, "Logout"); + bottomBar.add(logoutButton); - i++; - } + i = 0; + for(GuiButton b : bottomBar) { + int w = this.width - 30; + int w2 = w / bottomBar.size(); - //Bottom Button Bar (dat alliteration) - List bottomBar = new ArrayList(); + int x = 15 + (w2 * i); + b.xPosition = x + 2; + b.yPosition = height - 30; + b.width = w2 - 4; - GuiButton exitButton = new GuiButton(GuiConstants.CENTER_BACK_BUTTON, 20, 20, "Main Menu"); - bottomBar.add(exitButton); + buttonList.add(b); - GuiButton managerButton = new GuiButton(GuiConstants.CENTER_MANAGER_BUTTON, 20, 20, "Replay Viewer"); - bottomBar.add(managerButton); + i++; + } - GuiButton logoutButton = new GuiButton(GuiConstants.CENTER_LOGOUT_BUTTON, 20, 20, "Logout"); - bottomBar.add(logoutButton); + showOnlineRecent(); + } - i = 0; - for(GuiButton b : bottomBar) { - int w = this.width - 30; - int w2 = w/bottomBar.size(); + @Override + protected void actionPerformed(GuiButton button) throws java.io.IOException { + if(!button.enabled) return; + if(button.id == GuiConstants.CENTER_BACK_BUTTON) { + mc.displayGuiScreen(new GuiMainMenu()); + } else if(button.id == GuiConstants.CENTER_LOGOUT_BUTTON) { + mc.displayGuiScreen(getYesNoGui(this, LOGOUT_CALLBACK_ID)); + } else if(button.id == GuiConstants.CENTER_MANAGER_BUTTON) { + mc.displayGuiScreen(new GuiReplayViewer()); + } else if(button.id == GuiConstants.CENTER_RECENT_BUTTON) { + showOnlineRecent(); + } else if(button.id == GuiConstants.CENTER_BEST_BUTTON) { + showOnlineBest(); + } else if(button.id == GuiConstants.CENTER_MY_REPLAYS_BUTTON) { + showOnlineOwnFiles(); + } else if(button.id == GuiConstants.CENTER_SEARCH_BUTTON) { - int x = 15+(w2*i); - b.xPosition = x+2; - b.yPosition = height-30; - b.width = w2-4; + } + } - buttonList.add(b); + @Override + public void confirmClicked(boolean result, int id) { + if(id == LOGOUT_CALLBACK_ID) { + if(result) { + mc.addScheduledTask(new Runnable() { + @Override + public void run() { + AuthenticationHandler.logout(); + mc.displayGuiScreen(new GuiMainMenu()); + } + }); + } else { + mc.displayGuiScreen(this); + } + } + } - i++; - } + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + this.drawDefaultBackground(); + this.drawCenteredString(fontRendererObj, "Replay Center", this.width / 2, 8, Color.WHITE.getRGB()); - showOnlineRecent(); - } + if(currentList != null) { + currentList.drawScreen(mouseX, mouseY, partialTicks); + } - @Override - protected void actionPerformed(GuiButton button) throws java.io.IOException { - if(!button.enabled) return; - if(button.id == GuiConstants.CENTER_BACK_BUTTON) { - mc.displayGuiScreen(new GuiMainMenu()); - } else if(button.id == GuiConstants.CENTER_LOGOUT_BUTTON) { - mc.displayGuiScreen(getYesNoGui(this, LOGOUT_CALLBACK_ID)); - } else if(button.id == GuiConstants.CENTER_MANAGER_BUTTON) { - mc.displayGuiScreen(new GuiReplayViewer()); - } else if(button.id == GuiConstants.CENTER_RECENT_BUTTON) { - showOnlineRecent(); - } else if(button.id == GuiConstants.CENTER_BEST_BUTTON) { - showOnlineBest(); - } else if(button.id == GuiConstants.CENTER_MY_REPLAYS_BUTTON) { - showOnlineOwnFiles(); - } else if(button.id == GuiConstants.CENTER_SEARCH_BUTTON) { + super.drawScreen(mouseX, mouseY, partialTicks); + } - } - } + @Override + public void handleMouseInput() throws IOException { + super.handleMouseInput(); + if(currentList != null) { + this.currentList.handleMouseInput(); + } + } - private static final int LOGOUT_CALLBACK_ID = 1; - @Override - public void confirmClicked(boolean result, int id) { - if(id == LOGOUT_CALLBACK_ID) { - if(result) { - mc.addScheduledTask(new Runnable() { - @Override - public void run() { - AuthenticationHandler.logout(); - mc.displayGuiScreen(new GuiMainMenu()); - } - }); - } else { - mc.displayGuiScreen(this); - } - } - } + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { + super.mouseClicked(mouseX, mouseY, mouseButton); + if(currentList != null) { + this.currentList.mouseClicked(mouseX, mouseY, mouseButton); + } + } - public static GuiYesNo getYesNoGui(GuiYesNoCallback p_152129_0_, int p_152129_2_) { - String s1 = I18n.format("Do you really want to log out?", new Object[0]); - GuiYesNo guiyesno = new GuiYesNo(p_152129_0_, s1, "", "Logout", "Cancel", p_152129_2_); - return guiyesno; - } + @Override + protected void mouseReleased(int mouseX, int mouseY, int state) { + super.mouseReleased(mouseX, mouseY, state); + if(currentList != null) { + this.currentList.mouseReleased(mouseX, mouseY, state); + } + } - @Override - public void drawScreen(int mouseX, int mouseY, float partialTicks) { - this.drawDefaultBackground(); - this.drawCenteredString(fontRendererObj, "Replay Center", this.width/2, 8, Color.WHITE.getRGB()); + @Override + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); + } - if(currentList != null) { - currentList.drawScreen(mouseX, mouseY, partialTicks); - } + private void updateCurrentList(ReplayFileList list, SearchPagination pagination) { + currentList = list; + if(currentList == null) { + currentList = new ReplayFileList(mc, width, height, 50, height - 40, 36); + } else { + currentList.clearEntries(); + currentList.width = width; + currentList.height = height; + currentList.top = 50; + currentList.bottom = height - 40; + } - super.drawScreen(mouseX, mouseY, partialTicks); - } + if(pagination.getLoadedPages() < 0) { + pagination.fetchPage(); + } - @Override - public void handleMouseInput() throws IOException { - super.handleMouseInput(); - if(currentList != null) { - this.currentList.handleMouseInput(); - } - } + for(FileInfo i : pagination.getFiles()) { + try { + File tmp = null; + if(i.hasThumbnail()) { + tmp = File.createTempFile("thumb_online_" + i.getId(), "jpg"); + ReplayMod.apiClient.downloadThumbnail(i.getId(), tmp); + } + currentList.addEntry(i, tmp); + } catch(Exception e) { + e.printStackTrace(); + } + } + } - @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { - super.mouseClicked(mouseX, mouseY, mouseButton); - if(currentList != null) { - this.currentList.mouseClicked(mouseX, mouseY, mouseButton); - } - } + public void showOnlineRecent() { + Thread t = new Thread(new Runnable() { + @Override + public void run() { + updateCurrentList(recentFileList, recentFilePagination); + currentTab = Tab.RECENT_FILES; + } + }); + t.start(); + } - @Override - protected void mouseReleased(int mouseX, int mouseY, int state) { - super.mouseReleased(mouseX, mouseY, state); - if(currentList != null) { - this.currentList.mouseReleased(mouseX, mouseY, state); - } - } + public void showOnlineBest() { + Thread t = new Thread(new Runnable() { + @Override + public void run() { + updateCurrentList(bestFileList, bestFilePagination); + currentTab = Tab.BEST_FILES; + } + }); + t.start(); + } - @Override - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); - } + public void showOnlineOwnFiles() { + if(!AuthenticationHandler.isAuthenticated() || myFilePagination == null) return; + Thread t = new Thread(new Runnable() { + @Override + public void run() { + updateCurrentList(myFileList, myFilePagination); + currentTab = Tab.MY_FILES; + } + }); + t.start(); + } - private void updateCurrentList(ReplayFileList list, SearchPagination pagination) { - currentList = list; - if(currentList == null) { - currentList = new ReplayFileList(mc, width, height, 50, height-40, 36); - } else { - currentList.clearEntries(); - currentList.width = width; - currentList.height = height; - currentList.top = 50; - currentList.bottom = height-40; - } - - if(pagination.getLoadedPages() < 0) { - pagination.fetchPage(); - } - - for(FileInfo i : pagination.getFiles()) { - try { - File tmp = null; - if(i.hasThumbnail()) { - tmp = File.createTempFile("thumb_online_"+i.getId(), "jpg"); - ReplayMod.apiClient.downloadThumbnail(i.getId(), tmp); - } - currentList.addEntry(i, tmp); - } catch(Exception e) { - e.printStackTrace(); - } - } - } - - public void showOnlineRecent() { - Thread t = new Thread(new Runnable() { - @Override - public void run() { - updateCurrentList(recentFileList, recentFilePagination); - currentTab = Tab.RECENT_FILES; - } - }); - t.start(); - } - - public void showOnlineBest() { - Thread t = new Thread(new Runnable() { - @Override - public void run() { - updateCurrentList(bestFileList, bestFilePagination); - currentTab = Tab.BEST_FILES; - } - }); - t.start(); - } - - public void showOnlineOwnFiles() { - if(!AuthenticationHandler.isAuthenticated() || myFilePagination == null) return; - Thread t = new Thread(new Runnable() { - @Override - public void run() { - updateCurrentList(myFileList, myFilePagination); - currentTab = Tab.MY_FILES; - } - }); - t.start(); - } + private enum Tab { + RECENT_FILES, BEST_FILES, MY_FILES, SEARCH; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/online/GuiUploadFile.java b/src/main/java/eu/crushedpixel/replaymod/gui/online/GuiUploadFile.java index 5567d566..5f49647b 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/online/GuiUploadFile.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/online/GuiUploadFile.java @@ -1,36 +1,6 @@ package eu.crushedpixel.replaymod.gui.online; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.image.BufferedImage; -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.regex.Pattern; - -import javax.imageio.ImageIO; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Gui; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiMainMenu; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.gui.GuiTextField; -import net.minecraft.client.renderer.texture.DynamicTexture; -import net.minecraft.util.ResourceLocation; - -import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; -import org.apache.commons.compress.archivers.zip.ZipFile; -import org.apache.commons.io.FilenameUtils; -import org.lwjgl.input.Keyboard; - import com.google.gson.Gson; - import eu.crushedpixel.replaymod.api.client.ApiException; import eu.crushedpixel.replaymod.api.client.FileUploader; import eu.crushedpixel.replaymod.api.client.holders.Category; @@ -42,361 +12,374 @@ import eu.crushedpixel.replaymod.recording.ReplayMetaData; import eu.crushedpixel.replaymod.reflection.MCPNames; import eu.crushedpixel.replaymod.utils.ImageUtils; import eu.crushedpixel.replaymod.utils.ResourceHelper; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.GuiTextField; +import net.minecraft.client.renderer.texture.DynamicTexture; +import net.minecraft.util.ResourceLocation; +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.ZipFile; +import org.apache.commons.io.FilenameUtils; +import org.lwjgl.input.Keyboard; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.*; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; public class GuiUploadFile extends GuiScreen { - private GuiTextField fileTitleInput, tagInput, messageTextField, tagPlaceholder; - private GuiButton categoryButton, startUploadButton, cancelUploadButton, backButton; + private static final Pattern p = Pattern.compile("[^a-z0-9 \\-_]", Pattern.CASE_INSENSITIVE); + private static final Pattern pt = Pattern.compile("[^a-z0-9,]", Pattern.CASE_INSENSITIVE); + private final ResourceLocation textureResource; + private GuiTextField fileTitleInput, tagInput, messageTextField, tagPlaceholder; + private GuiButton categoryButton, startUploadButton, cancelUploadButton, backButton; + private Gson gson = new Gson(); + private File replayFile; + private ReplayMetaData metaData; + private BufferedImage thumb; + private FileUploader uploader = new FileUploader(); + private Category category = Category.MINIGAME; + private DynamicTexture dynTex = null; + private Minecraft mc = Minecraft.getMinecraft(); + private GuiReplayViewer parent; - private Gson gson = new Gson(); + public GuiUploadFile(File file, GuiReplayViewer parent) { + this.parent = parent; - private File replayFile; - private ReplayMetaData metaData; - private BufferedImage thumb; + this.textureResource = new ResourceLocation("upload_thumbs/" + FilenameUtils.getBaseName(file.getAbsolutePath())); + dynTex = null; - private FileUploader uploader = new FileUploader(); + boolean correctFile = false; + this.replayFile = file; - private Category category = Category.MINIGAME; + if(("." + FilenameUtils.getExtension(file.getAbsolutePath())).equals(ConnectionEventHandler.ZIP_FILE_EXTENSION)) { + ZipFile archive = null; + try { + archive = new ZipFile(file); + ZipArchiveEntry recfile = archive.getEntry("recording" + ConnectionEventHandler.TEMP_FILE_EXTENSION); + ZipArchiveEntry metadata = archive.getEntry("metaData" + ConnectionEventHandler.JSON_FILE_EXTENSION); - private final ResourceLocation textureResource; - private DynamicTexture dynTex = null; + ZipArchiveEntry image = archive.getEntry("thumb"); + BufferedImage img = null; + if(image != null) { + InputStream is = archive.getInputStream(image); + is.skip(7); + BufferedImage bimg = ImageIO.read(is); + if(bimg != null) { + thumb = ImageUtils.scaleImage(bimg, new Dimension(1280, 720)); + } + } - private Minecraft mc = Minecraft.getMinecraft(); + InputStream is = archive.getInputStream(metadata); + BufferedReader br = new BufferedReader(new InputStreamReader(is)); + String json = br.readLine(); - private static final Pattern p = Pattern.compile("[^a-z0-9 \\-_]", Pattern.CASE_INSENSITIVE); - private static final Pattern pt = Pattern.compile("[^a-z0-9,]", Pattern.CASE_INSENSITIVE); + metaData = gson.fromJson(json, ReplayMetaData.class); - private GuiReplayViewer parent; - - public GuiUploadFile(File file, GuiReplayViewer parent) { - this.parent = parent; - - this.textureResource = new ResourceLocation("upload_thumbs/"+FilenameUtils.getBaseName(file.getAbsolutePath())); - dynTex = null; + archive.close(); + correctFile = true; + } catch(Exception e) { + e.printStackTrace(); + } finally { + if(archive != null) { + try { + archive.close(); + } catch(IOException e) { + } + } + } + } - boolean correctFile = false; - this.replayFile = file; + if(!correctFile) { + System.out.println("Invalid file provided to upload"); + mc.displayGuiScreen(parent); //TODO: Error message + replayFile = null; + return; + } - if(("."+FilenameUtils.getExtension(file.getAbsolutePath())).equals(ConnectionEventHandler.ZIP_FILE_EXTENSION)) { - ZipFile archive = null; - try { - archive = new ZipFile(file); - ZipArchiveEntry recfile = archive.getEntry("recording"+ConnectionEventHandler.TEMP_FILE_EXTENSION); - ZipArchiveEntry metadata = archive.getEntry("metaData"+ConnectionEventHandler.JSON_FILE_EXTENSION); + //If thumb is null, set image to placeholder + if(thumb == null) { + try { + thumb = ImageIO.read(MCPNames.class.getClassLoader().getResourceAsStream("default_thumb.jpg")); + } catch(Exception e) { + e.printStackTrace(); + } + } + } - ZipArchiveEntry image = archive.getEntry("thumb"); - BufferedImage img = null; - if(image != null) { - InputStream is = archive.getInputStream(image); - is.skip(7); - BufferedImage bimg = ImageIO.read(is); - if(bimg != null) { - thumb = ImageUtils.scaleImage(bimg, new Dimension(1280, 720)); - } - } + @Override + public void initGui() { + if(replayFile == null) return; - InputStream is = archive.getInputStream(metadata); - BufferedReader br = new BufferedReader(new InputStreamReader(is)); - String json = br.readLine(); + if(fileTitleInput == null) { + fileTitleInput = new GuiTextField(GuiConstants.UPLOAD_NAME_INPUT, fontRendererObj, (this.width / 2) + 20 + 10, 21, Math.min(200, this.width - 20 - 260), 20); + String fname = FilenameUtils.getBaseName(replayFile.getAbsolutePath()); + fileTitleInput.setText(fname); + fileTitleInput.setMaxStringLength(30); + } else { + fileTitleInput.xPosition = (this.width / 2) + 20 + 10; + //fileTitleInput.yPosition = 21; + fileTitleInput.width = Math.min(200, this.width - 20 - 260); + //fileTitleInput.height = 20; + } - metaData = gson.fromJson(json, ReplayMetaData.class); + if(categoryButton == null) { + categoryButton = new GuiButton(GuiConstants.UPLOAD_CATEGORY_BUTTON, (this.width / 2) + 20 + 10 - 1, 80, "Category: " + category.toNiceString()); + categoryButton.width = Math.min(202, this.width - 20 - 260 + 2); + buttonList.add(categoryButton); + } else { + categoryButton.xPosition = (this.width / 2) + 20 + 10 - 1; + } - archive.close(); - correctFile = true; - } catch(Exception e) { - e.printStackTrace(); - } finally { - if(archive != null) { - try { - archive.close(); - } catch (IOException e) {} - } - } - } + if(startUploadButton == null) { + List bottomBar = new ArrayList(); + startUploadButton = new GuiButton(GuiConstants.UPLOAD_START_BUTTON, 0, 0, "Start Upload"); + bottomBar.add(startUploadButton); - if(!correctFile) { - System.out.println("Invalid file provided to upload"); - mc.displayGuiScreen(parent); //TODO: Error message - replayFile = null; - return; - } + cancelUploadButton = new GuiButton(GuiConstants.UPLOAD_CANCEL_BUTTON, 0, 0, "Cancel Upload"); + cancelUploadButton.enabled = false; + bottomBar.add(cancelUploadButton); - //If thumb is null, set image to placeholder - if(thumb == null) { - try { - thumb = ImageIO.read(MCPNames.class.getClassLoader().getResourceAsStream("default_thumb.jpg")); - } catch(Exception e) { - e.printStackTrace(); - } - } - } + backButton = new GuiButton(GuiConstants.UPLOAD_BACK_BUTTON, 0, 0, "Back"); + bottomBar.add(backButton); - @Override - public void initGui() { - if(replayFile == null) return; + int i = 0; + for(GuiButton b : bottomBar) { + int w = this.width - 30; + int w2 = w / bottomBar.size(); - if(fileTitleInput == null) { - fileTitleInput = new GuiTextField(GuiConstants.UPLOAD_NAME_INPUT, fontRendererObj, (this.width/2)+20+10, 21, Math.min(200, this.width-20-260), 20); - String fname = FilenameUtils.getBaseName(replayFile.getAbsolutePath()); - fileTitleInput.setText(fname); - fileTitleInput.setMaxStringLength(30); - } else { - fileTitleInput.xPosition = (this.width/2)+20+10; - //fileTitleInput.yPosition = 21; - fileTitleInput.width = Math.min(200, this.width-20-260); - //fileTitleInput.height = 20; - } + int x = 15 + (w2 * i); + b.xPosition = x + 2; + b.yPosition = height - 30; + b.width = w2 - 4; - if(categoryButton == null) { - categoryButton = new GuiButton(GuiConstants.UPLOAD_CATEGORY_BUTTON, (this.width/2)+20+10-1, 80, "Category: "+category.toNiceString()); - categoryButton.width = Math.min(202, this.width-20-260+2); - buttonList.add(categoryButton); - } else { - categoryButton.xPosition = (this.width/2)+20+10-1; - } + buttonList.add(b); - if(startUploadButton == null) { - List bottomBar = new ArrayList(); - startUploadButton = new GuiButton(GuiConstants.UPLOAD_START_BUTTON, 0, 0, "Start Upload"); - bottomBar.add(startUploadButton); + i++; + } + } else { + List bottomBar = new ArrayList(); - cancelUploadButton = new GuiButton(GuiConstants.UPLOAD_CANCEL_BUTTON, 0, 0, "Cancel Upload"); - cancelUploadButton.enabled = false; - bottomBar.add(cancelUploadButton); + bottomBar.add(startUploadButton); + bottomBar.add(cancelUploadButton); + bottomBar.add(backButton); - backButton = new GuiButton(GuiConstants.UPLOAD_BACK_BUTTON, 0, 0, "Back"); - bottomBar.add(backButton); + int i = 0; + for(GuiButton b : bottomBar) { + int w = this.width - 30; + int w2 = w / bottomBar.size(); - int i = 0; - for(GuiButton b : bottomBar) { - int w = this.width - 30; - int w2 = w/bottomBar.size(); + int x = 15 + (w2 * i); + b.xPosition = x + 2; + b.yPosition = height - 30; + b.width = w2 - 4; - int x = 15+(w2*i); - b.xPosition = x+2; - b.yPosition = height-30; - b.width = w2-4; + buttonList.add(b); - buttonList.add(b); + i++; + } + } - i++; - } - } else { - List bottomBar = new ArrayList(); + if(messageTextField == null) { + messageTextField = new GuiTextField(GuiConstants.UPLOAD_INFO_FIELD, fontRendererObj, 20, height - 80, width - 40, 20); + messageTextField.setEnabled(true); + messageTextField.setFocused(false); + messageTextField.setMaxStringLength(Integer.MAX_VALUE); + } else { + messageTextField.yPosition = height - 80; + messageTextField.width = width - 40; + } - bottomBar.add(startUploadButton); - bottomBar.add(cancelUploadButton); - bottomBar.add(backButton); + if(tagInput == null) { + tagInput = new GuiTextField(GuiConstants.UPLOAD_TAG_INPUT, fontRendererObj, (this.width / 2) + 20 + 10, 110, Math.min(200, this.width - 20 - 260), 20); + tagInput.setMaxStringLength(30); + } else { + tagInput.xPosition = (this.width / 2) + 20 + 10; + tagInput.width = Math.min(200, this.width - 20 - 260); + } - int i = 0; - for(GuiButton b : bottomBar) { - int w = this.width - 30; - int w2 = w/bottomBar.size(); + if(tagPlaceholder == null) { + tagPlaceholder = new GuiTextField(GuiConstants.UPLOAD_TAG_PLACEHOLDER, fontRendererObj, (this.width / 2) + 20 + 10, 110, Math.min(200, this.width - 20 - 260), 20); + tagPlaceholder.setTextColor(Color.DARK_GRAY.getRGB()); + tagPlaceholder.setText("Tags separated by comma"); + } else { + tagPlaceholder.xPosition = (this.width / 2) + 20 + 10; + tagPlaceholder.width = Math.min(200, this.width - 20 - 260); + } - int x = 15+(w2*i); - b.xPosition = x+2; - b.yPosition = height-30; - b.width = w2-4; + validateStartButton(); + } - buttonList.add(b); + @Override + protected void actionPerformed(GuiButton button) throws IOException { + if(!button.enabled) return; + if(button.id == GuiConstants.UPLOAD_CATEGORY_BUTTON) { + category = category.next(); + categoryButton.displayString = "Category: " + category.toNiceString(); + } else if(button.id == GuiConstants.UPLOAD_BACK_BUTTON) { + mc.displayGuiScreen(parent); + } else if(button.id == GuiConstants.UPLOAD_START_BUTTON) { + final String name = fileTitleInput.getText().trim(); + new Thread(new Runnable() { + @Override + public void run() { + try { + String tagsRaw = tagInput.getText(); + String[] split = tagsRaw.split(","); + List tags = new ArrayList(); + for(String str : split) { + if(!tags.contains(str) && str.length() > 0) { + tags.add(str); + } + } + uploader.uploadFile(GuiUploadFile.this, AuthenticationHandler.getKey(), name, tags, replayFile, category); + } catch(ApiException e) { //TODO: Error handling + e.printStackTrace(); + //mc.displayGuiScreen(new GuiMainMenu()); + } catch(RuntimeException e) { + e.printStackTrace(); + //mc.displayGuiScreen(new GuiMainMenu()); + } catch(IOException e) { + e.printStackTrace(); + } + } + }).start(); + } else if(button.id == GuiConstants.UPLOAD_CANCEL_BUTTON) { + uploader.cancelUploading(); + } + } - i++; - } - } + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + this.drawDefaultBackground(); - if(messageTextField == null) { - messageTextField = new GuiTextField(GuiConstants.UPLOAD_INFO_FIELD, fontRendererObj, 20, height-80, width-40, 20); - messageTextField.setEnabled(true); - messageTextField.setFocused(false); - messageTextField.setMaxStringLength(Integer.MAX_VALUE); - } else { - messageTextField.yPosition = height-80; - messageTextField.width = width-40; - } + drawString(fontRendererObj, metaData.getServerName(), (this.width / 2) + 20 + 10, 50, Color.GRAY.getRGB()); + drawString(fontRendererObj, "Duration: " + String.format("%02dm%02ds", + TimeUnit.MILLISECONDS.toMinutes(metaData.getDuration()), + TimeUnit.MILLISECONDS.toSeconds(metaData.getDuration()) - + TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(metaData.getDuration())) + ), (this.width / 2) + 20 + 10, 65, Color.GRAY.getRGB()); - if(tagInput == null) { - tagInput = new GuiTextField(GuiConstants.UPLOAD_TAG_INPUT, fontRendererObj, (this.width/2)+20+10, 110, Math.min(200, this.width-20-260), 20); - tagInput.setMaxStringLength(30); - } else { - tagInput.xPosition = (this.width/2)+20+10; - tagInput.width = Math.min(200, this.width-20-260); - } + drawCenteredString(fontRendererObj, "Upload File", this.width / 2, 5, Color.WHITE.getRGB()); - if(tagPlaceholder == null) { - tagPlaceholder = new GuiTextField(GuiConstants.UPLOAD_TAG_PLACEHOLDER, fontRendererObj, (this.width/2)+20+10, 110, Math.min(200, this.width-20-260), 20); - tagPlaceholder.setTextColor(Color.DARK_GRAY.getRGB()); - tagPlaceholder.setText("Tags separated by comma"); - } else { - tagPlaceholder.xPosition = (this.width/2)+20+10; - tagPlaceholder.width = Math.min(200, this.width-20-260); - } + //Draw thumbnail + if(thumb != null) { + if(dynTex == null) { + dynTex = new DynamicTexture(thumb); + mc.getTextureManager().loadTexture(textureResource, dynTex); + dynTex.updateDynamicTexture(); + ResourceHelper.registerResource(textureResource); + } - validateStartButton(); - } + mc.getTextureManager().bindTexture(textureResource); //Will be freed by the ResourceHelper + int wid = (this.width) / 2; + int hei = Math.round(wid * (720f / 1280f)); + Gui.drawScaledCustomSizeModalRect(19, 20, 0, 0, 1280, 720, wid, hei, 1280, 720); + } - @Override - protected void actionPerformed(GuiButton button) throws IOException { - if(!button.enabled) return; - if(button.id == GuiConstants.UPLOAD_CATEGORY_BUTTON) { - category = category.next(); - categoryButton.displayString = "Category: "+category.toNiceString(); - } else if(button.id == GuiConstants.UPLOAD_BACK_BUTTON) { - mc.displayGuiScreen(parent); - } else if(button.id == GuiConstants.UPLOAD_START_BUTTON) { - final String name = fileTitleInput.getText().trim(); - new Thread(new Runnable() { - @Override - public void run() { - try { - String tagsRaw = tagInput.getText(); - String[] split = tagsRaw.split(","); - List tags = new ArrayList(); - for(String str : split) { - if(!tags.contains(str) && str.length() > 0) { - tags.add(str); - } - } - uploader.uploadFile(GuiUploadFile.this, AuthenticationHandler.getKey(), name, tags, replayFile, category); - } catch (ApiException e) { //TODO: Error handling - e.printStackTrace(); - //mc.displayGuiScreen(new GuiMainMenu()); - } catch (RuntimeException e) { - e.printStackTrace(); - //mc.displayGuiScreen(new GuiMainMenu()); - } catch (IOException e) { - e.printStackTrace(); - } - } - }).start(); - } else if(button.id == GuiConstants.UPLOAD_CANCEL_BUTTON) { - uploader.cancelUploading(); - } - } + fileTitleInput.drawTextBox(); + messageTextField.drawTextBox(); - @Override - public void drawScreen(int mouseX, int mouseY, float partialTicks) { - this.drawDefaultBackground(); + if(tagInput.getText().length() > 0 || tagInput.isFocused()) { + tagInput.drawTextBox(); + } else { + tagPlaceholder.drawTextBox(); + } - drawString(fontRendererObj, metaData.getServerName(), (this.width/2)+20+10, 50, Color.GRAY.getRGB()); - drawString(fontRendererObj, "Duration: "+String.format("%02dm%02ds", - TimeUnit.MILLISECONDS.toMinutes(metaData.getDuration()), - TimeUnit.MILLISECONDS.toSeconds(metaData.getDuration()) - - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(metaData.getDuration())) - ), (this.width/2)+20+10, 65, Color.GRAY.getRGB()); + super.drawScreen(mouseX, mouseY, partialTicks); - drawCenteredString(fontRendererObj, "Upload File", this.width/2, 5, Color.WHITE.getRGB()); + this.drawRect(19, this.height - 52, width - 19, this.height - 37, Color.BLACK.getRGB()); + this.drawRect(21, this.height - 50, width - 21, this.height - 39, Color.WHITE.getRGB()); - //Draw thumbnail - if(thumb != null) { - if(dynTex == null) { - dynTex = new DynamicTexture(thumb); - mc.getTextureManager().loadTexture(textureResource, dynTex); - dynTex.updateDynamicTexture(); - ResourceHelper.registerResource(textureResource); - } + int width = this.width - 21 - 21; + float prog = uploader.getUploadProgress(); + float w = width * prog; - mc.getTextureManager().bindTexture(textureResource); //Will be freed by the ResourceHelper - int wid = (this.width)/2; - int hei = Math.round(wid*(720f/1280f)); - Gui.drawScaledCustomSizeModalRect(19, 20, 0, 0, 1280, 720, wid, hei, 1280, 720); - } + this.drawRect(21, this.height - 50, Math.round(21 + w), this.height - 39, Color.RED.getRGB()); - fileTitleInput.drawTextBox(); - messageTextField.drawTextBox(); + String perc = (int) Math.floor(prog * 100) + "%"; + fontRendererObj.drawString(perc, this.width / 2 - fontRendererObj.getStringWidth(perc) / 2, this.height - 48, Color.BLACK.getRGB()); + } - if(tagInput.getText().length() > 0 || tagInput.isFocused()) { - tagInput.drawTextBox(); - } else { - tagPlaceholder.drawTextBox(); - } + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { + super.mouseClicked(mouseX, mouseY, mouseButton); + fileTitleInput.mouseClicked(mouseX, mouseY, mouseButton); + tagInput.mouseClicked(mouseX, mouseY, mouseButton); + } - super.drawScreen(mouseX, mouseY, partialTicks); + @Override + public void updateScreen() { + fileTitleInput.updateCursorCounter(); + tagInput.updateCursorCounter(); + } - this.drawRect(19, this.height-52, width-19, this.height-37, Color.BLACK.getRGB()); - this.drawRect(21, this.height-50, width-21, this.height-39, Color.WHITE.getRGB()); + @Override + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); + } - int width = this.width-21 - 21; - float prog = uploader.getUploadProgress(); - float w = width*prog; + @Override + protected void keyTyped(char typedChar, int keyCode) throws IOException { + if(fileTitleInput.isFocused()) { + fileTitleInput.textboxKeyTyped(typedChar, keyCode); + } else if(tagInput.isFocused()) { + tagInput.textboxKeyTyped(typedChar, keyCode); + } - this.drawRect(21, this.height-50, Math.round(21+w), this.height-39, Color.RED.getRGB()); + if(uploader.isUploading()) { + startUploadButton.enabled = false; + } else { + validateStartButton(); + } + } - String perc = (int)Math.floor(prog*100)+"%"; - fontRendererObj.drawString(perc, this.width/2 - fontRendererObj.getStringWidth(perc)/2, this.height-48, Color.BLACK.getRGB()); - } + private void validateStartButton() { + boolean enabled = true; + if(fileTitleInput.getText().trim().length() < 5 || fileTitleInput.getText().trim().length() > 30) { + enabled = false; + } else if(p.matcher(fileTitleInput.getText()).find()) { + enabled = false; + fileTitleInput.setTextColor(Color.RED.getRGB()); + } else if(pt.matcher(tagInput.getText()).find()) { + enabled = false; + tagInput.setTextColor(Color.RED.getRGB()); + } else { + fileTitleInput.setTextColor(Color.WHITE.getRGB()); + tagInput.setTextColor(Color.WHITE.getRGB()); + } + startUploadButton.enabled = enabled; + } - @Override - public void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { - super.mouseClicked(mouseX, mouseY, mouseButton); - fileTitleInput.mouseClicked(mouseX, mouseY, mouseButton); - tagInput.mouseClicked(mouseX, mouseY, mouseButton); - } + public void onStartUploading() { + startUploadButton.enabled = false; + cancelUploadButton.enabled = true; + backButton.enabled = false; + categoryButton.enabled = false; + fileTitleInput.setEnabled(false); + messageTextField.setText("Uploading..."); + messageTextField.setTextColor(Color.WHITE.getRGB()); + } - @Override - public void updateScreen() { - fileTitleInput.updateCursorCounter(); - tagInput.updateCursorCounter(); - } - - @Override - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); - } - - @Override - protected void keyTyped(char typedChar, int keyCode) throws IOException { - if(fileTitleInput.isFocused()) { - fileTitleInput.textboxKeyTyped(typedChar, keyCode); - } else if(tagInput.isFocused()) { - tagInput.textboxKeyTyped(typedChar, keyCode); - } - - if(uploader.isUploading()) { - startUploadButton.enabled = false; - } else { - validateStartButton(); - } - } - - private void validateStartButton() { - boolean enabled = true; - if(fileTitleInput.getText().trim().length() < 5 || fileTitleInput.getText().trim().length() > 30) { - enabled = false; - } else if(p.matcher(fileTitleInput.getText()).find()) { - enabled = false; - fileTitleInput.setTextColor(Color.RED.getRGB()); - } else if(pt.matcher(tagInput.getText()).find()) { - enabled = false; - tagInput.setTextColor(Color.RED.getRGB()); - } else { - fileTitleInput.setTextColor(Color.WHITE.getRGB()); - tagInput.setTextColor(Color.WHITE.getRGB()); - } - startUploadButton.enabled = enabled; - } - - public void onStartUploading() { - startUploadButton.enabled = false; - cancelUploadButton.enabled = true; - backButton.enabled = false; - categoryButton.enabled = false; - fileTitleInput.setEnabled(false); - messageTextField.setText("Uploading..."); - messageTextField.setTextColor(Color.WHITE.getRGB()); - } - - public void onFinishUploading(boolean success, String info) { - validateStartButton(); - cancelUploadButton.enabled = false; - backButton.enabled = true; - categoryButton.enabled = true; - fileTitleInput.setEnabled(true); - if(success) { - messageTextField.setText("File has been successfully uploaded"); - messageTextField.setTextColor(Color.GREEN.getRGB()); - } else { - messageTextField.setText(info); - messageTextField.setTextColor(Color.RED.getRGB()); - } - } + public void onFinishUploading(boolean success, String info) { + validateStartButton(); + cancelUploadButton.enabled = false; + backButton.enabled = true; + categoryButton.enabled = true; + fileTitleInput.setEnabled(true); + if(success) { + messageTextField.setText("File has been successfully uploaded"); + messageTextField.setTextColor(Color.GREEN.getRGB()); + } else { + messageTextField.setText(info); + messageTextField.setTextColor(Color.RED.getRGB()); + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/online/ReplayFileList.java b/src/main/java/eu/crushedpixel/replaymod/gui/online/ReplayFileList.java index 2e500cf1..8581e59d 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/online/ReplayFileList.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/online/ReplayFileList.java @@ -1,12 +1,12 @@ package eu.crushedpixel.replaymod.gui.online; -import net.minecraft.client.Minecraft; import eu.crushedpixel.replaymod.gui.elements.GuiReplayListExtended; +import net.minecraft.client.Minecraft; public class ReplayFileList extends GuiReplayListExtended { - public ReplayFileList(Minecraft mcIn, int p_i45010_2_, int p_i45010_3_, - int p_i45010_4_, int p_i45010_5_, int p_i45010_6_) { - super(mcIn, p_i45010_2_, p_i45010_3_, p_i45010_4_, p_i45010_5_, p_i45010_6_); - } + public ReplayFileList(Minecraft mcIn, int p_i45010_2_, int p_i45010_3_, + int p_i45010_4_, int p_i45010_5_, int p_i45010_6_) { + super(mcIn, p_i45010_2_, p_i45010_3_, p_i45010_4_, p_i45010_5_, p_i45010_6_); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/replaystudio/GuiConnectPart.java b/src/main/java/eu/crushedpixel/replaymod/gui/replaystudio/GuiConnectPart.java index 5a504355..5bcbc857 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/replaystudio/GuiConnectPart.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/replaystudio/GuiConnectPart.java @@ -1,200 +1,198 @@ package eu.crushedpixel.replaymod.gui.replaystudio; -import java.awt.Color; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiButton; - -import org.apache.commons.io.FilenameUtils; - import eu.crushedpixel.replaymod.gui.GuiConstants; import eu.crushedpixel.replaymod.gui.elements.GuiArrowButton; import eu.crushedpixel.replaymod.gui.elements.GuiDropdown; import eu.crushedpixel.replaymod.gui.elements.GuiEntryList; import eu.crushedpixel.replaymod.gui.elements.listeners.SelectionListener; -import eu.crushedpixel.replaymod.registry.ReplayGuiRegistry; import eu.crushedpixel.replaymod.utils.ReplayFileIO; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; +import org.apache.commons.io.FilenameUtils; + +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; public class GuiConnectPart extends GuiStudioPart { - private static final String DESCRIPTION = "Connects multiple Replays in the same order as the list."; - private static final String TITLE = "Connect Replays"; + private static final String DESCRIPTION = "Connects multiple Replays in the same order as the list."; + private static final String TITLE = "Connect Replays"; - private boolean initialized = false; + private boolean initialized = false; - private GuiEntryList concatList; - private GuiDropdown replayDropdown; + private GuiEntryList concatList; + private GuiDropdown replayDropdown; - private GuiButton removeButton, addButton; - private GuiArrowButton upButton, downButton; + private GuiButton removeButton, addButton; + private GuiArrowButton upButton, downButton; - private List replayFiles; - private List filesToConcat; + private List replayFiles; + private List filesToConcat; - public GuiConnectPart(int yPos) { - super(yPos); - this.mc = Minecraft.getMinecraft(); - fontRendererObj = mc.fontRendererObj; - } + public GuiConnectPart(int yPos) { + super(yPos); + this.mc = Minecraft.getMinecraft(); + fontRendererObj = mc.fontRendererObj; + } - @Override - public void applyFilters(File replayFile, File outputFile) { - // TODO Auto-generated method stub - - } - - @Override - public String getDescription() { - return DESCRIPTION; - } + @Override + public void applyFilters(File replayFile, File outputFile) { + // TODO Auto-generated method stub - @Override - public String getTitle() { - return TITLE; - } + } - @Override - public void initGui() { - if(!initialized) { - concatList = new GuiEntryList(1, fontRendererObj, 30, yPos, 150, 0); - filesToConcat = new ArrayList(); - String selectedName = FilenameUtils.getBaseName(GuiReplayStudio.instance.getSelectedFile().getAbsolutePath()); - filesToConcat.add(selectedName); - concatList.setElements(filesToConcat); + @Override + public String getDescription() { + return DESCRIPTION; + } - concatList.setSelectionIndex(0); + @Override + public String getTitle() { + return TITLE; + } - replayDropdown = new GuiDropdown(1, fontRendererObj, 250, yPos+5, 0, 4); + @Override + public void initGui() { + if(!initialized) { + concatList = new GuiEntryList(1, fontRendererObj, 30, yPos, 150, 0); + filesToConcat = new ArrayList(); + String selectedName = FilenameUtils.getBaseName(GuiReplayStudio.instance.getSelectedFile().getAbsolutePath()); + filesToConcat.add(selectedName); + concatList.setElements(filesToConcat); - replayDropdown.clearElements(); - replayFiles = ReplayFileIO.getAllReplayFiles(); - int index = -1; - int i=0; - for(File file : replayFiles) { - String name = FilenameUtils.getBaseName(file.getAbsolutePath()); - replayDropdown.addElement(name); - if(name.equals(selectedName)) { - index = i; - } - i++; - } + concatList.setSelectionIndex(0); - replayDropdown.setSelectionPos(index); + replayDropdown = new GuiDropdown(1, fontRendererObj, 250, yPos + 5, 0, 4); - replayDropdown.addSelectionListener(new SelectionListener() { + replayDropdown.clearElements(); + replayFiles = ReplayFileIO.getAllReplayFiles(); + int index = -1; + int i = 0; + for(File file : replayFiles) { + String name = FilenameUtils.getBaseName(file.getAbsolutePath()); + replayDropdown.addElement(name); + if(name.equals(selectedName)) { + index = i; + } + i++; + } - @Override - public void onSelectionChanged(int selectionIndex) { - try { - filesToConcat.set(concatList.getSelectionIndex(), (String)replayDropdown.getElement(selectionIndex)); - concatList.setElements(filesToConcat); - } catch(Exception e) {} //Sorry, too lazy to properly avoid this Exception here - } - }); + replayDropdown.setSelectionPos(index); - concatList.addSelectionListener(new SelectionListener() { - @Override - public void onSelectionChanged(int selectionIndex) { - String selName = (String)concatList.getElement(selectionIndex); - int i = 0; - for(Object s : replayDropdown.getAllElements()) { - String str = (String)s; - if(str.equals(selName)) { - replayDropdown.setSelectionIndex(i); - break; - } - i++; - } - removeButton.enabled = upButton.enabled = downButton.enabled = !(selectionIndex < 0 || selectionIndex >= filesToConcat.size()); - if(upButton.enabled && selectionIndex == 0) upButton.enabled = false; - if(downButton.enabled && selectionIndex == filesToConcat.size()-1) downButton.enabled = false; - } - }); + replayDropdown.addSelectionListener(new SelectionListener() { - upButton = new GuiArrowButton(GuiConstants.REPLAY_EDITOR_UP_BUTTON, 195, yPos+40, "", true); - buttonList.add(upButton); + @Override + public void onSelectionChanged(int selectionIndex) { + try { + filesToConcat.set(concatList.getSelectionIndex(), (String) replayDropdown.getElement(selectionIndex)); + concatList.setElements(filesToConcat); + } catch(Exception e) { + } //Sorry, too lazy to properly avoid this Exception here + } + }); - downButton = new GuiArrowButton(GuiConstants.REPLAY_EDITOR_DOWN_BUTTON, 219, yPos+40, "", false); - buttonList.add(downButton); + concatList.addSelectionListener(new SelectionListener() { + @Override + public void onSelectionChanged(int selectionIndex) { + String selName = (String) concatList.getElement(selectionIndex); + int i = 0; + for(Object s : replayDropdown.getAllElements()) { + String str = (String) s; + if(str.equals(selName)) { + replayDropdown.setSelectionIndex(i); + break; + } + i++; + } + removeButton.enabled = upButton.enabled = downButton.enabled = !(selectionIndex < 0 || selectionIndex >= filesToConcat.size()); + if(upButton.enabled && selectionIndex == 0) upButton.enabled = false; + if(downButton.enabled && selectionIndex == filesToConcat.size() - 1) downButton.enabled = false; + } + }); - int w = GuiReplayStudio.instance.width-243-20-4; + upButton = new GuiArrowButton(GuiConstants.REPLAY_EDITOR_UP_BUTTON, 195, yPos + 40, "", true); + buttonList.add(upButton); - removeButton = new GuiButton(GuiConstants.REPLAY_EDITOR_REMOVE_BUTTON, 249, yPos+40, "Remove"); - buttonList.add(removeButton); + downButton = new GuiArrowButton(GuiConstants.REPLAY_EDITOR_DOWN_BUTTON, 219, yPos + 40, "", false); + buttonList.add(downButton); - addButton = new GuiButton(GuiConstants.REPLAY_EDITOR_ADD_BUTTON, 0, yPos+40, "Add"); - buttonList.add(addButton); + int w = GuiReplayStudio.instance.width - 243 - 20 - 4; - concatList.setSelectionIndex(0); - } + removeButton = new GuiButton(GuiConstants.REPLAY_EDITOR_REMOVE_BUTTON, 249, yPos + 40, "Remove"); + buttonList.add(removeButton); - int w = GuiReplayStudio.instance.width-249-20-4; - addButton.xPosition = 249+6+(w/2); + addButton = new GuiButton(GuiConstants.REPLAY_EDITOR_ADD_BUTTON, 0, yPos + 40, "Add"); + buttonList.add(addButton); - addButton.width = w/2+2; - removeButton.width = w/2+2; + concatList.setSelectionIndex(0); + } - replayDropdown.width = GuiReplayStudio.instance.width-250-18; + int w = GuiReplayStudio.instance.width - 249 - 20 - 4; + addButton.xPosition = 249 + 6 + (w / 2); - int h = GuiReplayStudio.instance.height-yPos-20; - int rows = (int)(h / (float)GuiEntryList.elementHeight); - concatList.setVisibleElements(rows); + addButton.width = w / 2 + 2; + removeButton.width = w / 2 + 2; - initialized = true; - } + replayDropdown.width = GuiReplayStudio.instance.width - 250 - 18; - @Override - public void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { - super.mouseClicked(mouseX, mouseY, mouseButton); //call this first to ensure the dropdown is still open - concatList.mouseClicked(mouseX, mouseY, mouseButton); - replayDropdown.mouseClicked(mouseX, mouseY, mouseButton); - } + int h = GuiReplayStudio.instance.height - yPos - 20; + int rows = (int) (h / (float) GuiEntryList.elementHeight); + concatList.setVisibleElements(rows); - @Override - public void drawScreen(int mouseX, int mouseY, float partialTicks) { - super.drawScreen(mouseX, mouseY, partialTicks); - concatList.drawTextBox(); - replayDropdown.drawTextBox(); + initialized = true; + } - drawString(fontRendererObj, "Replay:", 200, yPos+5+7, Color.WHITE.getRGB()); - } + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { + super.mouseClicked(mouseX, mouseY, mouseButton); //call this first to ensure the dropdown is still open + concatList.mouseClicked(mouseX, mouseY, mouseButton); + replayDropdown.mouseClicked(mouseX, mouseY, mouseButton); + } - @Override - public void updateScreen() { - if(!initialized) initGui(); - } + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + super.drawScreen(mouseX, mouseY, partialTicks); + concatList.drawTextBox(); + replayDropdown.drawTextBox(); - @Override - public void keyTyped(char typedChar, int keyCode) { + drawString(fontRendererObj, "Replay:", 200, yPos + 5 + 7, Color.WHITE.getRGB()); + } - } + @Override + public void updateScreen() { + if(!initialized) initGui(); + } - @Override - protected void actionPerformed(GuiButton button) { - if(!button.enabled || replayDropdown.isExpanded()) { - return; - } + @Override + public void keyTyped(char typedChar, int keyCode) { - if(button.id == GuiConstants.REPLAY_EDITOR_ADD_BUTTON) { - filesToConcat.add(FilenameUtils.getBaseName(replayFiles.get(0).getAbsolutePath())); - concatList.setElements(filesToConcat); - concatList.setSelectionIndex(filesToConcat.size()-1); - } else if(button.id == GuiConstants.REPLAY_EDITOR_REMOVE_BUTTON) { - int indexBefore = concatList.getSelectionIndex(); - if(indexBefore >= 0 && indexBefore < filesToConcat.size()) { - filesToConcat.remove(indexBefore); - concatList.setElements(filesToConcat); - if(filesToConcat.size() <= indexBefore) { - concatList.setSelectionIndex(filesToConcat.size()-1); - } else { - concatList.setSelectionIndex(indexBefore); - } - } - } - } + } + + @Override + protected void actionPerformed(GuiButton button) { + if(!button.enabled || replayDropdown.isExpanded()) { + return; + } + + if(button.id == GuiConstants.REPLAY_EDITOR_ADD_BUTTON) { + filesToConcat.add(FilenameUtils.getBaseName(replayFiles.get(0).getAbsolutePath())); + concatList.setElements(filesToConcat); + concatList.setSelectionIndex(filesToConcat.size() - 1); + } else if(button.id == GuiConstants.REPLAY_EDITOR_REMOVE_BUTTON) { + int indexBefore = concatList.getSelectionIndex(); + if(indexBefore >= 0 && indexBefore < filesToConcat.size()) { + filesToConcat.remove(indexBefore); + concatList.setElements(filesToConcat); + if(filesToConcat.size() <= indexBefore) { + concatList.setSelectionIndex(filesToConcat.size() - 1); + } else { + concatList.setSelectionIndex(indexBefore); + } + } + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/replaystudio/GuiReplayStudio.java b/src/main/java/eu/crushedpixel/replaymod/gui/replaystudio/GuiReplayStudio.java index 0272dac4..e6d508c1 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/replaystudio/GuiReplayStudio.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/replaystudio/GuiReplayStudio.java @@ -1,220 +1,216 @@ package eu.crushedpixel.replaymod.gui.replaystudio; -import java.awt.Color; +import eu.crushedpixel.replaymod.gui.GuiConstants; +import eu.crushedpixel.replaymod.gui.elements.GuiDropdown; +import eu.crushedpixel.replaymod.utils.ReplayFileIO; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiMainMenu; +import net.minecraft.client.gui.GuiScreen; +import org.apache.commons.io.FilenameUtils; + +import java.awt.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiMainMenu; -import net.minecraft.client.gui.GuiScreen; - -import org.apache.commons.io.FilenameUtils; - -import eu.crushedpixel.replaymod.gui.GuiConstants; -import eu.crushedpixel.replaymod.gui.elements.GuiDropdown; -import eu.crushedpixel.replaymod.utils.ReplayFileIO; - public class GuiReplayStudio extends GuiScreen { - public static GuiReplayStudio instance = null; + private static final int tabYPos = 110; + public static GuiReplayStudio instance = null; + private StudioTab currentTab = StudioTab.TRIM; + private GuiDropdown replayDropdown; + private GuiButton saveModeButton, saveButton; + private boolean overrideSave = false; + private boolean initialized = false; + private List replayFiles = new ArrayList(); - private static final int tabYPos = 110; + public GuiReplayStudio() { + instance = this; + } - private enum StudioTab { - TRIM(new GuiTrimPart(tabYPos)), CONNECT(new GuiConnectPart(tabYPos)), MODIFY(new GuiConnectPart(tabYPos)); + public File getSelectedFile() { + try { + return replayFiles.get(replayDropdown.getSelectionIndex()); + } catch(ArrayIndexOutOfBoundsException e) { + return null; + } + } - private GuiStudioPart studioPart; + private void refreshReplayDropdown() { + replayDropdown.clearElements(); + replayFiles = ReplayFileIO.getAllReplayFiles(); + for(File file : replayFiles) { + String name = FilenameUtils.getBaseName(file.getAbsolutePath()); + replayDropdown.addElement(name); + } + } - public GuiStudioPart getStudioPart() { - return studioPart; - } + @Override + public void initGui() { + List tabButtons = new ArrayList(); - private StudioTab(GuiStudioPart part) { - this.studioPart = part; - } - } + tabButtons.add(new GuiButton(GuiConstants.REPLAY_EDITOR_TRIM_TAB, 0, 0, "Trim Replay")); + tabButtons.add(new GuiButton(GuiConstants.REPLAY_EDITOR_CONNECT_TAB, 0, 0, "Connect Replays")); + tabButtons.add(new GuiButton(GuiConstants.REPLAY_EDITOR_MODIFY_TAB, 0, 0, "Modify Replay")); - public GuiReplayStudio() { - instance = this; - } + int w = this.width - 30; + int w2 = w / tabButtons.size(); + int i = 0; + for(GuiButton b : tabButtons) { + int x = 15 + (w2 * i); + b.xPosition = x + 2; + b.yPosition = 30; + b.width = w2 - 4; - private StudioTab currentTab = StudioTab.TRIM; + buttonList.add(b); - private GuiDropdown replayDropdown; - private GuiButton saveModeButton, saveButton; + i++; + } - private boolean overrideSave = false; + int modeWidth = tabButtons.get(0).width; - private boolean initialized = false; + if(!initialized) { + replayDropdown = new GuiDropdown(1, fontRendererObj, 15 + 2 + 1 + 80, 60, this.width - 30 - 8 - 80 - modeWidth - 4, 5); + refreshReplayDropdown(); + } else { + replayDropdown.width = this.width - 30 - 8 - 80 - modeWidth - 4; + } - private List replayFiles = new ArrayList(); - - public File getSelectedFile() { - try { - return replayFiles.get(replayDropdown.getSelectionIndex()); - } catch(ArrayIndexOutOfBoundsException e) { - return null; - } - } - - private void refreshReplayDropdown() { - replayDropdown.clearElements(); - replayFiles = ReplayFileIO.getAllReplayFiles(); - for(File file : replayFiles) { - String name = FilenameUtils.getBaseName(file.getAbsolutePath()); - replayDropdown.addElement(name); - } - } - - @Override - public void initGui() { - List tabButtons = new ArrayList(); - - tabButtons.add(new GuiButton(GuiConstants.REPLAY_EDITOR_TRIM_TAB, 0, 0, "Trim Replay")); - tabButtons.add(new GuiButton(GuiConstants.REPLAY_EDITOR_CONNECT_TAB, 0, 0, "Connect Replays")); - tabButtons.add(new GuiButton(GuiConstants.REPLAY_EDITOR_MODIFY_TAB, 0, 0, "Modify Replay")); - - int w = this.width - 30; - int w2 = w/tabButtons.size(); - int i = 0; - for(GuiButton b : tabButtons) { - int x = 15+(w2*i); - b.xPosition = x+2; - b.yPosition = 30; - b.width = w2-4; - - buttonList.add(b); - - i++; - } - - int modeWidth = tabButtons.get(0).width; - - if(!initialized) { - replayDropdown = new GuiDropdown(1, fontRendererObj, 15+2+1+80, 60, this.width-30-8-80-modeWidth-4, 5); - refreshReplayDropdown(); - } else { - replayDropdown.width = this.width-30-8-80-modeWidth-4; - } - - if(!initialized) { - saveModeButton = new GuiButton(GuiConstants.REPLAY_EDITOR_SAVEMODE_BUTTON, width-15-modeWidth-3, 60, getSaveModeLabel()); - } else { - saveModeButton.xPosition = width-15-modeWidth-3; - } - saveModeButton.width = modeWidth; - buttonList.add(saveModeButton); + if(!initialized) { + saveModeButton = new GuiButton(GuiConstants.REPLAY_EDITOR_SAVEMODE_BUTTON, width - 15 - modeWidth - 3, 60, getSaveModeLabel()); + } else { + saveModeButton.xPosition = width - 15 - modeWidth - 3; + } + saveModeButton.width = modeWidth; + buttonList.add(saveModeButton); - GuiButton backButton = new GuiButton(GuiConstants.REPLAY_EDITOR_BACK_BUTTON, width-70-18, height-20-5, "Back"); - backButton.width = 70; - buttonList.add(backButton); + GuiButton backButton = new GuiButton(GuiConstants.REPLAY_EDITOR_BACK_BUTTON, width - 70 - 18, height - 20 - 5, "Back"); + backButton.width = 70; + buttonList.add(backButton); - saveButton = new GuiButton(GuiConstants.REPLAY_EDITOR_SAVE_BUTTON, width-70-18, height-(2*20)-5-3, "Save"); - saveButton.width = 70; - buttonList.add(saveButton); + saveButton = new GuiButton(GuiConstants.REPLAY_EDITOR_SAVE_BUTTON, width - 70 - 18, height - (2 * 20) - 5 - 3, "Save"); + saveButton.width = 70; + buttonList.add(saveButton); - for(StudioTab tab : StudioTab.values()) { - tab.getStudioPart().initGui(); - } - - initialized = true; - }; + for(StudioTab tab : StudioTab.values()) { + tab.getStudioPart().initGui(); + } - private String getSaveModeLabel() { - return overrideSave ? "Replace Source File" : "Save to new File"; - } + initialized = true; + } - @Override - protected void actionPerformed(GuiButton button) throws IOException { - if(!button.enabled) return; - if(button.id == GuiConstants.REPLAY_EDITOR_SAVEMODE_BUTTON) { - overrideSave = !overrideSave; - button.displayString = getSaveModeLabel(); - } else if(button.id == GuiConstants.REPLAY_EDITOR_BACK_BUTTON) { - mc.displayGuiScreen(new GuiMainMenu()); - } else if(button.id == GuiConstants.REPLAY_EDITOR_TRIM_TAB) { - currentTab = StudioTab.TRIM; - } else if(button.id == GuiConstants.REPLAY_EDITOR_CONNECT_TAB) { - currentTab = StudioTab.CONNECT; - } else if(button.id == GuiConstants.REPLAY_EDITOR_MODIFY_TAB) { - currentTab = StudioTab.MODIFY; - } else if(button.id == GuiConstants.REPLAY_EDITOR_SAVE_BUTTON) { - File outputFile = getSelectedFile(); - File folder = ReplayFileIO.getReplayFolder(); - if(!overrideSave) { - String name = FilenameUtils.getBaseName(outputFile.getAbsolutePath())+"_edited"; - File f = new File(folder, name+".mcpr"); - int num = 0; - while(f.exists()) { - num++; - String fileName = name+"_"+num; - f = new File(folder, fileName+".mcpr"); - } - outputFile = f; - } - currentTab.getStudioPart().applyFilters(getSelectedFile(), outputFile); - } - } + private String getSaveModeLabel() { + return overrideSave ? "Replace Source File" : "Save to new File"; + } - @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseButton) - throws IOException { - replayDropdown.mouseClicked(mouseX, mouseY, mouseButton); - currentTab.getStudioPart().mouseClicked(mouseX, mouseY, mouseButton); - super.mouseClicked(mouseX, mouseY, mouseButton); - } + ; - @Override - public void drawScreen(int mouseX, int mouseY, float partialTicks) { - drawDefaultBackground(); - super.drawScreen(mouseX, mouseY, partialTicks); - currentTab.getStudioPart().drawScreen(mouseX, mouseY, partialTicks); + @Override + protected void actionPerformed(GuiButton button) throws IOException { + if(!button.enabled) return; + if(button.id == GuiConstants.REPLAY_EDITOR_SAVEMODE_BUTTON) { + overrideSave = !overrideSave; + button.displayString = getSaveModeLabel(); + } else if(button.id == GuiConstants.REPLAY_EDITOR_BACK_BUTTON) { + mc.displayGuiScreen(new GuiMainMenu()); + } else if(button.id == GuiConstants.REPLAY_EDITOR_TRIM_TAB) { + currentTab = StudioTab.TRIM; + } else if(button.id == GuiConstants.REPLAY_EDITOR_CONNECT_TAB) { + currentTab = StudioTab.CONNECT; + } else if(button.id == GuiConstants.REPLAY_EDITOR_MODIFY_TAB) { + currentTab = StudioTab.MODIFY; + } else if(button.id == GuiConstants.REPLAY_EDITOR_SAVE_BUTTON) { + File outputFile = getSelectedFile(); + File folder = ReplayFileIO.getReplayFolder(); + if(!overrideSave) { + String name = FilenameUtils.getBaseName(outputFile.getAbsolutePath()) + "_edited"; + File f = new File(folder, name + ".mcpr"); + int num = 0; + while(f.exists()) { + num++; + String fileName = name + "_" + num; + f = new File(folder, fileName + ".mcpr"); + } + outputFile = f; + } + currentTab.getStudioPart().applyFilters(getSelectedFile(), outputFile); + } + } - drawCenteredString(fontRendererObj, "§n"+currentTab.getStudioPart().getTitle(), width/2, 92, Color.WHITE.getRGB()); + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseButton) + throws IOException { + replayDropdown.mouseClicked(mouseX, mouseY, mouseButton); + currentTab.getStudioPart().mouseClicked(mouseX, mouseY, mouseButton); + super.mouseClicked(mouseX, mouseY, mouseButton); + } - List rows = new ArrayList(); - String remaining = currentTab.getStudioPart().getDescription(); - while(remaining.length() > 0) { - String[] split = remaining.split(" "); - String b = ""; - for(String sp : split) { - b += sp+" "; - if(fontRendererObj.getStringWidth(b.trim()) > width-30-70-20) { - b = b.substring(0, b.trim().length()-(sp.length())); - break; - } - } - String trimmed = b.trim(); - rows.add(trimmed); - try { - remaining = remaining.substring(trimmed.length()+1); - } catch(Exception e) {break;} - } + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + drawDefaultBackground(); + super.drawScreen(mouseX, mouseY, partialTicks); + currentTab.getStudioPart().drawScreen(mouseX, mouseY, partialTicks); - int i=0; - for(String row : rows) { - drawString(fontRendererObj, row, 30, height-(15*(rows.size()-i)), Color.WHITE.getRGB()); - i++; - } + drawCenteredString(fontRendererObj, "§n" + currentTab.getStudioPart().getTitle(), width / 2, 92, Color.WHITE.getRGB()); - drawCenteredString(fontRendererObj, "Replay Studio", this.width / 2, 10, 16777215); - drawString(fontRendererObj, "Replay File:", 30, 67, Color.WHITE.getRGB()); - - replayDropdown.drawTextBox(); - } + List rows = new ArrayList(); + String remaining = currentTab.getStudioPart().getDescription(); + while(remaining.length() > 0) { + String[] split = remaining.split(" "); + String b = ""; + for(String sp : split) { + b += sp + " "; + if(fontRendererObj.getStringWidth(b.trim()) > width - 30 - 70 - 20) { + b = b.substring(0, b.trim().length() - (sp.length())); + break; + } + } + String trimmed = b.trim(); + rows.add(trimmed); + try { + remaining = remaining.substring(trimmed.length() + 1); + } catch(Exception e) { + break; + } + } - @Override - protected void keyTyped(char typedChar, int keyCode) throws IOException { - currentTab.getStudioPart().keyTyped(typedChar, keyCode); - super.keyTyped(typedChar, keyCode); - } + int i = 0; + for(String row : rows) { + drawString(fontRendererObj, row, 30, height - (15 * (rows.size() - i)), Color.WHITE.getRGB()); + i++; + } - @Override - public void updateScreen() { - currentTab.getStudioPart().updateScreen(); - super.updateScreen(); - } + drawCenteredString(fontRendererObj, "Replay Studio", this.width / 2, 10, 16777215); + drawString(fontRendererObj, "Replay File:", 30, 67, Color.WHITE.getRGB()); + + replayDropdown.drawTextBox(); + } + + @Override + protected void keyTyped(char typedChar, int keyCode) throws IOException { + currentTab.getStudioPart().keyTyped(typedChar, keyCode); + super.keyTyped(typedChar, keyCode); + } + + @Override + public void updateScreen() { + currentTab.getStudioPart().updateScreen(); + super.updateScreen(); + } + + private enum StudioTab { + TRIM(new GuiTrimPart(tabYPos)), CONNECT(new GuiConnectPart(tabYPos)), MODIFY(new GuiConnectPart(tabYPos)); + + private GuiStudioPart studioPart; + + private StudioTab(GuiStudioPart part) { + this.studioPart = part; + } + + public GuiStudioPart getStudioPart() { + return studioPart; + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/replaystudio/GuiStudioPart.java b/src/main/java/eu/crushedpixel/replaymod/gui/replaystudio/GuiStudioPart.java index 22f1cfa3..5b657bc4 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/replaystudio/GuiStudioPart.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/replaystudio/GuiStudioPart.java @@ -1,29 +1,29 @@ package eu.crushedpixel.replaymod.gui.replaystudio; +import net.minecraft.client.gui.GuiScreen; + import java.io.File; import java.io.IOException; -import net.minecraft.client.gui.GuiScreen; - public abstract class GuiStudioPart extends GuiScreen { - - public GuiStudioPart(int yPos) { - this.yPos = yPos; - } - - protected int yPos = 0; - - public abstract void applyFilters(File replayFile, File outputFile); - - public abstract String getDescription(); - - public abstract String getTitle(); - - @Override - public abstract void keyTyped(char typedChar, int keyCode); - - @Override - public void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { - super.mouseClicked(mouseX, mouseY, mouseButton); - } + + protected int yPos = 0; + + public GuiStudioPart(int yPos) { + this.yPos = yPos; + } + + public abstract void applyFilters(File replayFile, File outputFile); + + public abstract String getDescription(); + + public abstract String getTitle(); + + @Override + public abstract void keyTyped(char typedChar, int keyCode); + + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { + super.mouseClicked(mouseX, mouseY, mouseButton); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/replaystudio/GuiTrimPart.java b/src/main/java/eu/crushedpixel/replaymod/gui/replaystudio/GuiTrimPart.java index f1f8fcf5..67b84f83 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/replaystudio/GuiTrimPart.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/replaystudio/GuiTrimPart.java @@ -1,163 +1,156 @@ package eu.crushedpixel.replaymod.gui.replaystudio; -import java.awt.Color; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.client.Minecraft; - -import org.lwjgl.input.Keyboard; - import eu.crushedpixel.replaymod.gui.elements.GuiNumberInput; import eu.crushedpixel.replaymod.studio.StudioImplementation; +import net.minecraft.client.Minecraft; +import org.lwjgl.input.Keyboard; + +import java.awt.*; +import java.io.File; +import java.util.ArrayList; +import java.util.List; public class GuiTrimPart extends GuiStudioPart { - private Minecraft mc = Minecraft.getMinecraft(); + private static final String DESCRIPTION = "Removes the beginning and end of a Replay File and only keeps the Replay between the given timestamps."; + private static final String TITLE = "Trim Replay"; + private Minecraft mc = Minecraft.getMinecraft(); + private boolean initialized = false; - private static final String DESCRIPTION = "Removes the beginning and end of a Replay File and only keeps the Replay between the given timestamps."; - private static final String TITLE = "Trim Replay"; + private GuiNumberInput startMinInput, startSecInput, startMsInput; + private GuiNumberInput endMinInput, endSecInput, endMsInput; - private boolean initialized = false; + private List inputOrder = new ArrayList(); - private GuiNumberInput startMinInput, startSecInput, startMsInput; - private GuiNumberInput endMinInput, endSecInput, endMsInput; + public GuiTrimPart(int yPos) { + super(yPos); + fontRendererObj = mc.fontRendererObj; + } - private List inputOrder = new ArrayList(); + @Override + public void applyFilters(File replayFile, File outputFile) { + try { + StudioImplementation.trimReplay(replayFile, false, getStartTimestamp(), getEndTimestamp(), outputFile); + } catch(Exception e) { + e.printStackTrace(); + } + } - public GuiTrimPart(int yPos) { - super(yPos); - fontRendererObj = mc.fontRendererObj; - } + private int valueOf(String text) { + try { + return Integer.valueOf(text); + } catch(NumberFormatException e) { + return 0; + } + } - @Override - public void applyFilters(File replayFile, File outputFile) { - try { - StudioImplementation.trimReplay(replayFile, false, getStartTimestamp(), getEndTimestamp(), outputFile); - } catch(Exception e) { - e.printStackTrace(); - } - } + private int getStartTimestamp() { + int mins = valueOf(startMinInput.getText()); + int secs = valueOf(startSecInput.getText()); + int ms = valueOf(startMsInput.getText()); - private int valueOf(String text) { - try { - return Integer.valueOf(text); - } catch(NumberFormatException e) { - return 0; - } - } + return (mins * 60 * 1000) + (secs * 1000) + ms; + } - private int getStartTimestamp() { - int mins = valueOf(startMinInput.getText()); - int secs = valueOf(startSecInput.getText()); - int ms = valueOf(startMsInput.getText()); + private int getEndTimestamp() { + int mins = valueOf(endMinInput.getText()); + int secs = valueOf(endSecInput.getText()); + int ms = valueOf(endMsInput.getText()); - return (mins*60*1000)+(secs*1000)+ms; - } + return (mins * 60 * 1000) + (secs * 1000) + ms; + } - private int getEndTimestamp() { - int mins = valueOf(endMinInput.getText()); - int secs = valueOf(endSecInput.getText()); - int ms = valueOf(endMsInput.getText()); + @Override + public String getDescription() { + return DESCRIPTION; + } - return (mins*60*1000)+(secs*1000)+ms; - } + @Override + public String getTitle() { + return TITLE; + } - @Override - public String getDescription() { - return DESCRIPTION; - } + @Override + public void initGui() { + if(!initialized) { + startMinInput = new GuiNumberInput(1, fontRendererObj, 70, yPos, 30, 3); + startSecInput = new GuiNumberInput(1, fontRendererObj, 120, yPos, 25, 2); + startMsInput = new GuiNumberInput(1, fontRendererObj, 165, yPos, 30, 3); - @Override - public String getTitle() { - return TITLE; - } + endMinInput = new GuiNumberInput(1, fontRendererObj, 70, yPos + 30, 30, 3); + endSecInput = new GuiNumberInput(1, fontRendererObj, 120, yPos + 30, 25, 2); + endMsInput = new GuiNumberInput(1, fontRendererObj, 165, yPos + 30, 30, 3); - @Override - public void initGui() { - if(!initialized) { - startMinInput = new GuiNumberInput(1, fontRendererObj, 70, yPos, 30, 3); - startSecInput = new GuiNumberInput(1, fontRendererObj, 120, yPos, 25, 2); - startMsInput = new GuiNumberInput(1, fontRendererObj, 165, yPos, 30, 3); + inputOrder.clear(); - endMinInput = new GuiNumberInput(1, fontRendererObj, 70, yPos+30, 30, 3); - endSecInput = new GuiNumberInput(1, fontRendererObj, 120, yPos+30, 25, 2); - endMsInput = new GuiNumberInput(1, fontRendererObj, 165, yPos+30, 30, 3); + inputOrder.add(startMinInput); + inputOrder.add(startSecInput); + inputOrder.add(startMsInput); + inputOrder.add(endMinInput); + inputOrder.add(endSecInput); + inputOrder.add(endMsInput); + } - inputOrder.clear(); + initialized = true; + } - inputOrder.add(startMinInput); - inputOrder.add(startSecInput); - inputOrder.add(startMsInput); - inputOrder.add(endMinInput); - inputOrder.add(endSecInput); - inputOrder.add(endMsInput); - } + @Override + public void mouseClicked(int mouseX, int mouseY, int mouseButton) { + for(GuiNumberInput input : inputOrder) { + input.mouseClicked(mouseX, mouseY, mouseButton); + } + } - initialized = true; - } + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + drawString(mc.fontRendererObj, "Start:", 30, yPos + 7, Color.WHITE.getRGB()); + drawString(mc.fontRendererObj, "End:", 30, yPos + 7 + 30, Color.WHITE.getRGB()); + drawString(mc.fontRendererObj, "m", 105, yPos + 7, Color.WHITE.getRGB()); + drawString(mc.fontRendererObj, "m", 105, yPos + 7 + 30, Color.WHITE.getRGB()); + drawString(mc.fontRendererObj, "s", 150, yPos + 7, Color.WHITE.getRGB()); + drawString(mc.fontRendererObj, "s", 150, yPos + 7 + 30, Color.WHITE.getRGB()); + drawString(mc.fontRendererObj, "ms", 200, yPos + 7, Color.WHITE.getRGB()); + drawString(mc.fontRendererObj, "ms", 200, yPos + 7 + 30, Color.WHITE.getRGB()); - @Override - public void mouseClicked(int mouseX, int mouseY, int mouseButton) { - for(GuiNumberInput input: inputOrder) { - input.mouseClicked(mouseX, mouseY, mouseButton); - } - } + drawString(mc.fontRendererObj, "Timestamp: " + getStartTimestamp(), 230, yPos + 7, Color.WHITE.getRGB()); + drawString(mc.fontRendererObj, "Timestamp: " + getEndTimestamp(), 230, yPos + 30 + 7, Color.WHITE.getRGB()); - @Override - public void drawScreen(int mouseX, int mouseY, float partialTicks) { - drawString(mc.fontRendererObj, "Start:", 30, yPos+7, Color.WHITE.getRGB()); - drawString(mc.fontRendererObj, "End:", 30, yPos+7+30, Color.WHITE.getRGB()); - drawString(mc.fontRendererObj, "m", 105, yPos+7, Color.WHITE.getRGB()); - drawString(mc.fontRendererObj, "m", 105, yPos+7+30, Color.WHITE.getRGB()); - drawString(mc.fontRendererObj, "s", 150, yPos+7, Color.WHITE.getRGB()); - drawString(mc.fontRendererObj, "s", 150, yPos+7+30, Color.WHITE.getRGB()); - drawString(mc.fontRendererObj, "ms", 200, yPos+7, Color.WHITE.getRGB()); - drawString(mc.fontRendererObj, "ms", 200, yPos+7+30, Color.WHITE.getRGB()); + for(GuiNumberInput input : inputOrder) { + input.drawTextBox(); + } - drawString(mc.fontRendererObj, "Timestamp: "+getStartTimestamp(), 230, yPos+7, Color.WHITE.getRGB()); - drawString(mc.fontRendererObj, "Timestamp: "+getEndTimestamp(), 230, yPos+30+7, Color.WHITE.getRGB()); + super.drawScreen(mouseX, mouseY, partialTicks); + } - for(GuiNumberInput input: inputOrder) { - input.drawTextBox(); - } + @Override + public void updateScreen() { + if(!initialized) { + initGui(); + } else { + for(GuiNumberInput input : inputOrder) { + input.updateCursorCounter(); + } + } + } - super.drawScreen(mouseX, mouseY, partialTicks); - } - - @Override - public void updateScreen() { - if(!initialized) { - initGui(); - } else { - for(GuiNumberInput input: inputOrder) { - input.updateCursorCounter(); - } - } - } - - @Override - public void keyTyped(char typedChar, int keyCode) { - if(keyCode == Keyboard.KEY_TAB) { //Tab handling - int i=0; - for(GuiNumberInput input: inputOrder) { - if(input.isFocused()) { - input.setFocused(false); - i++; - if(i >= inputOrder.size()) i=0; - inputOrder.get(i).setFocused(true); - break; - } - i++; - } - } else { - for(GuiNumberInput input: inputOrder) { - input.textboxKeyTyped(typedChar, keyCode); - } - } - } + @Override + public void keyTyped(char typedChar, int keyCode) { + if(keyCode == Keyboard.KEY_TAB) { //Tab handling + int i = 0; + for(GuiNumberInput input : inputOrder) { + if(input.isFocused()) { + input.setFocused(false); + i++; + if(i >= inputOrder.size()) i = 0; + inputOrder.get(i).setFocused(true); + break; + } + i++; + } + } else { + for(GuiNumberInput input : inputOrder) { + input.textboxKeyTyped(typedChar, keyCode); + } + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/replayviewer/GuiRenameReplay.java b/src/main/java/eu/crushedpixel/replaymod/gui/replayviewer/GuiRenameReplay.java index d29e69f6..684c5f27 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/replayviewer/GuiRenameReplay.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/replayviewer/GuiRenameReplay.java @@ -1,40 +1,33 @@ package eu.crushedpixel.replaymod.gui.replayviewer; -import java.io.File; -import java.io.IOException; - +import eu.crushedpixel.replaymod.recording.ConnectionEventHandler; +import eu.crushedpixel.replaymod.utils.ReplayFileIO; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiTextField; import net.minecraft.client.resources.I18n; - import org.apache.commons.io.FilenameUtils; import org.lwjgl.input.Keyboard; -import eu.crushedpixel.replaymod.recording.ConnectionEventHandler; -import eu.crushedpixel.replaymod.utils.ReplayFileIO; +import java.io.File; +import java.io.IOException; -public class GuiRenameReplay extends GuiScreen -{ +public class GuiRenameReplay extends GuiScreen { + private static final String __OBFID = "CL_00000709"; private GuiScreen field_146585_a; private GuiTextField field_146583_f; - private static final String __OBFID = "CL_00000709"; - private File file; - public GuiRenameReplay(GuiScreen parent, File file) - { + public GuiRenameReplay(GuiScreen parent, File file) { this.field_146585_a = parent; this.file = file; } - public void updateScreen() - { + public void updateScreen() { this.field_146583_f.updateCursorCounter(); } - public void initGui() - { + public void initGui() { Keyboard.enableRepeatEvents(true); this.buttonList.clear(); this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 96 + 12, I18n.format("Rename", new Object[0]))); @@ -45,29 +38,23 @@ public class GuiRenameReplay extends GuiScreen this.field_146583_f.setText(s); } - public void onGuiClosed() - { + public void onGuiClosed() { Keyboard.enableRepeatEvents(false); } - protected void actionPerformed(GuiButton button) throws IOException - { - if (button.enabled) - { - if (button.id == 1) - { + protected void actionPerformed(GuiButton button) throws IOException { + if(button.enabled) { + if(button.id == 1) { this.mc.displayGuiScreen(this.field_146585_a); - } - else if (button.id == 0) - { - File folder = ReplayFileIO.getReplayFolder(); + } else if(button.id == 0) { + File folder = ReplayFileIO.getReplayFolder(); - File initRenamed = new File(folder, this.field_146583_f.getText().trim()+ConnectionEventHandler.ZIP_FILE_EXTENSION.replaceAll("[^a-zA-Z0-9\\.\\-]", "_")); - File renamed = initRenamed; - int i=1; + File initRenamed = new File(folder, this.field_146583_f.getText().trim() + ConnectionEventHandler.ZIP_FILE_EXTENSION.replaceAll("[^a-zA-Z0-9\\.\\-]", "_")); + File renamed = initRenamed; + int i = 1; while(renamed.isFile()) { - renamed = new File(initRenamed.getAbsolutePath()+"_"+i); - i++; + renamed = new File(initRenamed.getAbsolutePath() + "_" + i); + i++; } file.renameTo(renamed); this.mc.displayGuiScreen(this.field_146585_a); @@ -75,25 +62,21 @@ public class GuiRenameReplay extends GuiScreen } } - protected void keyTyped(char typedChar, int keyCode) throws IOException - { + protected void keyTyped(char typedChar, int keyCode) throws IOException { this.field_146583_f.textboxKeyTyped(typedChar, keyCode); - ((GuiButton)this.buttonList.get(0)).enabled = this.field_146583_f.getText().trim().length() > 0; + ((GuiButton) this.buttonList.get(0)).enabled = this.field_146583_f.getText().trim().length() > 0; - if (keyCode == 28 || keyCode == 156) - { - this.actionPerformed((GuiButton)this.buttonList.get(0)); + if(keyCode == 28 || keyCode == 156) { + this.actionPerformed((GuiButton) this.buttonList.get(0)); } } - protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException - { + protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { super.mouseClicked(mouseX, mouseY, mouseButton); this.field_146583_f.mouseClicked(mouseX, mouseY, mouseButton); } - public void drawScreen(int mouseX, int mouseY, float partialTicks) - { + public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); this.drawCenteredString(this.fontRendererObj, I18n.format("Rename World", new Object[0]), this.width / 2, 20, 16777215); this.drawString(this.fontRendererObj, I18n.format("Replay Name", new Object[0]), this.width / 2 - 100, 47, 10526880); diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/replayviewer/GuiReplayViewer.java b/src/main/java/eu/crushedpixel/replaymod/gui/replayviewer/GuiReplayViewer.java index f2899699..f4971f44 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/replayviewer/GuiReplayViewer.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/replayviewer/GuiReplayViewer.java @@ -1,37 +1,7 @@ package eu.crushedpixel.replaymod.gui.replayviewer; -import java.awt.Dimension; -import java.awt.image.BufferedImage; -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URI; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.List; - -import javax.imageio.ImageIO; - -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.gui.GuiYesNo; -import net.minecraft.client.gui.GuiYesNoCallback; -import net.minecraft.client.resources.I18n; -import net.minecraft.util.Util; - -import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; -import org.apache.commons.compress.archivers.zip.ZipFile; -import org.apache.commons.io.FilenameUtils; -import org.lwjgl.Sys; -import org.lwjgl.input.Keyboard; - import com.google.gson.Gson; import com.mojang.realmsclient.util.Pair; - import eu.crushedpixel.replaymod.api.client.holders.FileInfo; import eu.crushedpixel.replaymod.gui.GuiReplaySettings; import eu.crushedpixel.replaymod.gui.elements.GuiReplayListExtended; @@ -42,265 +12,271 @@ import eu.crushedpixel.replaymod.recording.ReplayMetaData; import eu.crushedpixel.replaymod.replay.ReplayHandler; import eu.crushedpixel.replaymod.utils.ImageUtils; import eu.crushedpixel.replaymod.utils.ReplayFileIO; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.GuiYesNo; +import net.minecraft.client.gui.GuiYesNoCallback; +import net.minecraft.client.resources.I18n; +import net.minecraft.util.Util; +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.ZipFile; +import org.apache.commons.io.FilenameUtils; +import org.lwjgl.Sys; +import org.lwjgl.input.Keyboard; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.*; +import java.net.URI; +import java.util.*; +import java.util.List; public class GuiReplayViewer extends GuiScreen implements GuiYesNoCallback { - private GuiScreen parentScreen; - private GuiButton btnEditServer; - private GuiButton btnSelectServer; - private GuiButton btnDeleteServer; - private String hoveringText; - private boolean initialized; - private GuiReplayListExtended replayGuiList; - private List, File>> replayFileList = new ArrayList, File>>(); - private GuiButton loadButton, uploadButton, folderButton, renameButton, deleteButton, cancelButton, settingsButton; + private static final int LOAD_BUTTON_ID = 9001; + private static final int UPLOAD_BUTTON_ID = 9002; + private static final int FOLDER_BUTTON_ID = 9003; + private static final int RENAME_BUTTON_ID = 9004; + private static final int DELETE_BUTTON_ID = 9005; + private static final int SETTINGS_BUTTON_ID = 9006; + private static final int CANCEL_BUTTON_ID = 9007; + private static Gson gson = new Gson(); + private GuiScreen parentScreen; + private GuiButton btnEditServer; + private GuiButton btnSelectServer; + private GuiButton btnDeleteServer; + private String hoveringText; + private boolean initialized; + private GuiReplayListExtended replayGuiList; + private List, File>> replayFileList = new ArrayList, File>>(); + private GuiButton loadButton, uploadButton, folderButton, renameButton, deleteButton, cancelButton, settingsButton; + private boolean replaying = false; + private boolean delete_file = false; - private static Gson gson = new Gson(); - private boolean replaying = false; + public static GuiYesNo getYesNoGui(GuiYesNoCallback p_152129_0_, String file, int p_152129_2_) { + String s1 = I18n.format("Are you sure you want to delete this replay?", new Object[0]); + String s2 = "\'" + file + "\' " + I18n.format("will be lost forever! (A long time!)", new Object[0]); + String s3 = I18n.format("Delete", new Object[0]); + String s4 = I18n.format("Cancel", new Object[0]); + GuiYesNo guiyesno = new GuiYesNo(p_152129_0_, s1, s2, s3, s4, p_152129_2_); + return guiyesno; + } - private static final int LOAD_BUTTON_ID = 9001; - private static final int UPLOAD_BUTTON_ID = 9002; - private static final int FOLDER_BUTTON_ID = 9003; - private static final int RENAME_BUTTON_ID = 9004; - private static final int DELETE_BUTTON_ID = 9005; - private static final int SETTINGS_BUTTON_ID = 9006; - private static final int CANCEL_BUTTON_ID = 9007; + private void reloadFiles() { + replayGuiList.clearEntries(); + replayFileList = new ArrayList, File>>(); - private boolean delete_file = false; + for(File file : ReplayFileIO.getAllReplayFiles()) { + try { + ZipFile archive = new ZipFile(file); + ZipArchiveEntry recfile = archive.getEntry("recording" + ConnectionEventHandler.TEMP_FILE_EXTENSION); + ZipArchiveEntry metadata = archive.getEntry("metaData" + ConnectionEventHandler.JSON_FILE_EXTENSION); - private void reloadFiles() { - replayGuiList.clearEntries(); - replayFileList = new ArrayList, File>>(); + ZipArchiveEntry image = archive.getEntry("thumb"); + BufferedImage img = null; + if(image != null) { + InputStream is = archive.getInputStream(image); + is.skip(7); + BufferedImage bimg = ImageIO.read(is); + if(bimg != null) { + img = ImageUtils.scaleImage(bimg, new Dimension(1280, 720)); + } + } - for(File file : ReplayFileIO.getAllReplayFiles()) { - try { - ZipFile archive = new ZipFile(file); - ZipArchiveEntry recfile = archive.getEntry("recording"+ConnectionEventHandler.TEMP_FILE_EXTENSION); - ZipArchiveEntry metadata = archive.getEntry("metaData"+ConnectionEventHandler.JSON_FILE_EXTENSION); + File tmp = null; + if(img != null) { + tmp = File.createTempFile(FilenameUtils.getBaseName(file.getAbsolutePath()), "jpg"); + tmp.deleteOnExit(); - ZipArchiveEntry image = archive.getEntry("thumb"); - BufferedImage img = null; - if(image != null) { - InputStream is = archive.getInputStream(image); - is.skip(7); - BufferedImage bimg = ImageIO.read(is); - if(bimg != null) { - img = ImageUtils.scaleImage(bimg, new Dimension(1280, 720)); - } - } + ImageIO.write(img, "jpg", tmp); + } - File tmp = null; - if(img != null) { - tmp = File.createTempFile(FilenameUtils.getBaseName(file.getAbsolutePath()), "jpg"); - tmp.deleteOnExit(); + InputStream is = archive.getInputStream(metadata); + BufferedReader br = new BufferedReader(new InputStreamReader(is)); - ImageIO.write(img, "jpg", tmp); - } + String json = br.readLine(); - InputStream is = archive.getInputStream(metadata); - BufferedReader br = new BufferedReader(new InputStreamReader(is)); + ReplayMetaData metaData = gson.fromJson(json, ReplayMetaData.class); - String json = br.readLine(); + replayFileList.add(Pair.of(Pair.of(file, metaData), tmp)); - ReplayMetaData metaData = gson.fromJson(json, ReplayMetaData.class); + archive.close(); + } catch(Exception e) { + } + } - replayFileList.add(Pair.of(Pair.of(file, metaData), tmp)); + Collections.sort(replayFileList, new FileAgeComparator()); - archive.close(); - } catch(Exception e) {} - } + for(Pair, File> p : replayFileList) { + FileInfo fileInfo = new FileInfo(-1, p.first().second(), null, null, + -1, -1, -1, FilenameUtils.getBaseName(p.first().first().getName()), true); + replayGuiList.addEntry(fileInfo, p.second()); + } + } - Collections.sort(replayFileList, new FileAgeComparator()); + @Override + public void initGui() { + replayGuiList = new ReplayList(this, this.mc, this.width, this.height, 32, this.height - 64, 36); + Keyboard.enableRepeatEvents(true); + this.buttonList.clear(); - for(Pair, File> p : replayFileList) { - FileInfo fileInfo = new FileInfo(-1, p.first().second(), null, null, - -1, -1, -1, FilenameUtils.getBaseName(p.first().first().getName()), true); - replayGuiList.addEntry(fileInfo, p.second()); - } - } + if(!this.initialized) { + this.initialized = true; + } else { + this.replayGuiList.setDimensions(this.width, this.height, 32, this.height - 64); + } - public class FileAgeComparator implements Comparator, File>> { + reloadFiles(); + this.createButtons(); + } - @Override - public int compare(Pair, File> o1, Pair, File> o2) { - try { - return (int)(new Date(o2.first().second().getDate()).compareTo(new Date(o1.first().second().getDate()))); - } catch(Exception e) { - return 0; - } - } + private void createButtons() { + this.buttonList.add(loadButton = new GuiButton(LOAD_BUTTON_ID, this.width / 2 - 154, this.height - 52, 73, 20, I18n.format("Load", new Object[0]))); + this.buttonList.add(uploadButton = new GuiButton(UPLOAD_BUTTON_ID, this.width / 2 - 154 + 78, this.height - 52, 73, 20, I18n.format("Upload", new Object[0]))); + this.buttonList.add(folderButton = new GuiButton(FOLDER_BUTTON_ID, this.width / 2 + 4, this.height - 52, 150, 20, I18n.format("Open Replay Folder...", new Object[0]))); + this.buttonList.add(renameButton = new GuiButton(RENAME_BUTTON_ID, this.width / 2 - 154, this.height - 28, 72, 20, I18n.format("Rename", new Object[0]))); + this.buttonList.add(deleteButton = new GuiButton(DELETE_BUTTON_ID, this.width / 2 - 76, this.height - 28, 72, 20, I18n.format("Delete", new Object[0]))); + this.buttonList.add(settingsButton = new GuiButton(SETTINGS_BUTTON_ID, this.width / 2 + 4, this.height - 28, 72, 20, I18n.format("Settings", new Object[0]))); + this.buttonList.add(cancelButton = new GuiButton(CANCEL_BUTTON_ID, this.width / 2 + 4 + 78, this.height - 28, 72, 20, I18n.format("Cancel", new Object[0]))); + setButtonsEnabled(false); + } - } + @Override + public void handleMouseInput() throws IOException { + super.handleMouseInput(); + this.replayGuiList.handleMouseInput(); + } - @Override - public void initGui() { - replayGuiList = new ReplayList(this, this.mc, this.width, this.height, 32, this.height - 64, 36); - Keyboard.enableRepeatEvents(true); - this.buttonList.clear(); + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { + super.mouseClicked(mouseX, mouseY, mouseButton); + this.replayGuiList.mouseClicked(mouseX, mouseY, mouseButton); + } - if (!this.initialized) { - this.initialized = true; - } - else { - this.replayGuiList.setDimensions(this.width, this.height, 32, this.height - 64); - } + @Override + protected void mouseReleased(int mouseX, int mouseY, int state) { + super.mouseReleased(mouseX, mouseY, state); + this.replayGuiList.mouseReleased(mouseX, mouseY, state); + } - reloadFiles(); - this.createButtons(); - } + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + this.hoveringText = null; + this.drawDefaultBackground(); + this.replayGuiList.drawScreen(mouseX, mouseY, partialTicks); + this.drawCenteredString(this.fontRendererObj, "Replay Viewer", this.width / 2, 20, 16777215); + super.drawScreen(mouseX, mouseY, partialTicks); + } - private void createButtons() { - this.buttonList.add(loadButton = new GuiButton(LOAD_BUTTON_ID, this.width / 2 - 154, this.height - 52, 73, 20, I18n.format("Load", new Object[0]))); - this.buttonList.add(uploadButton = new GuiButton(UPLOAD_BUTTON_ID, this.width / 2 - 154 + 78, this.height - 52, 73, 20, I18n.format("Upload", new Object[0]))); - this.buttonList.add(folderButton = new GuiButton(FOLDER_BUTTON_ID, this.width / 2 + 4, this.height - 52, 150, 20, I18n.format("Open Replay Folder...", new Object[0]))); - this.buttonList.add(renameButton = new GuiButton(RENAME_BUTTON_ID, this.width / 2 - 154, this.height - 28, 72, 20, I18n.format("Rename", new Object[0]))); - this.buttonList.add(deleteButton = new GuiButton(DELETE_BUTTON_ID, this.width / 2 - 76, this.height - 28, 72, 20, I18n.format("Delete", new Object[0]))); - this.buttonList.add(settingsButton = new GuiButton(SETTINGS_BUTTON_ID, this.width / 2 + 4, this.height - 28, 72, 20, I18n.format("Settings", new Object[0]))); - this.buttonList.add(cancelButton = new GuiButton(CANCEL_BUTTON_ID, this.width / 2 + 4 + 78, this.height - 28, 72, 20, I18n.format("Cancel", new Object[0]))); - setButtonsEnabled(false); - } + @Override + protected void actionPerformed(GuiButton button) throws IOException { + if(button.enabled) { + if(button.id == LOAD_BUTTON_ID) { + loadReplay(replayGuiList.selected); + } else if(button.id == CANCEL_BUTTON_ID) { + mc.displayGuiScreen(parentScreen); + } else if(button.id == DELETE_BUTTON_ID) { + String s = replayGuiList.getListEntry(replayGuiList.selected).getFileInfo().getName(); - @Override - public void handleMouseInput() throws IOException { - super.handleMouseInput(); - this.replayGuiList.handleMouseInput(); - } + if(s != null) { + delete_file = true; + GuiYesNo guiyesno = getYesNoGui(this, s, 1); + this.mc.displayGuiScreen(guiyesno); + } + } else if(button.id == SETTINGS_BUTTON_ID) { + this.mc.displayGuiScreen(new GuiReplaySettings(this)); + } else if(button.id == RENAME_BUTTON_ID) { + File file = replayFileList.get(replayGuiList.selected).first().first(); + this.mc.displayGuiScreen(new GuiRenameReplay(this, file)); + } else if(button.id == UPLOAD_BUTTON_ID) { + File file = replayFileList.get(replayGuiList.selected).first().first(); + this.mc.displayGuiScreen(new GuiUploadFile(file, this)); + } else if(button.id == FOLDER_BUTTON_ID) { + File file1 = ReplayFileIO.getReplayFolder(); - @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { - super.mouseClicked(mouseX, mouseY, mouseButton); - this.replayGuiList.mouseClicked(mouseX, mouseY, mouseButton); - } + String s = file1.getAbsolutePath(); - @Override - protected void mouseReleased(int mouseX, int mouseY, int state) { - super.mouseReleased(mouseX, mouseY, state); - this.replayGuiList.mouseReleased(mouseX, mouseY, state); - } + if(Util.getOSType() == Util.EnumOS.OSX) { + try { + Runtime.getRuntime().exec(new String[]{"/usr/bin/open", s}); + return; + } catch(IOException ioexception1) { + } + } else if(Util.getOSType() == Util.EnumOS.WINDOWS) { + String s1 = String.format("cmd.exe /C start \"Open file\" \"%s\"", new Object[]{s}); - @Override - public void drawScreen(int mouseX, int mouseY, float partialTicks) { - this.hoveringText = null; - this.drawDefaultBackground(); - this.replayGuiList.drawScreen(mouseX, mouseY, partialTicks); - this.drawCenteredString(this.fontRendererObj, "Replay Viewer", this.width / 2, 20, 16777215); - super.drawScreen(mouseX, mouseY, partialTicks); - } + try { + Runtime.getRuntime().exec(s1); + return; + } catch(IOException ioexception) { + } + } - @Override - protected void actionPerformed(GuiButton button) throws IOException { - if(button.enabled) { - if(button.id == LOAD_BUTTON_ID) { - loadReplay(replayGuiList.selected); - } - else if(button.id == CANCEL_BUTTON_ID) { - mc.displayGuiScreen(parentScreen); - } - else if(button.id == DELETE_BUTTON_ID) { - String s = replayGuiList.getListEntry(replayGuiList.selected).getFileInfo().getName(); + boolean flag = false; - if (s != null) { - delete_file = true; - GuiYesNo guiyesno = getYesNoGui(this, s, 1); - this.mc.displayGuiScreen(guiyesno); - } - } - else if(button.id == SETTINGS_BUTTON_ID) { - this.mc.displayGuiScreen(new GuiReplaySettings(this)); - } - else if(button.id == RENAME_BUTTON_ID) { - File file = replayFileList.get(replayGuiList.selected).first().first(); - this.mc.displayGuiScreen(new GuiRenameReplay(this, file)); - } - else if(button.id == UPLOAD_BUTTON_ID) { - File file = replayFileList.get(replayGuiList.selected).first().first(); - this.mc.displayGuiScreen(new GuiUploadFile(file, this)); - } - else if(button.id == FOLDER_BUTTON_ID) { - File file1 = ReplayFileIO.getReplayFolder(); - - String s = file1.getAbsolutePath(); + try { + Class oclass = Class.forName("java.awt.Desktop"); + Object object = oclass.getMethod("getDesktop", new Class[0]).invoke((Object) null, new Object[0]); + oclass.getMethod("browse", new Class[]{URI.class}).invoke(object, new Object[]{file1.toURI()}); + } catch(Throwable throwable) { + flag = true; + } - if(Util.getOSType() == Util.EnumOS.OSX) { - try { - Runtime.getRuntime().exec(new String[] {"/usr/bin/open", s}); - return; - } - catch(IOException ioexception1) {} - } - else if(Util.getOSType() == Util.EnumOS.WINDOWS) { - String s1 = String.format("cmd.exe /C start \"Open file\" \"%s\"", new Object[] {s}); + if(flag) { + Sys.openURL("file://" + s); + } + } + } + } - try{ - Runtime.getRuntime().exec(s1); - return; - } - catch(IOException ioexception) {} - } + public void confirmClicked(boolean result, int id) { + if(this.delete_file) { + this.delete_file = false; - boolean flag = false; + if(result) { + replayFileList.get(replayGuiList.selected).first().first().delete(); + replayFileList.remove(replayGuiList.selected); + } - try { - Class oclass = Class.forName("java.awt.Desktop"); - Object object = oclass.getMethod("getDesktop", new Class[0]).invoke((Object)null, new Object[0]); - oclass.getMethod("browse", new Class[] {URI.class}).invoke(object, new Object[] {file1.toURI()}); - } - catch(Throwable throwable) { - flag = true; - } + this.mc.displayGuiScreen(this); + } + } - if(flag) { - Sys.openURL("file://" + s); - } - } - } - } + public void setButtonsEnabled(boolean b) { + loadButton.enabled = b; + if(!b || !AuthenticationHandler.isAuthenticated()) { + uploadButton.enabled = false; + } else { + uploadButton.enabled = true; + } - public void confirmClicked(boolean result, int id) { - if (this.delete_file) - { - this.delete_file = false; + renameButton.enabled = b; + deleteButton.enabled = b; + } - if (result) - { - replayFileList.get(replayGuiList.selected).first().first().delete(); - replayFileList.remove(replayGuiList.selected); - } + public void loadReplay(int id) { + mc.displayGuiScreen((GuiScreen) null); - this.mc.displayGuiScreen(this); - } - } + try { + ReplayHandler.startReplay(replayFileList.get(id).first().first()); + } catch(Exception e) { + e.printStackTrace(); + } - public static GuiYesNo getYesNoGui(GuiYesNoCallback p_152129_0_, String file, int p_152129_2_) { - String s1 = I18n.format("Are you sure you want to delete this replay?", new Object[0]); - String s2 = "\'" + file + "\' " + I18n.format("will be lost forever! (A long time!)", new Object[0]); - String s3 = I18n.format("Delete", new Object[0]); - String s4 = I18n.format("Cancel", new Object[0]); - GuiYesNo guiyesno = new GuiYesNo(p_152129_0_, s1, s2, s3, s4, p_152129_2_); - return guiyesno; - } + } - public void setButtonsEnabled(boolean b) { - loadButton.enabled = b; - if(!b || !AuthenticationHandler.isAuthenticated()) { - uploadButton.enabled = false; - } else { - uploadButton.enabled = true; - } + public class FileAgeComparator implements Comparator, File>> { - renameButton.enabled = b; - deleteButton.enabled = b; - } + @Override + public int compare(Pair, File> o1, Pair, File> o2) { + try { + return (int) (new Date(o2.first().second().getDate()).compareTo(new Date(o1.first().second().getDate()))); + } catch(Exception e) { + return 0; + } + } - public void loadReplay(int id) { - mc.displayGuiScreen((GuiScreen)null); - - try { - ReplayHandler.startReplay(replayFileList.get(id).first().first()); - } catch(Exception e) { - e.printStackTrace(); - } - - } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/gui/replayviewer/ReplayList.java b/src/main/java/eu/crushedpixel/replaymod/gui/replayviewer/ReplayList.java index 106ea6a4..29912d7a 100755 --- a/src/main/java/eu/crushedpixel/replaymod/gui/replayviewer/ReplayList.java +++ b/src/main/java/eu/crushedpixel/replaymod/gui/replayviewer/ReplayList.java @@ -5,25 +5,25 @@ import net.minecraft.client.Minecraft; public class ReplayList extends GuiReplayListExtended { - private GuiReplayViewer parent; - - public ReplayList(GuiReplayViewer parent, Minecraft mcIn, - int p_i45010_2_, int p_i45010_3_, int p_i45010_4_, int p_i45010_5_, - int p_i45010_6_) { - super(mcIn, p_i45010_2_, p_i45010_3_, p_i45010_4_, p_i45010_5_, - p_i45010_6_); + private GuiReplayViewer parent; - this.parent = parent; - } - - @Override - protected void elementClicked(int slotIndex, boolean isDoubleClick, - int mouseX, int mouseY) { - super.elementClicked(slotIndex, isDoubleClick, mouseX, mouseY); - parent.setButtonsEnabled(true); - if(isDoubleClick) { - parent.loadReplay(slotIndex); - } - } + public ReplayList(GuiReplayViewer parent, Minecraft mcIn, + int p_i45010_2_, int p_i45010_3_, int p_i45010_4_, int p_i45010_5_, + int p_i45010_6_) { + super(mcIn, p_i45010_2_, p_i45010_3_, p_i45010_4_, p_i45010_5_, + p_i45010_6_); + + this.parent = parent; + } + + @Override + protected void elementClicked(int slotIndex, boolean isDoubleClick, + int mouseX, int mouseY) { + super.elementClicked(slotIndex, isDoubleClick, mouseX, mouseY); + parent.setButtonsEnabled(true); + if(isDoubleClick) { + parent.loadReplay(slotIndex); + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/holders/Keyframe.java b/src/main/java/eu/crushedpixel/replaymod/holders/Keyframe.java index a0f7645e..38610cad 100755 --- a/src/main/java/eu/crushedpixel/replaymod/holders/Keyframe.java +++ b/src/main/java/eu/crushedpixel/replaymod/holders/Keyframe.java @@ -2,19 +2,13 @@ package eu.crushedpixel.replaymod.holders; public class Keyframe { - private int realTimestamp; - - public Keyframe(int realTimestamp) { - this.realTimestamp = realTimestamp; - } + private final int realTimestamp; - public int getRealTimestamp() { - return realTimestamp; - } + public Keyframe(int realTimestamp) { + this.realTimestamp = realTimestamp; + } - public void setRealTimestamp(int realTimestamp) { - this.realTimestamp = realTimestamp; - } - - + public int getRealTimestamp() { + return realTimestamp; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/holders/KeyframeComparator.java b/src/main/java/eu/crushedpixel/replaymod/holders/KeyframeComparator.java index b56c28e6..7b65a901 100755 --- a/src/main/java/eu/crushedpixel/replaymod/holders/KeyframeComparator.java +++ b/src/main/java/eu/crushedpixel/replaymod/holders/KeyframeComparator.java @@ -1,16 +1,16 @@ package eu.crushedpixel.replaymod.holders; -import java.util.Comparator; - import eu.crushedpixel.replaymod.replay.ReplayHandler; +import java.util.Comparator; + public class KeyframeComparator implements Comparator { - @Override - public int compare(Keyframe o1, Keyframe o2) { - if(ReplayHandler.isSelected(o1)) return 1; - if(ReplayHandler.isSelected(o2)) return -1; - return ((Integer)o1.getRealTimestamp()).compareTo(o2.getRealTimestamp()); - } + @Override + public int compare(Keyframe o1, Keyframe o2) { + if(ReplayHandler.isSelected(o1)) return 1; + if(ReplayHandler.isSelected(o2)) return -1; + return ((Integer) o1.getRealTimestamp()).compareTo(o2.getRealTimestamp()); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/holders/PacketData.java b/src/main/java/eu/crushedpixel/replaymod/holders/PacketData.java index 9ee764de..8faa1f71 100755 --- a/src/main/java/eu/crushedpixel/replaymod/holders/PacketData.java +++ b/src/main/java/eu/crushedpixel/replaymod/holders/PacketData.java @@ -1,30 +1,30 @@ package eu.crushedpixel.replaymod.holders; -import io.netty.buffer.ByteBuf; -import net.minecraft.network.Packet; - public class PacketData { - private byte[] array; - private int timestamp; - - public PacketData(byte[] array, int timestamp) { - this.array = array; - this.timestamp = timestamp; - } - - public byte[] getByteArray() { - return array; - } - public void setByteArray(byte[] array) { - this.array = array; - } - public int getTimestamp() { - return timestamp; - } - public void setTimestamp(int timestamp) { - this.timestamp = timestamp; - } - - + private byte[] array; + private int timestamp; + + public PacketData(byte[] array, int timestamp) { + this.array = array; + this.timestamp = timestamp; + } + + public byte[] getByteArray() { + return array; + } + + public void setByteArray(byte[] array) { + this.array = array; + } + + public int getTimestamp() { + return timestamp; + } + + public void setTimestamp(int timestamp) { + this.timestamp = timestamp; + } + + } diff --git a/src/main/java/eu/crushedpixel/replaymod/holders/Position.java b/src/main/java/eu/crushedpixel/replaymod/holders/Position.java index 3de615ac..a30e61eb 100755 --- a/src/main/java/eu/crushedpixel/replaymod/holders/Position.java +++ b/src/main/java/eu/crushedpixel/replaymod/holders/Position.java @@ -4,67 +4,67 @@ import net.minecraft.entity.Entity; public class Position { - private double x, y, z; - private float pitch, yaw; - - public Position(Entity e) { - this.x = e.posX; - this.y = e.posY; - this.z = e.posZ; - this.pitch = e.rotationPitch; - this.yaw = e.rotationYaw; - } - - public Position(double x, double y, double z, float pitch, float yaw) { - this.x = x; - this.y = y; - this.z = z; - this.pitch = pitch; - this.yaw = yaw; - } + private double x, y, z; + private float pitch, yaw; - public double getX() { - return x; - } + public Position(Entity e) { + this.x = e.posX; + this.y = e.posY; + this.z = e.posZ; + this.pitch = e.rotationPitch; + this.yaw = e.rotationYaw; + } - public void setX(double x) { - this.x = x; - } + public Position(double x, double y, double z, float pitch, float yaw) { + this.x = x; + this.y = y; + this.z = z; + this.pitch = pitch; + this.yaw = yaw; + } - public double getY() { - return y; - } + public double getX() { + return x; + } - public void setY(double y) { - this.y = y; - } + public void setX(double x) { + this.x = x; + } - public double getZ() { - return z; - } + public double getY() { + return y; + } - public void setZ(double z) { - this.z = z; - } + public void setY(double y) { + this.y = y; + } - public float getPitch() { - return pitch; - } + public double getZ() { + return z; + } - public void setPitch(float pitch) { - this.pitch = pitch; - } + public void setZ(double z) { + this.z = z; + } - public float getYaw() { - return yaw; - } + public float getPitch() { + return pitch; + } - public void setYaw(float yaw) { - this.yaw = yaw; - } - - @Override - public String toString() { - return "X="+x+", Y="+y+", Z="+z+", Yaw="+yaw+", Pitch="+pitch; - } + public void setPitch(float pitch) { + this.pitch = pitch; + } + + public float getYaw() { + return yaw; + } + + public void setYaw(float yaw) { + this.yaw = yaw; + } + + @Override + public String toString() { + return "X=" + x + ", Y=" + y + ", Z=" + z + ", Yaw=" + yaw + ", Pitch=" + pitch; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/holders/PositionKeyframe.java b/src/main/java/eu/crushedpixel/replaymod/holders/PositionKeyframe.java index a4b1ea90..fcecf785 100755 --- a/src/main/java/eu/crushedpixel/replaymod/holders/PositionKeyframe.java +++ b/src/main/java/eu/crushedpixel/replaymod/holders/PositionKeyframe.java @@ -2,19 +2,14 @@ package eu.crushedpixel.replaymod.holders; public class PositionKeyframe extends Keyframe { - private Position position; - - public PositionKeyframe(int realTime, Position position) { - super(realTime); - this.position = position; - } + private final Position position; - public Position getPosition() { - return position; - } + public PositionKeyframe(int realTime, Position position) { + super(realTime); + this.position = position; + } - public void setPosition(Position position) { - this.position = position; - } - + public Position getPosition() { + return position; + } } \ No newline at end of file diff --git a/src/main/java/eu/crushedpixel/replaymod/holders/TimeInfo.java b/src/main/java/eu/crushedpixel/replaymod/holders/TimeInfo.java deleted file mode 100755 index a1583a9f..00000000 --- a/src/main/java/eu/crushedpixel/replaymod/holders/TimeInfo.java +++ /dev/null @@ -1,100 +0,0 @@ -package eu.crushedpixel.replaymod.holders; - -/** - * Copyright (c) 2014 Johni0702 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - **/ -public final class TimeInfo { - - @Override - public String toString() { - return start+" | "+speedSince+" | "+speed+" | "+jumpTo; - } - - public static TimeInfo create() { - long now = System.currentTimeMillis(); - return new TimeInfo(now, now, 1, -1); - } - - public TimeInfo(long start, long speedSince, double speed, long jumpTo) { - this.start = start; - this.speedSince = speedSince; - this.speed = speed; - this.jumpTo = jumpTo; - } - - private final long start; - private final long speedSince; - private final double speed; - private final long jumpTo; - - public long getActualStartTime(long now) { - long realTimePassed = now - speedSince; - long ingameTimePassed = (long) (realTimePassed * this.speed); - return start + realTimePassed - ingameTimePassed; - } - - public long getInGameTimePassed(long now) { - long realTimePassed = now - speedSince; - long ingameTimePassed = (long) (realTimePassed * this.speed); - return speedSince - start + ingameTimePassed; - } - - public TimeInfo updateSpeed(long now, double speed) { - if (isJumping()) { - return new TimeInfo(now-jumpTo, now, speed, -1); - } else { - if (this.speed == speed) { - return this; - } - long start; - if (this.speed == 1) { - start = this.start; - } else { - start = getActualStartTime(now); - } - return new TimeInfo(start, now, speed, -1); - } - } - - public boolean isJumping() { - return jumpTo != -1; - } - - public TimeInfo jumpTo(long jumpTo) { - return new TimeInfo(start, speedSince, speed, jumpTo); - } - - public long getStart() { - return start; - } - - public long getSpeedSince() { - return speedSince; - } - - public double getSpeed() { - return speed; - } - - public long getJumpTo() { - return jumpTo; - } -} \ No newline at end of file diff --git a/src/main/java/eu/crushedpixel/replaymod/holders/TimeKeyframe.java b/src/main/java/eu/crushedpixel/replaymod/holders/TimeKeyframe.java index bb527812..cd84567d 100755 --- a/src/main/java/eu/crushedpixel/replaymod/holders/TimeKeyframe.java +++ b/src/main/java/eu/crushedpixel/replaymod/holders/TimeKeyframe.java @@ -2,18 +2,14 @@ package eu.crushedpixel.replaymod.holders; public class TimeKeyframe extends Keyframe { - private int timestamp; - - public TimeKeyframe(int realTime, int timestamp) { - super(realTime); - this.timestamp = timestamp; - } + private final int timestamp; - public int getTimestamp() { - return timestamp; - } - - public void setTimestamp(int timestamp) { - this.timestamp = timestamp; - } + public TimeKeyframe(int realTime, int timestamp) { + super(realTime); + this.timestamp = timestamp; + } + + public int getTimestamp() { + return timestamp; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/interpolation/BasicSpline.java b/src/main/java/eu/crushedpixel/replaymod/interpolation/BasicSpline.java index 58c9dab0..002b588a 100755 --- a/src/main/java/eu/crushedpixel/replaymod/interpolation/BasicSpline.java +++ b/src/main/java/eu/crushedpixel/replaymod/interpolation/BasicSpline.java @@ -2,21 +2,20 @@ package eu.crushedpixel.replaymod.interpolation; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; import java.util.Collection; import java.util.List; public abstract class BasicSpline { - public void calcNaturalCubic(List valueCollection, Field val, Collection cubicCollection) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { - int num = valueCollection.size()-1; + public void calcNaturalCubic(List valueCollection, Field val, Collection cubicCollection) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { + int num = valueCollection.size() - 1; - double[] gamma = new double[num+1]; - double[] delta = new double[num+1]; - double[] D = new double[num+1]; + double[] gamma = new double[num + 1]; + double[] delta = new double[num + 1]; + double[] D = new double[num + 1]; - int i; - /* - We solve the equation + int i; + /* + We solve the equation [2 1 ] [D[0]] [3(x[1] - x[0]) ] |1 4 1 | |D[1]| |3(x[2] - x[0]) | | 1 4 1 | | . | = | . | @@ -27,45 +26,46 @@ public abstract class BasicSpline { by using row operations to convert the matrix to upper triangular and then back sustitution. The D[i] are the derivatives at the knots. */ - gamma[0] = 1.0f / 2.0f; - for(i=1; i< num; i++) { - gamma[i] = 1.0f/(4.0f - gamma[i-1]); - } - gamma[num] = 1.0f/(2.0f - gamma[num-1]); + gamma[0] = 1.0f / 2.0f; + for(i = 1; i < num; i++) { + gamma[i] = 1.0f / (4.0f - gamma[i - 1]); + } + gamma[num] = 1.0f / (2.0f - gamma[num - 1]); - Double p0 = val.getDouble(valueCollection.get(0)); - Double p1 = val.getDouble(valueCollection.get(1)); + Double p0 = val.getDouble(valueCollection.get(0)); + Double p1 = val.getDouble(valueCollection.get(1)); - delta[0] = 3.0f * (p1 - p0) * gamma[0]; - for(i=1; i< num; i++) { - p0 = val.getDouble(valueCollection.get(i-1)); - p1 = val.getDouble(valueCollection.get(i+1)); - delta[i] = (3.0f * (p1 - p0) - delta[i - 1]) * gamma[i]; - } - p0 = val.getDouble(valueCollection.get(num-1)); - p1 = val.getDouble(valueCollection.get(num)); + delta[0] = 3.0f * (p1 - p0) * gamma[0]; + for(i = 1; i < num; i++) { + p0 = val.getDouble(valueCollection.get(i - 1)); + p1 = val.getDouble(valueCollection.get(i + 1)); + delta[i] = (3.0f * (p1 - p0) - delta[i - 1]) * gamma[i]; + } - delta[num] = (3.0f * (p1 - p0) - delta[num - 1]) * gamma[num]; + p0 = val.getDouble(valueCollection.get(num - 1)); + p1 = val.getDouble(valueCollection.get(num)); - D[num] = delta[num]; - for(i=num-1; i >= 0; i--) { - D[i] = delta[i] - gamma[i] * D[i+1]; - } + delta[num] = (3.0f * (p1 - p0) - delta[num - 1]) * gamma[num]; - //now compute the coefficients of the cubics - cubicCollection.clear(); + D[num] = delta[num]; + for(i = num - 1; i >= 0; i--) { + D[i] = delta[i] - gamma[i] * D[i + 1]; + } - for(i=0; i { - public LinearInterpolation() { - points = new ArrayList(); - } - - protected List points = new ArrayList(); - - public abstract K getPoint(float position); - - public void addPoint(K point) { - points.add(point); - } - - public void clearPoints() { - points = new ArrayList(); - } - - protected Pair> getCurrentPoints(float position) { - if(points.size() == 0) return null; - position = position * (points.size()-1); - int cubicNum = (int)Math.min(points.size()-1, position); - float cubicPos = (position - cubicNum); - - if(cubicNum == points.size()-1) { - cubicNum--; - cubicPos++; - } + protected List points = new ArrayList(); - if(cubicNum < 0) { - return new Pair>(cubicPos, new Pair(points.get(cubicNum+1), points.get(cubicNum+1))); - } - return new Pair>(cubicPos, new Pair(points.get(cubicNum), points.get(cubicNum+1))); - } - - protected double getInterpolatedValue(double val1, double val2, float perc) { - return val1+((val2-val1)*perc); - } + public LinearInterpolation() { + points = new ArrayList(); + } + + public abstract K getPoint(float position); + + public void addPoint(K point) { + points.add(point); + } + + public void clearPoints() { + points = new ArrayList(); + } + + protected Pair> getCurrentPoints(float position) { + if(points.size() == 0) return null; + position = position * (points.size() - 1); + int cubicNum = (int) Math.min(points.size() - 1, position); + float cubicPos = (position - cubicNum); + + if(cubicNum == points.size() - 1) { + cubicNum--; + cubicPos++; + } + + if(cubicNum < 0) { + return new Pair>(cubicPos, new Pair(points.get(cubicNum + 1), points.get(cubicNum + 1))); + } + return new Pair>(cubicPos, new Pair(points.get(cubicNum), points.get(cubicNum + 1))); + } + + protected double getInterpolatedValue(double val1, double val2, float perc) { + return val1 + ((val2 - val1) * perc); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/interpolation/LinearPoint.java b/src/main/java/eu/crushedpixel/replaymod/interpolation/LinearPoint.java index c77f53cf..ffb8736b 100755 --- a/src/main/java/eu/crushedpixel/replaymod/interpolation/LinearPoint.java +++ b/src/main/java/eu/crushedpixel/replaymod/interpolation/LinearPoint.java @@ -5,25 +5,25 @@ import eu.crushedpixel.replaymod.holders.Position; public class LinearPoint extends LinearInterpolation { - @Override - public Position getPoint(float positionIn) { - Pair> pair = getCurrentPoints(positionIn); - if(pair == null) return null; - - float perc = pair.first(); + @Override + public Position getPoint(float positionIn) { + Pair> pair = getCurrentPoints(positionIn); + if(pair == null) return null; - Position first = pair.second().first(); - Position second = pair.second().second(); - - double x = getInterpolatedValue(first.getX(), second.getX(), perc); - double y = getInterpolatedValue(first.getY(), second.getY(), perc); - double z = getInterpolatedValue(first.getZ(), second.getZ(), perc); - - float pitch = (float)getInterpolatedValue(first.getPitch(), second.getPitch(), perc); - float yaw = (float)getInterpolatedValue(first.getYaw(), second.getYaw(), perc); - - Position inter = new Position(x, y, z, pitch, yaw); + float perc = pair.first(); - return inter; - } + Position first = pair.second().first(); + Position second = pair.second().second(); + + double x = getInterpolatedValue(first.getX(), second.getX(), perc); + double y = getInterpolatedValue(first.getY(), second.getY(), perc); + double z = getInterpolatedValue(first.getZ(), second.getZ(), perc); + + float pitch = (float) getInterpolatedValue(first.getPitch(), second.getPitch(), perc); + float yaw = (float) getInterpolatedValue(first.getYaw(), second.getYaw(), perc); + + Position inter = new Position(x, y, z, pitch, yaw); + + return inter; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/interpolation/LinearTimestamp.java b/src/main/java/eu/crushedpixel/replaymod/interpolation/LinearTimestamp.java index 5bc08eec..8f3b7866 100755 --- a/src/main/java/eu/crushedpixel/replaymod/interpolation/LinearTimestamp.java +++ b/src/main/java/eu/crushedpixel/replaymod/interpolation/LinearTimestamp.java @@ -1,22 +1,21 @@ package eu.crushedpixel.replaymod.interpolation; import akka.japi.Pair; -import eu.crushedpixel.replaymod.holders.Position; public class LinearTimestamp extends LinearInterpolation { - @Override - public Integer getPoint(float position) { - Pair> pair = getCurrentPoints(position); - if(pair == null) return null; - - float perc = pair.first(); + @Override + public Integer getPoint(float position) { + Pair> pair = getCurrentPoints(position); + if(pair == null) return null; - int first = pair.second().first(); - int second = pair.second().second(); + float perc = pair.first(); - int val = (int)getInterpolatedValue(first, second, perc); + int first = pair.second().first(); + int second = pair.second().second(); - return val; - } + int val = (int) getInterpolatedValue(first, second, perc); + + return val; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/interpolation/SplinePoint.java b/src/main/java/eu/crushedpixel/replaymod/interpolation/SplinePoint.java index d851a86c..e16d5877 100755 --- a/src/main/java/eu/crushedpixel/replaymod/interpolation/SplinePoint.java +++ b/src/main/java/eu/crushedpixel/replaymod/interpolation/SplinePoint.java @@ -1,92 +1,86 @@ package eu.crushedpixel.replaymod.interpolation; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Vector; - -import com.sun.javafx.geom.Vec3d; - import eu.crushedpixel.replaymod.holders.Position; -public class SplinePoint extends BasicSpline{ - private Vector points; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.util.Vector; - private Vector xCubics; - private Vector yCubics; - private Vector zCubics; - private Vector pitchCubics; - private Vector yawCubics; +public class SplinePoint extends BasicSpline { + private static final Object[] EMPTYOBJ = new Object[]{}; + private Vector points; + private Vector xCubics; + private Vector yCubics; + private Vector zCubics; + private Vector pitchCubics; + private Vector yawCubics; + private Field vectorX; + private Field vectorY; + private Field vectorZ; + private Field vectorPitch; + private Field vectorYaw; - private Field vectorX; - private Field vectorY; - private Field vectorZ; - private Field vectorPitch; - private Field vectorYaw; - - private static final Object[] EMPTYOBJ = new Object[] { }; + public SplinePoint() { + this.points = new Vector(); - public SplinePoint() { - this.points = new Vector(); + this.xCubics = new Vector(); + this.yCubics = new Vector(); + this.zCubics = new Vector(); + this.pitchCubics = new Vector(); + this.yawCubics = new Vector(); - this.xCubics = new Vector(); - this.yCubics = new Vector(); - this.zCubics = new Vector(); - this.pitchCubics = new Vector(); - this.yawCubics = new Vector(); + try { + vectorX = Position.class.getDeclaredField("x"); + vectorY = Position.class.getDeclaredField("y"); + vectorZ = Position.class.getDeclaredField("z"); + vectorPitch = Position.class.getDeclaredField("pitch"); + vectorYaw = Position.class.getDeclaredField("yaw"); + vectorX.setAccessible(true); + vectorY.setAccessible(true); + vectorZ.setAccessible(true); + vectorPitch.setAccessible(true); + vectorYaw.setAccessible(true); + } catch(SecurityException e) { + e.printStackTrace(); + } catch(NoSuchFieldException e) { + e.printStackTrace(); + } + } - try { - vectorX = Position.class.getDeclaredField("x"); - vectorY = Position.class.getDeclaredField("y"); - vectorZ = Position.class.getDeclaredField("z"); - vectorPitch = Position.class.getDeclaredField("pitch"); - vectorYaw = Position.class.getDeclaredField("yaw"); - vectorX.setAccessible(true); - vectorY.setAccessible(true); - vectorZ.setAccessible(true); - vectorPitch.setAccessible(true); - vectorYaw.setAccessible(true); - } catch (SecurityException e) { - e.printStackTrace(); - } catch (NoSuchFieldException e) { - e.printStackTrace(); - } - } + public void addPoint(Position point) { + this.points.add(point); + } - public void addPoint(Position point) { - this.points.add(point); - } + public Vector getPoints() { + return points; + } - public Vector getPoints() { - return points; - } + public void calcSpline() { + try { + calcNaturalCubic(points, vectorX, xCubics); + calcNaturalCubic(points, vectorY, yCubics); + calcNaturalCubic(points, vectorZ, zCubics); + calcNaturalCubic(points, vectorPitch, pitchCubics); + calcNaturalCubic(points, vectorYaw, yawCubics); + } catch(IllegalArgumentException e) { + e.printStackTrace(); + } catch(IllegalAccessException e) { + e.printStackTrace(); + } catch(InvocationTargetException e) { + e.printStackTrace(); + } + } - public void calcSpline() { - try { - calcNaturalCubic(points, vectorX, xCubics); - calcNaturalCubic(points, vectorY, yCubics); - calcNaturalCubic(points, vectorZ, zCubics); - calcNaturalCubic(points, vectorPitch, pitchCubics); - calcNaturalCubic(points, vectorYaw, yawCubics); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } - } + public Position getPoint(float position) { + position = position * xCubics.size(); + int cubicNum = (int) Math.min(xCubics.size() - 1, position); + float cubicPos = (position - cubicNum); - public Position getPoint(float position) { - position = position * xCubics.size(); - int cubicNum = (int)Math.min(xCubics.size()-1, position); - float cubicPos = (position - cubicNum); - - return new Position(xCubics.get(cubicNum).eval(cubicPos), - yCubics.get(cubicNum).eval(cubicPos), - zCubics.get(cubicNum).eval(cubicPos), - (float)pitchCubics.get(cubicNum).eval(cubicPos), - (float)yawCubics.get(cubicNum).eval(cubicPos)); - } + return new Position(xCubics.get(cubicNum).eval(cubicPos), + yCubics.get(cubicNum).eval(cubicPos), + zCubics.get(cubicNum).eval(cubicPos), + (float) pitchCubics.get(cubicNum).eval(cubicPos), + (float) yawCubics.get(cubicNum).eval(cubicPos)); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/online/authentication/AuthenticationHandler.java b/src/main/java/eu/crushedpixel/replaymod/online/authentication/AuthenticationHandler.java index 053450e7..39bfd6c5 100755 --- a/src/main/java/eu/crushedpixel/replaymod/online/authentication/AuthenticationHandler.java +++ b/src/main/java/eu/crushedpixel/replaymod/online/authentication/AuthenticationHandler.java @@ -1,82 +1,53 @@ package eu.crushedpixel.replaymod.online.authentication; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import net.minecraft.client.Minecraft; import eu.crushedpixel.replaymod.ReplayMod; import eu.crushedpixel.replaymod.api.client.ApiClient; import eu.crushedpixel.replaymod.api.client.ApiException; -import eu.crushedpixel.replaymod.reflection.MCPNames; + +import java.io.IOException; public class AuthenticationHandler { - public static final int SUCCESS = 1; - public static final int INVALID = 2; - public static final int NO_CONNECTION = 3; - - private static final ApiClient apiClient = new ApiClient(); - - private static Minecraft mc = Minecraft.getMinecraft(); + public static final int SUCCESS = 1; + public static final int INVALID = 2; + public static final int NO_CONNECTION = 3; - private static String authkey = null; + private static final ApiClient apiClient = new ApiClient(); - public static boolean isAuthenticated() { - return authkey != null; - } - - public static String getKey() { - return authkey; - } - - public static boolean hasDonated(String uuid) throws IOException, ApiException { - return apiClient.hasDonated(uuid); - } - - public static int authenticate(String username, String password) { - try { - authkey = ReplayMod.apiClient.getLogin(username, password).getAuthkey(); - return SUCCESS; - } catch(ApiException e) { - return INVALID; - } catch(Exception e) { - return NO_CONNECTION; - } - } - - public static int logout() { - try { - boolean success = ReplayMod.apiClient.logout(authkey); - authkey = null; - return SUCCESS; - } catch(ApiException e) { - return INVALID; - } catch(Exception e) { - return NO_CONNECTION; - } - } + private static String authkey = null; - private static final List PREMIUM_USERS = new ArrayList() { - { - add("Ender_Workbench"); - add("oleoleMC"); - add("Johni0702"); - add("Rafessor"); - add("bluffamachuck"); - add("Panguino"); - add("SixteenBy16"); - } - }; - - private static boolean isPremiumUsername(String username) { - //TODO: API check with the website - return (PREMIUM_USERS.contains(username) || MCPNames.env.isMCPEnvironment()); - } + public static boolean isAuthenticated() { + return authkey != null; + } - private static boolean isPremiumUUID(String uuid) { - //TODO: API check with the website - return false; - } + public static String getKey() { + return authkey; + } + + public static boolean hasDonated(String uuid) throws IOException, ApiException { + return apiClient.hasDonated(uuid); + } + + public static int authenticate(String username, String password) { + try { + authkey = ReplayMod.apiClient.getLogin(username, password).getAuthkey(); + return SUCCESS; + } catch(ApiException e) { + return INVALID; + } catch(Exception e) { + return NO_CONNECTION; + } + } + + public static int logout() { + try { + ReplayMod.apiClient.logout(authkey); + authkey = null; + return SUCCESS; + } catch(ApiException e) { + return INVALID; + } catch(Exception e) { + return NO_CONNECTION; + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/recording/ConnectionEventHandler.java b/src/main/java/eu/crushedpixel/replaymod/recording/ConnectionEventHandler.java index 038f816a..fb1872f8 100755 --- a/src/main/java/eu/crushedpixel/replaymod/recording/ConnectionEventHandler.java +++ b/src/main/java/eu/crushedpixel/replaymod/recording/ConnectionEventHandler.java @@ -1,8 +1,7 @@ package eu.crushedpixel.replaymod.recording; import eu.crushedpixel.replaymod.ReplayMod; -import eu.crushedpixel.replaymod.chat.ChatMessageRequests; -import eu.crushedpixel.replaymod.chat.ChatMessageRequests.ChatMessageType; +import eu.crushedpixel.replaymod.chat.ChatMessageHandler.ChatMessageType; import eu.crushedpixel.replaymod.utils.ReplayFileIO; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; @@ -25,127 +24,123 @@ import java.util.Map.Entry; public class ConnectionEventHandler { - private static final String decoderKey = "decoder"; - private static final String packetHandlerKey = "packet_handler"; - private static final String DATE_FORMAT = "yyyy_MM_dd_HH_mm_ss"; - private static final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); - public static final String TEMP_FILE_EXTENSION = ".tmcpr"; - public static final String JSON_FILE_EXTENSION = ".json"; - public static final String ZIP_FILE_EXTENSION = ".mcpr"; + public static final String TEMP_FILE_EXTENSION = ".tmcpr"; + public static final String JSON_FILE_EXTENSION = ".json"; + public static final String ZIP_FILE_EXTENSION = ".mcpr"; + private static final String decoderKey = "decoder"; + private static final String packetHandlerKey = "packet_handler"; + private static final String DATE_FORMAT = "yyyy_MM_dd_HH_mm_ss"; + private static final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); + private static PacketListener packetListener = null; + private static boolean isRecording = false; + private File currentFile; + private String fileName; - private File currentFile; - private String fileName; + public static boolean isRecording() { + return isRecording; + } - private static PacketListener packetListener = null; + public static void insertPacket(Packet packet) { + if(!isRecording || packetListener == null) { + String reason = isRecording ? " (recording)" : " (null)"; + System.out.println("Invalid attempt to insert Packet!" + reason); + return; + } + try { + packetListener.saveOnly(packet); + } catch(Exception e) { + e.printStackTrace(); + } + } - private static boolean isRecording = false; + @SubscribeEvent + public void onConnectedToServerEvent(ClientConnectedToServerEvent event) { + System.out.println("Connected to server"); - public static boolean isRecording() { - return isRecording; - } + ReplayMod.chatMessageHandler.initialize(); + ReplayMod.recordingHandler.resetVars(); - public static void insertPacket(Packet packet) { - if(!isRecording || packetListener == null) { - String reason = isRecording ? " (recording)":" (null)"; - System.out.println("Invalid attempt to insert Packet!"+reason); - return; - } - try { - packetListener.saveOnly(packet); - } catch (Exception e) { - e.printStackTrace(); - } - } + try { + if(event.isLocal) { + if(!ReplayMod.replaySettings.isEnableRecordingSingleplayer()) { + System.out.println("Singleplayer Recording is disabled"); + return; + } + } else { + if(!ReplayMod.replaySettings.isEnableRecordingServer()) { + System.out.println("Multiplayer Recording is disabled"); + return; + } + } + NetworkManager nm = event.manager; + String worldName = ""; + if(!event.isLocal) { + worldName = ((InetSocketAddress) nm.getRemoteAddress()).getHostName(); + } + Channel channel = nm.channel(); + ChannelPipeline pipeline = channel.pipeline(); - @SubscribeEvent - public void onConnectedToServerEvent(ClientConnectedToServerEvent event) { - System.out.println("Connected to server"); + List channelHandlerKeys = new ArrayList(); + Iterator> it = pipeline.iterator(); + while(it.hasNext()) { + Entry entry = it.next(); + channelHandlerKeys.add(entry.getKey()); + } - ChatMessageRequests.initialize(); - - ReplayMod.recordingHandler.resetVars(); + File folder = ReplayFileIO.getReplayFolder(); - try { - if(event.isLocal) { - if(!ReplayMod.replaySettings.isEnableRecordingSingleplayer()) { - System.out.println("Singleplayer Recording is disabled"); - return; - } - } else { - if(!ReplayMod.replaySettings.isEnableRecordingServer()) { - System.out.println("Multiplayer Recording is disabled"); - return; - } - } - NetworkManager nm = event.manager; - String worldName = ""; - if(!event.isLocal) { - worldName = ((InetSocketAddress)nm.getRemoteAddress()).getHostName(); - } - Channel channel = nm.channel(); - ChannelPipeline pipeline = channel.pipeline(); + fileName = sdf.format(Calendar.getInstance().getTime()); + currentFile = new File(folder, fileName + TEMP_FILE_EXTENSION); - List channelHandlerKeys = new ArrayList(); - Iterator> it = pipeline.iterator(); - while(it.hasNext()) { - Entry entry = it.next(); - channelHandlerKeys.add(entry.getKey()); - } + currentFile.createNewFile(); - File folder = ReplayFileIO.getReplayFolder(); + PacketListener insert = null; - fileName = sdf.format(Calendar.getInstance().getTime()); - currentFile = new File(folder, fileName+TEMP_FILE_EXTENSION); + pipeline.addBefore(packetHandlerKey, "replay_recorder", insert = new PacketListener + (currentFile, fileName, worldName, System.currentTimeMillis(), event.isLocal)); + ReplayMod.chatMessageHandler.addChatMessage("Recording started!", ChatMessageType.INFORMATION); + isRecording = true; - currentFile.createNewFile(); + final PacketListener listener = insert; - PacketListener insert = null; + if(insert != null && event.isLocal) { + new Thread(new Runnable() { - pipeline.addBefore(packetHandlerKey, "replay_recorder", insert = new PacketListener - (currentFile, fileName, worldName, System.currentTimeMillis(), event.isLocal)); - ChatMessageRequests.addChatMessage("Recording started!", ChatMessageType.INFORMATION); - isRecording = true; + @Override + public void run() { + String worldName = null; + while(worldName == null) { + try { + worldName = MinecraftServer.getServer().getWorldName(); + listener.setWorldName(worldName); + return; - final PacketListener listener = insert; + } catch(Exception e) { + try { + Thread.sleep(100); + } catch(InterruptedException e1) { + e1.printStackTrace(); + } + } + } - if(insert != null && event.isLocal) { - new Thread(new Runnable() { + } + }).start(); + } - @Override - public void run() { - String worldName = null; - while(worldName == null) { - try { - worldName = MinecraftServer.getServer().getWorldName(); - listener.setWorldName(worldName); - return; + packetListener = listener; - } catch(Exception e) { - try { - Thread.sleep(100); - } catch (InterruptedException e1) { - e1.printStackTrace(); - } - } - } + } catch(Exception e) { + ReplayMod.chatMessageHandler.addChatMessage("Failed to start recording!", ChatMessageType.WARNING); + e.printStackTrace(); + } + } - } - }).start(); - } - - packetListener = listener; - - } catch(Exception e) { - ChatMessageRequests.addChatMessage("Failed to start recording!", ChatMessageType.WARNING); - e.printStackTrace(); - } - } - - @SubscribeEvent - public void onDisconnectedFromServerEvent(ClientDisconnectionFromServerEvent event) { - System.out.println("Disconnected from server"); - isRecording = false; - packetListener = null; - ChatMessageRequests.stop(); - } + @SubscribeEvent + public void onDisconnectedFromServerEvent(ClientDisconnectionFromServerEvent event) { + System.out.println("Disconnected from server"); + isRecording = false; + packetListener = null; + ReplayMod.chatMessageHandler.stop(); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/recording/DataListener.java b/src/main/java/eu/crushedpixel/replaymod/recording/DataListener.java index fbb22fcd..24733fe2 100755 --- a/src/main/java/eu/crushedpixel/replaymod/recording/DataListener.java +++ b/src/main/java/eu/crushedpixel/replaymod/recording/DataListener.java @@ -1,175 +1,153 @@ package eu.crushedpixel.replaymod.recording; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandlerAdapter; - -import java.io.BufferedOutputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.ActiveRenderInfo; - import com.google.gson.Gson; - -import eu.crushedpixel.replaymod.ReplayMod; import eu.crushedpixel.replaymod.gui.GuiReplaySaving; import eu.crushedpixel.replaymod.holders.PacketData; import eu.crushedpixel.replaymod.utils.ReplayFileIO; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import net.minecraft.client.Minecraft; + +import java.io.*; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map.Entry; +import java.util.Set; +import java.util.concurrent.ConcurrentLinkedQueue; public abstract class DataListener extends ChannelInboundHandlerAdapter { - protected File file; - protected Long startTime = null; - protected String name; - protected String worldName; + protected File file; + protected Long startTime = null; + protected String name; + protected String worldName; + protected long lastSentPacket = 0; + protected boolean alive = true; + protected DataWriter dataWriter; + protected Set players = new HashSet(); + private boolean singleplayer; + private Gson gson = new Gson(); - private boolean singleplayer; + public DataListener(File file, String name, String worldName, long startTime, boolean singleplayer) throws FileNotFoundException { + this.file = file; + this.startTime = startTime; + this.name = name; + this.worldName = worldName; + this.singleplayer = singleplayer; - protected long lastSentPacket = 0; + System.out.println(worldName); - protected boolean alive = true; + FileOutputStream fos = new FileOutputStream(file); + BufferedOutputStream bos = new BufferedOutputStream(fos); + DataOutputStream out = new DataOutputStream(bos); + dataWriter = new DataWriter(out); + } - protected DataWriter dataWriter; + public void setWorldName(String worldName) { + this.worldName = worldName; + System.out.println(worldName); + } - private Gson gson = new Gson(); + @Override + public void channelInactive(ChannelHandlerContext ctx) throws Exception { + dataWriter.requestFinish(players); + } - protected Set players = new HashSet(); + public class DataWriter { - public void setWorldName(String worldName) { - this.worldName = worldName; - System.out.println(worldName); - } + private boolean active = true; - public DataListener(File file, String name, String worldName, long startTime, boolean singleplayer) throws FileNotFoundException { - this.file = file; - this.startTime = startTime; - this.name = name; - this.worldName = worldName; - this.singleplayer = singleplayer; + private ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue(); + private DataOutputStream stream; + Thread outputThread = new Thread(new Runnable() { - System.out.println(worldName); + @Override + public void run() { - FileOutputStream fos = new FileOutputStream(file); - BufferedOutputStream bos = new BufferedOutputStream(fos); - DataOutputStream out = new DataOutputStream(bos); - dataWriter = new DataWriter(out); - } + HashMap counts = new HashMap(); - @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception { - dataWriter.requestFinish(players); - } + while(active) { + PacketData dataReciever = queue.poll(); + if(dataReciever != null) { + //write the ByteBuf to the given OutputStream - public class DataWriter { + byte[] array = dataReciever.getByteArray(); - private boolean active = true; + if(array != null) { + try { + ReplayFileIO.writePacket(dataReciever, stream); + stream.flush(); + } catch(Exception e) { + e.printStackTrace(); + } + } - private ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue(); + } else { + try { + //let the Thread sleep for 1/4 second and queue up new Packets + Thread.sleep(250L); + } catch(InterruptedException e) { + e.printStackTrace(); + } + } + } - public void writeData(PacketData data) { - queue.add(data); - } + try { + stream.flush(); + stream.close(); + } catch(Exception e) { + e.printStackTrace(); + } - Thread outputThread = new Thread(new Runnable() { + for(Entry entries : counts.entrySet()) { + System.out.println(entries.getKey() + "| " + entries.getValue()); + } - @Override - public void run() { + } + }); - HashMap counts = new HashMap(); + public DataWriter(DataOutputStream stream) { + this.stream = stream; + outputThread.start(); + } - while(active) { - PacketData dataReciever = queue.poll(); - if(dataReciever != null) { - //write the ByteBuf to the given OutputStream + public void writeData(PacketData data) { + queue.add(data); + } - byte[] array = dataReciever.getByteArray(); + public void requestFinish(Set players) { + active = false; - if(array != null) { - try { - ReplayFileIO.writePacket(dataReciever, stream); - stream.flush(); - } catch(Exception e) { - e.printStackTrace(); - } - } + try { + GuiReplaySaving.replaySaving = true; - } else { - try { - //let the Thread sleep for 1/4 second and queue up new Packets - Thread.sleep(250L); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } + String mcversion = Minecraft.getMinecraft().getVersion(); + String[] split = mcversion.split("-"); + if(split.length > 0) { + mcversion = split[0]; + } - try { - stream.flush(); - stream.close(); - } catch (Exception e) { - e.printStackTrace(); - } + String[] pl = players.toArray(new String[players.size()]); - for(Entry entries : counts.entrySet()) { - System.out.println(entries.getKey()+ "| "+entries.getValue()); - } + ReplayMetaData metaData = new ReplayMetaData(singleplayer, worldName, (int) lastSentPacket, startTime, pl, mcversion); + String json = gson.toJson(metaData); - } - }); + File folder = ReplayFileIO.getReplayFolder(); - private DataOutputStream stream; + File archive = new File(folder, name + ConnectionEventHandler.ZIP_FILE_EXTENSION); + archive.createNewFile(); - public DataWriter(DataOutputStream stream) { - this.stream = stream; - outputThread.start(); - } + ReplayFileIO.writeReplayFile(archive, file, metaData); - public void requestFinish(Set players) { - active = false; + file.delete(); - try { - GuiReplaySaving.replaySaving = true; + GuiReplaySaving.replaySaving = false; + } catch(Exception e) { + e.printStackTrace(); + GuiReplaySaving.replaySaving = false; + } + } - String mcversion = Minecraft.getMinecraft().getVersion(); - String[] split = mcversion.split("-"); - if(split.length > 0) { - mcversion = split[0]; - } - - String[] pl = players.toArray(new String[players.size()]); - - ReplayMetaData metaData = new ReplayMetaData(singleplayer, worldName, (int)lastSentPacket, startTime, pl, mcversion); - String json = gson.toJson(metaData); - - File folder = ReplayFileIO.getReplayFolder(); - - File archive = new File(folder, name+ConnectionEventHandler.ZIP_FILE_EXTENSION); - archive.createNewFile(); - - ReplayFileIO.writeReplayFile(archive, file, metaData); - - file.delete(); - - GuiReplaySaving.replaySaving = false; - } catch(Exception e) { - e.printStackTrace(); - GuiReplaySaving.replaySaving = false; - } - } - - } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/recording/PacketListener.java b/src/main/java/eu/crushedpixel/replaymod/recording/PacketListener.java index e7cd371e..3204b349 100755 --- a/src/main/java/eu/crushedpixel/replaymod/recording/PacketListener.java +++ b/src/main/java/eu/crushedpixel/replaymod/recording/PacketListener.java @@ -1,8 +1,15 @@ package eu.crushedpixel.replaymod.recording; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; +import eu.crushedpixel.replaymod.holders.PacketData; +import eu.crushedpixel.replaymod.reflection.MCPNames; +import eu.crushedpixel.replaymod.utils.ReplayFileIO; import io.netty.channel.ChannelHandlerContext; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.DataWatcher; +import net.minecraft.network.Packet; +import net.minecraft.network.play.server.S0CPacketSpawnPlayer; +import net.minecraft.network.play.server.S0DPacketCollectItem; +import net.minecraft.network.play.server.S0FPacketSpawnMob; import java.io.File; import java.io.FileNotFoundException; @@ -10,130 +17,116 @@ import java.io.IOException; import java.lang.reflect.Field; import java.util.UUID; -import net.minecraft.client.Minecraft; -import net.minecraft.entity.DataWatcher; -import net.minecraft.network.EnumPacketDirection; -import net.minecraft.network.Packet; -import net.minecraft.network.play.server.S0CPacketSpawnPlayer; -import net.minecraft.network.play.server.S0DPacketCollectItem; -import net.minecraft.network.play.server.S0FPacketSpawnMob; -import eu.crushedpixel.replaymod.chat.ChatMessageRequests; -import eu.crushedpixel.replaymod.chat.ChatMessageRequests.ChatMessageType; -import eu.crushedpixel.replaymod.holders.PacketData; -import eu.crushedpixel.replaymod.reflection.MCPNames; -import eu.crushedpixel.replaymod.utils.ReplayFileIO; - public class PacketListener extends DataListener { - public PacketListener(File file, String name, String worldName, long startTime, boolean singleplayer) throws FileNotFoundException { - super(file, name, worldName, startTime, singleplayer); - } + private static final Minecraft mc = Minecraft.getMinecraft(); + private static Field spawnMobDataWatcher, spawnPlayerDataWatcher; - private static final Minecraft mc = Minecraft.getMinecraft(); + static { + try { + spawnMobDataWatcher = S0FPacketSpawnMob.class.getDeclaredField(MCPNames.field("field_149043_l")); + spawnMobDataWatcher.setAccessible(true); - private ChannelHandlerContext context = null; + spawnPlayerDataWatcher = S0CPacketSpawnPlayer.class.getDeclaredField(MCPNames.field("field_148960_i")); + spawnPlayerDataWatcher.setAccessible(true); + } catch(Exception e) { + e.printStackTrace(); + } + } - public void saveOnly(Packet packet) { - try { - if(packet instanceof S0CPacketSpawnPlayer) { - UUID uuid = ((S0CPacketSpawnPlayer)packet).func_179819_c(); - players.add(uuid.toString()); - } - - PacketData pd = getPacketData(context, packet); - writeData(pd); - } catch(Exception e) { - e.printStackTrace(); - } - } + private ChannelHandlerContext context = null; - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - if(ctx == null) { - if(context == null) { - return; - } else { - ctx = context; - } - } - this.context = ctx; - if(!alive) { - super.channelRead(ctx, msg); - return; - } - if(msg instanceof Packet) { - try { - Packet packet = (Packet)msg; + public PacketListener(File file, String name, String worldName, long startTime, boolean singleplayer) throws FileNotFoundException { + super(file, name, worldName, startTime, singleplayer); + } - if(packet instanceof S0DPacketCollectItem) { - if(mc.thePlayer != null || - ((S0DPacketCollectItem)packet).func_149353_d() == mc.thePlayer.getEntityId()) { - super.channelRead(ctx, msg); - return; - } - } - - if(packet instanceof S0CPacketSpawnPlayer) { - UUID uuid = ((S0CPacketSpawnPlayer)packet).func_179819_c(); - players.add(uuid.toString()); - } + public void saveOnly(Packet packet) { + try { + if(packet instanceof S0CPacketSpawnPlayer) { + UUID uuid = ((S0CPacketSpawnPlayer) packet).func_179819_c(); + players.add(uuid.toString()); + } - PacketData pd = getPacketData(ctx, packet); - writeData(pd); - } catch(Exception e) { - e.printStackTrace(); - } + PacketData pd = getPacketData(context, packet); + writeData(pd); + } catch(Exception e) { + e.printStackTrace(); + } + } - } + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + if(ctx == null) { + if(context == null) { + return; + } else { + ctx = context; + } + } + this.context = ctx; + if(!alive) { + super.channelRead(ctx, msg); + return; + } + if(msg instanceof Packet) { + try { + Packet packet = (Packet) msg; - super.channelRead(ctx, msg); - } + if(packet instanceof S0DPacketCollectItem) { + if(mc.thePlayer != null || + ((S0DPacketCollectItem) packet).func_149353_d() == mc.thePlayer.getEntityId()) { + super.channelRead(ctx, msg); + return; + } + } - private void writeData(PacketData pd) { - dataWriter.writeData(pd); - lastSentPacket = pd.getTimestamp(); - } - - private static Field spawnMobDataWatcher, spawnPlayerDataWatcher; - - static { - try { - spawnMobDataWatcher = S0FPacketSpawnMob.class.getDeclaredField(MCPNames.field("field_149043_l")); - spawnMobDataWatcher.setAccessible(true); - - spawnPlayerDataWatcher = S0CPacketSpawnPlayer.class.getDeclaredField(MCPNames.field("field_148960_i")); - spawnPlayerDataWatcher.setAccessible(true); - } catch(Exception e) { - e.printStackTrace(); - } - } - - private PacketData getPacketData(ChannelHandlerContext ctx, Packet packet) throws IOException, IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + if(packet instanceof S0CPacketSpawnPlayer) { + UUID uuid = ((S0CPacketSpawnPlayer) packet).func_179819_c(); + players.add(uuid.toString()); + } - if(startTime == null) startTime = System.currentTimeMillis(); + PacketData pd = getPacketData(ctx, packet); + writeData(pd); + } catch(Exception e) { + e.printStackTrace(); + } - int timestamp = (int)(System.currentTimeMillis() - startTime); - - if(packet instanceof S0FPacketSpawnMob) { - DataWatcher l = (DataWatcher)spawnMobDataWatcher.get(packet); - DataWatcher dw = new DataWatcher(null); - if(l == null) { - spawnMobDataWatcher.set(packet, dw); - } - } + } - if(packet instanceof S0CPacketSpawnPlayer) { - DataWatcher l = (DataWatcher)spawnPlayerDataWatcher.get(packet); - DataWatcher dw = new DataWatcher(null); - if(l == null) { - spawnPlayerDataWatcher.set(packet, dw); - } - } + super.channelRead(ctx, msg); + } - byte[] array = ReplayFileIO.serializePacket(packet); + private void writeData(PacketData pd) { + dataWriter.writeData(pd); + lastSentPacket = pd.getTimestamp(); + } - return new PacketData(array, timestamp); - } + private PacketData getPacketData(ChannelHandlerContext ctx, Packet packet) throws IOException, IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + + if(startTime == null) startTime = System.currentTimeMillis(); + + int timestamp = (int) (System.currentTimeMillis() - startTime); + + if(packet instanceof S0FPacketSpawnMob) { + DataWatcher l = (DataWatcher) spawnMobDataWatcher.get(packet); + DataWatcher dw = new DataWatcher(null); + if(l == null) { + spawnMobDataWatcher.set(packet, dw); + } + } + + if(packet instanceof S0CPacketSpawnPlayer) { + DataWatcher l = (DataWatcher) spawnPlayerDataWatcher.get(packet); + DataWatcher dw = new DataWatcher(null); + if(l == null) { + spawnPlayerDataWatcher.set(packet, dw); + } + } + + byte[] array = ReplayFileIO.serializePacket(packet); + + return new PacketData(array, timestamp); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/recording/PacketSerializer.java b/src/main/java/eu/crushedpixel/replaymod/recording/PacketSerializer.java index 6e290123..349be9a9 100755 --- a/src/main/java/eu/crushedpixel/replaymod/recording/PacketSerializer.java +++ b/src/main/java/eu/crushedpixel/replaymod/recording/PacketSerializer.java @@ -3,36 +3,35 @@ package eu.crushedpixel.replaymod.recording; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; - -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.IOException; -import java.io.ObjectInputStream; - -import net.minecraft.network.EnumConnectionState; -import net.minecraft.network.EnumPacketDirection; -import net.minecraft.network.NetworkManager; -import net.minecraft.network.Packet; -import net.minecraft.network.PacketBuffer; -import net.minecraft.network.play.server.S0CPacketSpawnPlayer; +import net.minecraft.network.*; import net.minecraft.util.MessageSerializer; +import java.io.IOException; + public class PacketSerializer extends MessageSerializer { - public PacketSerializer(EnumPacketDirection direction) { - super(direction); - } + public PacketSerializer(EnumPacketDirection direction) { + super(direction); + } - @Override - public void encode(ChannelHandlerContext ctx, Packet packet, ByteBuf byteBuf) throws IOException { - EnumConnectionState state = ((EnumConnectionState)ctx.channel().attr(NetworkManager.attrKeyConnectionState).get()); - encode(state, packet, byteBuf); - } - - public void encode(EnumConnectionState state, Packet packet, ByteBuf byteBuf) { - Integer integer = state.getPacketId(EnumPacketDirection.CLIENTBOUND, packet); + public static ByteBuf toByteBuf(byte[] bytes) throws IOException, ClassNotFoundException { + ByteBuf bb; + bb = Unpooled.buffer(bytes.length); + bb.writeBytes(bytes); - if (integer == null) { + return bb; + } + + @Override + public void encode(ChannelHandlerContext ctx, Packet packet, ByteBuf byteBuf) throws IOException { + EnumConnectionState state = ((EnumConnectionState) ctx.channel().attr(NetworkManager.attrKeyConnectionState).get()); + encode(state, packet, byteBuf); + } + + public void encode(EnumConnectionState state, Packet packet, ByteBuf byteBuf) { + Integer integer = state.getPacketId(EnumPacketDirection.CLIENTBOUND, packet); + + if(integer == null) { return; } else { PacketBuffer packetbuffer = new PacketBuffer(byteBuf); @@ -40,20 +39,11 @@ public class PacketSerializer extends MessageSerializer { try { packet.writePacketData(packetbuffer); - } - catch (Throwable throwable) { - throwable.printStackTrace(); + } catch(Throwable throwable) { + throwable.printStackTrace(); } } - } - - public static ByteBuf toByteBuf(byte[] bytes) throws IOException, ClassNotFoundException { - ByteBuf bb; - bb = Unpooled.buffer(bytes.length); - bb.writeBytes(bytes); - - return bb; - } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/recording/ReplayMetaData.java b/src/main/java/eu/crushedpixel/replaymod/recording/ReplayMetaData.java index 32fb1284..83af9db3 100755 --- a/src/main/java/eu/crushedpixel/replaymod/recording/ReplayMetaData.java +++ b/src/main/java/eu/crushedpixel/replaymod/recording/ReplayMetaData.java @@ -1,45 +1,49 @@ package eu.crushedpixel.replaymod.recording; -import java.util.Date; -import java.util.List; - public class ReplayMetaData { - - private boolean singleplayer; - private String serverName; - private int duration; - private long date; - private String[] players; - private String mcversion; - - public ReplayMetaData(boolean singleplayer, String serverName, - int duration, long date, String[] players, String mcversion) { - this.singleplayer = singleplayer; - this.serverName = serverName; - this.duration = duration; - this.date = date; - this.players = players; - this.mcversion = mcversion; - } - public boolean isSingleplayer() { - return singleplayer; - } - public String getServerName() { - return serverName; - } - public int getDuration() { - return duration; - } - public void setDuration(int duration) { - this.duration = duration; - } - public long getDate() { - return date; - } - public String[] getPlayers() { - return players; - } - public String getMCVersion() { - return mcversion; - } + + private boolean singleplayer; + private String serverName; + private int duration; + private long date; + private String[] players; + private String mcversion; + + public ReplayMetaData(boolean singleplayer, String serverName, + int duration, long date, String[] players, String mcversion) { + this.singleplayer = singleplayer; + this.serverName = serverName; + this.duration = duration; + this.date = date; + this.players = players; + this.mcversion = mcversion; + } + + public boolean isSingleplayer() { + return singleplayer; + } + + public String getServerName() { + return serverName; + } + + public int getDuration() { + return duration; + } + + public void setDuration(int duration) { + this.duration = duration; + } + + public long getDate() { + return date; + } + + public String[] getPlayers() { + return players; + } + + public String getMCVersion() { + return mcversion; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/reflection/MCPEnvironment.java b/src/main/java/eu/crushedpixel/replaymod/reflection/MCPEnvironment.java deleted file mode 100755 index 2b54ec31..00000000 --- a/src/main/java/eu/crushedpixel/replaymod/reflection/MCPEnvironment.java +++ /dev/null @@ -1,24 +0,0 @@ -package eu.crushedpixel.replaymod.reflection; - -import java.lang.reflect.Field; - -import net.minecraft.client.gui.GuiMainMenu; - -public class MCPEnvironment { - - boolean eclipse = true; - - public MCPEnvironment() { - eclipse = true; - Class clazz = GuiMainMenu.class; - try { - Field viewportTexture = clazz.getDeclaredField("viewportTexture"); - } catch(Exception e) { - eclipse = false; - } - } - - public boolean isMCPEnvironment() { - return eclipse; - } -} diff --git a/src/main/java/eu/crushedpixel/replaymod/reflection/MCPNames.java b/src/main/java/eu/crushedpixel/replaymod/reflection/MCPNames.java index b0f33c90..87aea821 100755 --- a/src/main/java/eu/crushedpixel/replaymod/reflection/MCPNames.java +++ b/src/main/java/eu/crushedpixel/replaymod/reflection/MCPNames.java @@ -1,267 +1,140 @@ package eu.crushedpixel.replaymod.reflection; -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; - -import net.minecraft.client.Minecraft; -import net.minecraft.util.ResourceLocation; - -import com.google.common.base.Charsets; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; -import com.google.common.io.Files; import com.google.common.io.LineProcessor; +import net.minecraft.launchwrapper.Launch; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Iterator; +import java.util.Map; +import java.util.NoSuchElementException; /** *

A helper class for working with obfuscated field names.

*

In the development environment the mappings file will automatically loaded. You can provide the location of a custom mappings file by * providing the system property {@code sevencommons.mappingsFile}.

+ * * @author diesieben07 * @author CrushedPixel */ public final class MCPNames { - private static final Map fields; - private static final Map methods; - public static final MCPEnvironment env = new MCPEnvironment(); - - static { - if (use()) { - String mappingsDir = "./../build/unpacked/mappings/"; - - InputStream fieldsIs = MCPNames.class.getClassLoader().getResourceAsStream("fields.csv"); - InputStream methodsIs = MCPNames.class.getClassLoader().getResourceAsStream("methods.csv"); - - fields = readMappings(fieldsIs); - methods = readMappings(methodsIs); - - } else { - methods = fields = null; - } - } - - /** - *

Whether the code is running in a development environment or not.

- * @return true if the code is running in development mode (use MCP instead of SRG names) - */ - public static boolean use() { - return env.isMCPEnvironment(); - } - - /** - *

Get the correct name for the given SRG field based on the context.

- * @param srg the SRG name for a field - * @return the input if the code is running outside of development mode or the matching MCP name otherwise - */ - public static String field(String srg) { - if (use()) { - String mcp = fields.get(srg); - if (mcp == null) { - // no mapping - return srg; - } - return mcp; - } else { - return srg; - } - } - - /** - *

Get the correct name for the given SRG method based on the context.

- * @param srg the SRG name for a method - * @return the input if the code is running outside of development mode or the matching MCP name otherwise - */ - public static String method(String srg) { - if (use()) { - String mcp = methods.get(srg); - if (mcp == null) { - // no mapping - return srg; - } - return mcp; - } else { - return srg; - } - } - - private static Map readMappings(InputStream is) { - try { - InputStreamReader isr = new InputStreamReader(is); - BufferedReader br = new BufferedReader(isr); - - MCPFileParser fileParser = new MCPFileParser(); - - while(br.ready()) { - fileParser.processLine(br.readLine()); - } - - return fileParser.getResult(); - } catch (IOException e) { - throw new RuntimeException("Couldn't read SRG->MCP mappings", e); - } - } - - private static class MCPFileParser implements LineProcessor> { - - private static final Splitter splitter = Splitter.on(',').trimResults(); - private final Map map = Maps.newHashMap(); - private boolean foundFirst; - - @Override - public boolean processLine(String line) throws IOException { - if (!foundFirst) { - foundFirst = true; - return true; - } - - Iterator splitted = splitter.split(line).iterator(); - try { - String srg = splitted.next(); - String mcp = splitted.next(); - if (!map.containsKey(srg)) { - map.put(srg, mcp); - } - } catch (NoSuchElementException e) { - throw new IOException("Invalid Mappings file!", e); - } - - return true; - } - - @Override - public Map getResult() { - return ImmutableMap.copyOf(map); - } - } - - public static final String M_SPAWN_BABY = "func_75388_i"; - - public static final String F_TARGET_MATE = "field_75391_e"; - - public static final String F_THE_ANIMAL = "field_75390_d"; - - public static final String M_CLONE_PLAYER = "func_71049_a"; - - public static final String M_CONVERT_TO_VILLAGER = "func_82232_p"; - - public static final String M_SET_WORLD_AND_RESOLUTION = "func_73872_a"; - - public static final String F_BUTTON_LIST = "field_73887_h"; - - public static final String F_TAG_LIST = "field_74747_a"; - - public static final String F_TAG_MAP = "field_74784_a"; - - public static final String F_FOV_MODIFIER_HAND_PREV = "field_78506_S"; - - public static final String F_FOV_MODIFIER_HAND = "field_78507_R"; - - public static final String F_TRACKED_ENTITY_IDS = "field_72794_c"; - - public static final String F_MAP_TEXTURE_OBJECTS = "field_110585_a"; - - public static final String F_MY_ENTITY = "field_73132_a"; - - public static final String M_TRY_START_WATCHING_THIS = "func_73117_b"; - - public static final String M_ON_UPDATE = "func_70071_h_"; - - public static final String M_UPDATE_ENTITY = "func_70316_g"; - - public static final String M_DETECT_AND_SEND_CHANGES = "func_75142_b"; - - public static final String F_IS_REMOTE = "field_72995_K"; - - public static final String F_WORLD_OBJ_TILEENTITY = "field_70331_k"; - - public static final String F_WORLD_OBJ_ENTITY = "field_70170_p"; - - public static final String F_TIMER = "field_71428_T"; - - public static final String F_PACKET_CLASS_TO_ID_MAP = "field_73291_a"; - - public static final String M_SEND_PACKET_TO_PLAYER = "func_72567_b"; - - public static final String M_REMOVE_ENTITY = "func_72900_e"; - - public static final String M_WRITE_ENTITY_TO_NBT = "func_70014_b"; - - public static final String M_READ_ENTITY_FROM_NBT = "func_70037_a"; - - public static final String M_WRITE_TO_NBT_TILEENTITY = "func_70310_b"; - - public static final String M_READ_FROM_NBT_TILEENTITY = "func_70307_a"; - - public static final String F_ITEM_DAMAGE = "field_77991_e"; - - public static final String M_REGISTER_EXT_PROPS = "registerExtendedProperties"; - - public static final String M_READ_PACKET_DATA = "func_73267_a"; - - public static final String M_WRITE_PACKET_DATA = "func_73273_a"; - - public static final String M_GET_PACKET_SIZE = "func_73284_a"; - - public static final String F_UNLOCALIZED_NAME_BLOCK = "field_71968_b"; - - public static final String M_SET_HAS_SUBTYPES = "func_77627_a"; - - public static final String F_ICON_STRING = "field_111218_cA"; - - public static final String F_UNLOCALIZED_NAME_ITEM = "field_77774_bZ"; - - public static final String F_TEXTURE_NAME_BLOCK = "field_111026_f"; - - public static final String M_ACTION_PERFORMED = "func_73875_a"; - - public static final String F_Z_LEVEL = "field_73735_i"; - - public static final String M_ADD_SLOT_TO_CONTAINER = "func_75146_a"; - - public static final String M_MERGE_ITEM_STACK = "func_75135_a"; - - public static final String F_CRAFTERS = "field_75149_d"; - - public static final String M_GET_ICON_STRING = "func_111208_A"; - - public static final String M_GET_TEXTURE_NAME = "func_111023_E"; - - public static final String M_NBT_WRITE = "func_74734_a"; - - public static final String M_NBT_LOAD = "func_74735_a"; - - public static final String F_NBT_STRING_DATA = "field_74751_a"; - public static final String F_NBT_BYTE_DATA = "field_74756_a"; - public static final String F_NBT_SHORT_DATA = "field_74752_a"; - public static final String F_NBT_INT_DATA = "field_74748_a"; - public static final String F_NBT_LONG_DATA = "field_74753_a"; - public static final String F_NBT_FLOAT_DATA = "field_74750_a"; - public static final String F_NBT_DOUBLE_DATA = "field_74755_a"; - - public static final String M_SET_TAG = "func_74782_a"; - - public static final String M_NBT_GET_ID = "func_74732_a"; - - public static final String M_ITEMSTACK_WRITE_NBT = "func_77955_b"; - public static final String M_LOAD_ITEMSTACK_FROM_NBT = "func_77949_a"; - - public static final String M_ADD_CRAFTING_TO_CRAFTERS = "func_75132_a"; - - public static final String M_CHECK_HOTBAR_KEYS = "func_82319_a"; - - public static final String M_HANDLE_MOUSE_CLICK = "func_74191_a"; - - public static final String F_GUICONTAINER_THE_SLOT = "field_82320_o"; - - private MCPNames() { } + private static final Map fields; + private static final Map methods; + + static { + if(use()) { + InputStream fieldsIs = MCPNames.class.getClassLoader().getResourceAsStream("fields.csv"); + InputStream methodsIs = MCPNames.class.getClassLoader().getResourceAsStream("methods.csv"); + + fields = readMappings(fieldsIs); + methods = readMappings(methodsIs); + + } else { + methods = fields = null; + } + } + + /** + *

Whether the code is running in a development environment or not.

+ * + * @return true if the code is running in development mode (use MCP instead of SRG names) + */ + public static boolean use() { + return (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment"); + } + + /** + *

Get the correct name for the given SRG field based on the context.

+ * + * @param srg the SRG name for a field + * @return the input if the code is running outside of development mode or the matching MCP name otherwise + */ + public static String field(String srg) { + if(use()) { + String mcp = fields.get(srg); + if(mcp == null) { + // no mapping + return srg; + } + return mcp; + } else { + return srg; + } + } + + /** + *

Get the correct name for the given SRG method based on the context.

+ * + * @param srg the SRG name for a method + * @return the input if the code is running outside of development mode or the matching MCP name otherwise + */ + public static String method(String srg) { + if(use()) { + String mcp = methods.get(srg); + if(mcp == null) { + // no mapping + return srg; + } + return mcp; + } else { + return srg; + } + } + + private static Map readMappings(InputStream is) { + try { + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + + MCPFileParser fileParser = new MCPFileParser(); + + while(br.ready()) { + fileParser.processLine(br.readLine()); + } + + return fileParser.getResult(); + } catch(IOException e) { + throw new RuntimeException("Could not read SRG->MCP mappings", e); + } + } + + private static class MCPFileParser implements LineProcessor> { + + private static final Splitter splitter = Splitter.on(',').trimResults(); + private final Map map = Maps.newHashMap(); + private boolean foundFirst; + + @Override + public boolean processLine(String line) throws IOException { + if(!foundFirst) { + foundFirst = true; + return true; + } + + Iterator splitted = splitter.split(line).iterator(); + try { + String srg = splitted.next(); + String mcp = splitted.next(); + if(!map.containsKey(srg)) { + map.put(srg, mcp); + } + } catch(NoSuchElementException e) { + throw new IOException("Invalid Mappings file!", e); + } + + return true; + } + + @Override + public Map getResult() { + return ImmutableMap.copyOf(map); + } + } } \ No newline at end of file diff --git a/src/main/java/eu/crushedpixel/replaymod/registry/FileCopyHandler.java b/src/main/java/eu/crushedpixel/replaymod/registry/FileCopyHandler.java index 30a97c14..11b81d81 100644 --- a/src/main/java/eu/crushedpixel/replaymod/registry/FileCopyHandler.java +++ b/src/main/java/eu/crushedpixel/replaymod/registry/FileCopyHandler.java @@ -12,6 +12,9 @@ import java.util.concurrent.ConcurrentLinkedQueue; public class FileCopyHandler extends Thread { + private Queue> filesToMove = new ConcurrentLinkedQueue>(); + private boolean shutdown = false; + public FileCopyHandler() { Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override @@ -21,8 +24,6 @@ public class FileCopyHandler extends Thread { })); } - private Queue> filesToMove = new ConcurrentLinkedQueue>(); - public void registerModifiedFile(File tempFile, File destination) { filesToMove.add(Pair.of(tempFile, destination)); @@ -37,8 +38,6 @@ public class FileCopyHandler extends Thread { shutdown = true; } - private boolean shutdown = false; - @Override public void run() { while(!shutdown || !filesToMove.isEmpty()) { @@ -52,7 +51,8 @@ public class FileCopyHandler extends Thread { } try { Thread.sleep(1000); - } catch(Exception e) {} + } catch(Exception e) { + } } } diff --git a/src/main/java/eu/crushedpixel/replaymod/registry/KeybindRegistry.java b/src/main/java/eu/crushedpixel/replaymod/registry/KeybindRegistry.java index b6d291f4..e1fea75b 100755 --- a/src/main/java/eu/crushedpixel/replaymod/registry/KeybindRegistry.java +++ b/src/main/java/eu/crushedpixel/replaymod/registry/KeybindRegistry.java @@ -1,29 +1,27 @@ package eu.crushedpixel.replaymod.registry; +import net.minecraft.client.Minecraft; +import net.minecraft.client.settings.KeyBinding; +import org.lwjgl.input.Keyboard; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import net.minecraft.client.Minecraft; -import net.minecraft.client.settings.KeyBinding; - -import org.lwjgl.input.Keyboard; - public class KeybindRegistry { - private static Minecraft mc = Minecraft.getMinecraft(); - - public static final String KEY_LIGHTING = "Toggle Lighting"; - public static final String KEY_THUMBNAIL = "Create Thumbnail"; - public static final String KEY_SPECTATE = "Spectate Entity"; - - public static void initialize() { - List bindings = new ArrayList(Arrays.asList(mc.gameSettings.keyBindings)); - - bindings.add(new KeyBinding(KEY_LIGHTING, Keyboard.KEY_V, "Replay Mod")); - bindings.add(new KeyBinding(KEY_THUMBNAIL, Keyboard.KEY_B, "Replay Mod")); - bindings.add(new KeyBinding(KEY_SPECTATE, Keyboard.KEY_C, "Replay Mod")); - - mc.gameSettings.keyBindings = bindings.toArray(new KeyBinding[bindings.size()]); - } + public static final String KEY_LIGHTING = "Toggle Lighting"; + public static final String KEY_THUMBNAIL = "Create Thumbnail"; + public static final String KEY_SPECTATE = "Spectate Entity"; + private static Minecraft mc = Minecraft.getMinecraft(); + + public static void initialize() { + List bindings = new ArrayList(Arrays.asList(mc.gameSettings.keyBindings)); + + bindings.add(new KeyBinding(KEY_LIGHTING, Keyboard.KEY_V, "Replay Mod")); + bindings.add(new KeyBinding(KEY_THUMBNAIL, Keyboard.KEY_B, "Replay Mod")); + bindings.add(new KeyBinding(KEY_SPECTATE, Keyboard.KEY_C, "Replay Mod")); + + mc.gameSettings.keyBindings = bindings.toArray(new KeyBinding[bindings.size()]); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/registry/LightingHandler.java b/src/main/java/eu/crushedpixel/replaymod/registry/LightingHandler.java index 2653abfc..77dee4c1 100644 --- a/src/main/java/eu/crushedpixel/replaymod/registry/LightingHandler.java +++ b/src/main/java/eu/crushedpixel/replaymod/registry/LightingHandler.java @@ -1,42 +1,38 @@ package eu.crushedpixel.replaymod.registry; +import eu.crushedpixel.replaymod.ReplayMod; +import eu.crushedpixel.replaymod.timer.MCTimerHandler; import net.minecraft.client.Minecraft; import net.minecraft.client.settings.GameSettings.Options; -import net.minecraft.util.Timer; -import eu.crushedpixel.replaymod.replay.ReplayHandler; -import eu.crushedpixel.replaymod.timer.MCTimerHandler; public class LightingHandler { - private static float initialGamma = 0; - - private static boolean enabled = false; - - public static void setInitialGamma(float gamma) { - initialGamma = gamma; - } - - public static void setLighting(boolean lighting) { - if(lighting) { - if(!enabled) { - initialGamma = Minecraft.getMinecraft().gameSettings.getOptionFloatValue(Options.GAMMA); - } - Minecraft.getMinecraft().gameSettings.setOptionFloatValue(Options.GAMMA, 1000); - } - else Minecraft.getMinecraft().gameSettings.setOptionFloatValue(Options.GAMMA, initialGamma); - - enabled = lighting; - - try { - if(ReplayHandler.isPaused()) { - MCTimerHandler.advancePartialTicks(1); - MCTimerHandler.advanceRenderPartialTicks(1); - } else { - Minecraft.getMinecraft().entityRenderer.updateCameraAndRender(0); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - + private static float initialGamma = 0; + + private static boolean enabled = false; + + //TODO: Properly reset Gamma on game start + //TODO: Properly handle manual gamma changes while in Replay + public static void setLighting(boolean lighting) { + if(lighting) { + if(!enabled) { + initialGamma = Minecraft.getMinecraft().gameSettings.getOptionFloatValue(Options.GAMMA); + } + Minecraft.getMinecraft().gameSettings.setOptionFloatValue(Options.GAMMA, 1000); + } else Minecraft.getMinecraft().gameSettings.setOptionFloatValue(Options.GAMMA, initialGamma); + + enabled = lighting; + + try { + if(ReplayMod.replaySender.paused()) { + MCTimerHandler.advancePartialTicks(1); + MCTimerHandler.advanceRenderPartialTicks(1); + } else { + Minecraft.getMinecraft().entityRenderer.updateCameraAndRender(0); + } + } catch(Exception e) { + e.printStackTrace(); + } + } + } diff --git a/src/main/java/eu/crushedpixel/replaymod/registry/ReplayGuiRegistry.java b/src/main/java/eu/crushedpixel/replaymod/registry/ReplayGuiRegistry.java index 67bddbcc..301999e2 100755 --- a/src/main/java/eu/crushedpixel/replaymod/registry/ReplayGuiRegistry.java +++ b/src/main/java/eu/crushedpixel/replaymod/registry/ReplayGuiRegistry.java @@ -1,83 +1,49 @@ package eu.crushedpixel.replaymod.registry; -import java.lang.reflect.Field; - import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.EntityRenderer; -import net.minecraft.network.play.server.S0CPacketSpawnPlayer; import net.minecraftforge.client.GuiIngameForge; -import eu.crushedpixel.replaymod.reflection.MCPNames; public class ReplayGuiRegistry { - //private static Field renderHand; - private static Minecraft mc = Minecraft.getMinecraft(); - - public static boolean hidden = false; - - /* - static { - try { - //renderHand = EntityRenderer.class.getDeclaredField(MCPNames.field("field_175074_C")); - //renderHand.setAccessible(true); - } catch(Exception e) { - e.printStackTrace(); - } - } - */ - - public static void hide() { - if(hidden) return; - GuiIngameForge.renderExperiance = false; - GuiIngameForge.renderArmor = false; - GuiIngameForge.renderAir = false; - GuiIngameForge.renderHealth = false; - GuiIngameForge.renderHotbar = false; - GuiIngameForge.renderFood = false; - GuiIngameForge.renderBossHealth = false; - GuiIngameForge.renderCrosshairs = false; - GuiIngameForge.renderHelmet = false; - GuiIngameForge.renderPortal = false; - GuiIngameForge.renderHealthMount = false; - GuiIngameForge.renderJumpBar = false; - GuiIngameForge.renderObjective = false; - - /* - try { - renderHand.set(mc.entityRenderer, false); - } catch(Exception e) { - e.printStackTrace(); - } - */ - - hidden = true; - } - - public static void show() { - mc.gameSettings.hideGUI = false; - - GuiIngameForge.renderExperiance = true; - GuiIngameForge.renderArmor = true; - GuiIngameForge.renderAir = true; - GuiIngameForge.renderHealth = true; - GuiIngameForge.renderHotbar = true; - GuiIngameForge.renderFood = true; - GuiIngameForge.renderBossHealth = true; - GuiIngameForge.renderCrosshairs = true; - GuiIngameForge.renderHelmet = true; - GuiIngameForge.renderPortal = true; - GuiIngameForge.renderHealthMount = true; - GuiIngameForge.renderJumpBar = true; - GuiIngameForge.renderObjective = true; - - /* - try { - renderHand.set(mc.entityRenderer, true); - } catch(Exception e) { - e.printStackTrace(); - } - */ - - hidden = false; - } + public static boolean hidden = false; + private static Minecraft mc = Minecraft.getMinecraft(); + + public static void hide() { + if(hidden) return; + GuiIngameForge.renderExperiance = false; + GuiIngameForge.renderArmor = false; + GuiIngameForge.renderAir = false; + GuiIngameForge.renderHealth = false; + GuiIngameForge.renderHotbar = false; + GuiIngameForge.renderFood = false; + GuiIngameForge.renderBossHealth = false; + GuiIngameForge.renderCrosshairs = false; + GuiIngameForge.renderHelmet = false; + GuiIngameForge.renderPortal = false; + GuiIngameForge.renderHealthMount = false; + GuiIngameForge.renderJumpBar = false; + GuiIngameForge.renderObjective = false; + + hidden = true; + } + + public static void show() { + mc.gameSettings.hideGUI = false; + + GuiIngameForge.renderExperiance = true; + GuiIngameForge.renderArmor = true; + GuiIngameForge.renderAir = true; + GuiIngameForge.renderHealth = true; + GuiIngameForge.renderHotbar = true; + GuiIngameForge.renderFood = true; + GuiIngameForge.renderBossHealth = true; + GuiIngameForge.renderCrosshairs = true; + GuiIngameForge.renderHelmet = true; + GuiIngameForge.renderPortal = true; + GuiIngameForge.renderHealthMount = true; + GuiIngameForge.renderJumpBar = true; + GuiIngameForge.renderObjective = true; + + hidden = false; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/renderer/SafeEntityRenderer.java b/src/main/java/eu/crushedpixel/replaymod/renderer/SafeEntityRenderer.java index 812f7f0e..427f0101 100755 --- a/src/main/java/eu/crushedpixel/replaymod/renderer/SafeEntityRenderer.java +++ b/src/main/java/eu/crushedpixel/replaymod/renderer/SafeEntityRenderer.java @@ -1,41 +1,44 @@ package eu.crushedpixel.replaymod.renderer; -import java.lang.reflect.Field; - import eu.crushedpixel.replaymod.reflection.MCPNames; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.client.resources.IResourceManager; +import java.lang.reflect.Field; + public class SafeEntityRenderer extends EntityRenderer { - private static Field resourceManager; - static { - try { - resourceManager = EntityRenderer.class.getDeclaredField(MCPNames.field("field_147711_ac")); - resourceManager.setAccessible(true); - } catch(Exception e) { - e.printStackTrace(); - } - } + private static Field resourceManager; - public SafeEntityRenderer(Minecraft mcIn, EntityRenderer renderer) throws IllegalArgumentException, IllegalAccessException { - super(mcIn, (IResourceManager)resourceManager.get(renderer)); - } + static { + try { + resourceManager = EntityRenderer.class.getDeclaredField(MCPNames.field("field_147711_ac")); + resourceManager.setAccessible(true); + } catch(Exception e) { + e.printStackTrace(); + } + } - @Override - public void updateCameraAndRender(float partialTicks) { - try { - super.updateCameraAndRender(partialTicks); - } catch(Exception e) {} //This is plain easier than doing proper error prevention. - //If Johni reads this, don't think I'm a bad programmer... Just a lazy one :P - } - - @Override - public void updateRenderer() { - try { - super.updateRenderer(); - } catch(Exception e) {} - } + public SafeEntityRenderer(Minecraft mcIn, EntityRenderer renderer) throws IllegalArgumentException, IllegalAccessException { + super(mcIn, (IResourceManager) resourceManager.get(renderer)); + } + + @Override + public void updateCameraAndRender(float partialTicks) { + try { + super.updateCameraAndRender(partialTicks); + } catch(Exception e) { + } //This is plain easier than doing proper error prevention. + //If Johni reads this, don't think I'm a bad programmer... Just a lazy one :P + } + + @Override + public void updateRenderer() { + try { + super.updateRenderer(); + } catch(Exception e) { + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/replay/LesserDataWatcher.java b/src/main/java/eu/crushedpixel/replaymod/replay/LesserDataWatcher.java index 714c4928..42d40bd6 100755 --- a/src/main/java/eu/crushedpixel/replaymod/replay/LesserDataWatcher.java +++ b/src/main/java/eu/crushedpixel/replaymod/replay/LesserDataWatcher.java @@ -1,105 +1,105 @@ package eu.crushedpixel.replaymod.replay; -import java.io.IOException; -import java.util.List; - -import scala.actors.threadpool.Arrays; import net.minecraft.entity.DataWatcher; import net.minecraft.entity.Entity; import net.minecraft.item.ItemStack; import net.minecraft.network.PacketBuffer; import net.minecraft.util.Rotations; +import java.io.IOException; +import java.util.List; + +/** + * A Data Watcher which is applied to the Camera Entity to avoid both NPEs and the Screen constantly jittering (because of the entity being dead) + */ public class LesserDataWatcher extends DataWatcher { - public LesserDataWatcher(Entity owner) { - super(owner); - } + public LesserDataWatcher(Entity owner) { + super(owner); + } - @Override - public void addObject(int id, Object object) { - } + @Override + public void addObject(int id, Object object) { + } - @Override - public void addObjectByDataType(int id, int type) { - } + @Override + public void addObjectByDataType(int id, int type) { + } - @Override - public byte getWatchableObjectByte(int id) { - return 10; - } + @Override + public byte getWatchableObjectByte(int id) { + return 10; + } - @Override - public short getWatchableObjectShort(int id) { - return 10; - } + @Override + public short getWatchableObjectShort(int id) { + return 10; + } - @Override - public int getWatchableObjectInt(int id) { - return 10; - } + @Override + public int getWatchableObjectInt(int id) { + return 10; + } - @Override - public float getWatchableObjectFloat(int id) { - return 10f; - } + @Override + public float getWatchableObjectFloat(int id) { + return 10f; + } - @Override - public String getWatchableObjectString(int id) { - return null; - } + @Override + public String getWatchableObjectString(int id) { + return null; + } - @Override - public ItemStack getWatchableObjectItemStack(int id) { - return null; - } + @Override + public ItemStack getWatchableObjectItemStack(int id) { + return null; + } - @Override - public Rotations getWatchableObjectRotations(int id) { - return null; - } + @Override + public Rotations getWatchableObjectRotations(int id) { + return null; + } - @Override - public void updateObject(int id, Object newData) { - } + @Override + public void updateObject(int id, Object newData) { + } - @Override - public void setObjectWatched(int id) { - } + @Override + public void setObjectWatched(int id) { + } - @Override - public boolean hasObjectChanged() { - return false; - } + @Override + public boolean hasObjectChanged() { + return false; + } - @Override - public List getChanged() { - return null; - } + @Override + public List getChanged() { + return null; + } - @Override - public void writeTo(PacketBuffer buffer) throws IOException { - } + @Override + public void writeTo(PacketBuffer buffer) throws IOException { + } - @Override - public List getAllWatched() { - return null; - } + @Override + public List getAllWatched() { + return null; + } - @Override - public void updateWatchedObjectsFromList(List p_75687_1_) { - } + @Override + public void updateWatchedObjectsFromList(List p_75687_1_) { + } - @Override - public boolean getIsBlank() { - return true; - } + @Override + public boolean getIsBlank() { + return true; + } + + @Override + public void func_111144_e() { + } - @Override - public void func_111144_e() { - } - - - } diff --git a/src/main/java/eu/crushedpixel/replaymod/replay/OpenEmbeddedChannel.java b/src/main/java/eu/crushedpixel/replaymod/replay/OpenEmbeddedChannel.java index 360568c3..5329e57c 100755 --- a/src/main/java/eu/crushedpixel/replaymod/replay/OpenEmbeddedChannel.java +++ b/src/main/java/eu/crushedpixel/replaymod/replay/OpenEmbeddedChannel.java @@ -1,34 +1,34 @@ package eu.crushedpixel.replaymod.replay; -import net.minecraft.network.NetworkManager; import io.netty.channel.ChannelFuture; import io.netty.channel.embedded.EmbeddedChannel; +import net.minecraft.network.NetworkManager; public class OpenEmbeddedChannel extends EmbeddedChannel { - private boolean ignoreClose = false; - - public OpenEmbeddedChannel(NetworkManager networkManager) { - super(networkManager); - } - - @Override - public boolean finish() { - System.out.println("wanted to finish"); - ignoreClose = true; + private boolean ignoreClose = false; + + public OpenEmbeddedChannel(NetworkManager networkManager) { + super(networkManager); + } + + @Override + public boolean finish() { + System.out.println("wanted to finish"); + ignoreClose = true; return super.finish(); } - @Override + @Override public ChannelFuture close() { - if(ignoreClose) { - ignoreClose = false; - return null; - } + if(ignoreClose) { + ignoreClose = false; + return null; + } + return pipeline().close(); + } + + public ChannelFuture manualClose() { return pipeline().close(); } - - public ChannelFuture manualClose() { - return pipeline().close(); - } } diff --git a/src/main/java/eu/crushedpixel/replaymod/replay/PacketDeserializer.java b/src/main/java/eu/crushedpixel/replaymod/replay/PacketDeserializer.java deleted file mode 100755 index 6ce3a3ef..00000000 --- a/src/main/java/eu/crushedpixel/replaymod/replay/PacketDeserializer.java +++ /dev/null @@ -1,110 +0,0 @@ -package eu.crushedpixel.replaymod.replay; - -import gnu.trove.iterator.TIntObjectIterator; -import gnu.trove.map.TIntObjectMap; -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; - -import java.io.IOException; -import java.lang.reflect.Field; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import net.minecraft.network.EnumConnectionState; -import net.minecraft.network.EnumPacketDirection; -import net.minecraft.network.NetworkManager; -import net.minecraft.network.Packet; -import net.minecraft.network.PacketBuffer; -import net.minecraft.util.MessageDeserializer; - -import com.google.common.collect.BiMap; - -import eu.crushedpixel.replaymod.reflection.MCPNames; - -public class PacketDeserializer extends MessageDeserializer { - - private final EnumPacketDirection direction; - private Field directionMaps; - private EnumConnectionState state; - - public PacketDeserializer(EnumPacketDirection direction) { - super(direction); - this.direction = direction; - try { - directionMaps = EnumConnectionState.class.getDeclaredField(MCPNames.field("field_179247_h")); - directionMaps.setAccessible(true); - } catch (NoSuchFieldException e) { - e.printStackTrace(); - } catch (SecurityException e) { - e.printStackTrace(); - } - } - - public Packet getPacket(EnumPacketDirection direction, int packetId) throws InstantiationException, IllegalAccessException - { - Map map = ((Map)directionMaps.get(state)); - BiMap biMap = ((BiMap)map.get(direction)); - if(biMap == null) { - System.out.println("BiMap is null!"); - } - Class oclass = (Class)biMap.get(Integer.valueOf(packetId)); - return oclass == null ? null : (Packet)oclass.newInstance(); - } - - public void setEnumConnectionState(EnumConnectionState state) { - this.state = state; - } - - @Override - public void decode(ChannelHandlerContext p_decode_1_, - ByteBuf p_decode_2_, List p_decode_3_) throws IOException, - InstantiationException, IllegalAccessException { - - if (p_decode_2_.readableBytes() != 0) - { - PacketBuffer packetbuffer = new PacketBuffer(p_decode_2_); - int i = packetbuffer.readVarIntFromBuffer(); - - Field state_by_id = null; - try { - state_by_id = EnumConnectionState.class.getDeclaredField(MCPNames.field("field_150764_e")); - state_by_id.setAccessible(true); - state = (EnumConnectionState)((TIntObjectMap)state_by_id.get(null)).get(i); - TIntObjectMap map = (TIntObjectMap)state_by_id.get(null); - TIntObjectIterator it = map.iterator(); - while(it.hasNext()) { - it.advance(); - System.out.println(it.key() +" | "+it.value().getClass()); - } - } catch(Exception e) { - e.printStackTrace(); - } - - if(state == null) { - System.out.println("state is null"); - } - //Packet packet = getPacket(this.direction, i); - Packet packet = state.getPacket(EnumPacketDirection.CLIENTBOUND, i); - - if (packet == null) - { - throw new IOException("Bad packet id " + i); - } - else - { - packet.readPacketData(packetbuffer); - - if (packetbuffer.readableBytes() > 0) - { - throw new IOException("Packet " + ((EnumConnectionState)p_decode_1_.channel().attr(NetworkManager.attrKeyConnectionState).get()).getId() + "/" + i + " (" + packet.getClass().getSimpleName() + ") was larger than I expected, found " + packetbuffer.readableBytes() + " bytes extra whilst reading packet " + i); - } - else - { - p_decode_3_.add(packet); - } - } - } - } - -} diff --git a/src/main/java/eu/crushedpixel/replaymod/replay/PacketInfo.java b/src/main/java/eu/crushedpixel/replaymod/replay/PacketInfo.java deleted file mode 100755 index 53bf51b0..00000000 --- a/src/main/java/eu/crushedpixel/replaymod/replay/PacketInfo.java +++ /dev/null @@ -1,38 +0,0 @@ -package eu.crushedpixel.replaymod.replay; - -import net.minecraft.network.EnumConnectionState; - -public class PacketInfo { - - private byte[] bytes; - private EnumConnectionState connectionState; - private int packetID; - - public PacketInfo(byte[] bytes, EnumConnectionState connectionState, - int packetID) { - super(); - this.bytes = bytes; - this.connectionState = connectionState; - this.packetID = packetID; - } - public byte[] getBytes() { - return bytes; - } - public void setBytes(byte[] bytes) { - this.bytes = bytes; - } - public EnumConnectionState getConnectionState() { - return connectionState; - } - public void setConnectionState(EnumConnectionState connectionState) { - this.connectionState = connectionState; - } - public int getPacketID() { - return packetID; - } - public void setPacketID(int packetID) { - this.packetID = packetID; - } - - -} diff --git a/src/main/java/eu/crushedpixel/replaymod/replay/ReplayHandler.java b/src/main/java/eu/crushedpixel/replaymod/replay/ReplayHandler.java index f7f4d4b7..59165db2 100755 --- a/src/main/java/eu/crushedpixel/replaymod/replay/ReplayHandler.java +++ b/src/main/java/eu/crushedpixel/replaymod/replay/ReplayHandler.java @@ -1,7 +1,17 @@ package eu.crushedpixel.replaymod.replay; -import io.netty.channel.ChannelPipeline; +import com.mojang.authlib.GameProfile; +import eu.crushedpixel.replaymod.ReplayMod; +import eu.crushedpixel.replaymod.entities.CameraEntity; +import eu.crushedpixel.replaymod.holders.*; import io.netty.channel.embedded.EmbeddedChannel; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.network.NetHandlerPlayClient; +import net.minecraft.entity.Entity; +import net.minecraft.network.EnumPacketDirection; +import net.minecraft.network.NetworkManager; +import net.minecraft.network.play.INetHandlerPlayClient; import java.io.File; import java.util.ArrayList; @@ -9,436 +19,327 @@ import java.util.Collections; import java.util.List; import java.util.UUID; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.network.NetHandlerPlayClient; -import net.minecraft.entity.Entity; -import net.minecraft.network.EnumPacketDirection; -import net.minecraft.network.NetworkManager; -import net.minecraft.network.Packet; -import net.minecraft.network.play.INetHandlerPlayClient; - -import com.mojang.authlib.GameProfile; - -import eu.crushedpixel.replaymod.ReplayMod; -import eu.crushedpixel.replaymod.chat.ChatMessageRequests; -import eu.crushedpixel.replaymod.entities.CameraEntity; -import eu.crushedpixel.replaymod.holders.Keyframe; -import eu.crushedpixel.replaymod.holders.KeyframeComparator; -import eu.crushedpixel.replaymod.holders.Position; -import eu.crushedpixel.replaymod.holders.PositionKeyframe; -import eu.crushedpixel.replaymod.holders.TimeKeyframe; - public class ReplayHandler { - private static NetworkManager networkManager; - private static Minecraft mc = Minecraft.getMinecraft(); - private static ReplaySender replaySender; - private static OpenEmbeddedChannel channel; - - private static int realTimelinePosition = 0; - - private static Keyframe selectedKeyframe; - - private static boolean inPath = false; - - private static CameraEntity cameraEntity; - - private static List keyframes = new ArrayList(); - - private static boolean inReplay = false; - - public static long lastExit = 0; - - private static Entity currentEntity = null; - - public static void insertPacketInstantly(Packet p) { - if(replaySender != null) { - try { - replaySender.channelRead(null, p); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - public static void spectateEntity(Entity e) { - currentEntity = e; - mc.setRenderViewEntity(currentEntity); - } - - public static Entity getSpectatedEntity() { - return currentEntity; - } - - public static void spectateCamera() { - if(currentEntity != null) { - Position prev = new Position(currentEntity); - cameraEntity.movePath(prev); - } - currentEntity = cameraEntity; - mc.setRenderViewEntity(cameraEntity); - } - - public static boolean isCamera() { - return currentEntity == cameraEntity; - } - - public static void setInPath(boolean replaying) { - inPath = replaying; - } - - public static void resetToleratedTimestamp() { - if(replaySender != null) replaySender.resetToleratedTimeStamp(); - } - - public static void stopHurrying() { - if(replaySender != null) replaySender.stopHurrying(); - } - - public static void startPath(boolean save) { - if(!ReplayHandler.isInPath()) ReplayProcess.startReplayProcess(save); - } - - public static void interruptReplay() { - ReplayProcess.stopReplayProcess(false); - } - - public static boolean isInPath() { - return inPath; - } - - public static void setCameraEntity(CameraEntity entity) { - if(entity == null) return; - cameraEntity = entity; - spectateCamera(); - } - - public static CameraEntity getCameraEntity() { - return cameraEntity; - } - - public static int getDesiredTimestamp() { - return replaySender == null ? 0 : (int)replaySender.getDesiredTimestamp(); - } - - public static int getReplayTime() { - return replaySender == null ? 0 : (int)replaySender.currentTimeStamp(); - } - - public static void sortKeyframes() { - Collections.sort(keyframes, new KeyframeComparator()); - } - - public static void addKeyframe(Keyframe keyframe) { - keyframes.add(keyframe); - selectKeyframe(keyframe); - } - - public static void removeKeyframe(Keyframe keyframe) { - keyframes.remove(keyframe); - if(keyframe == selectedKeyframe) { - selectKeyframe(null); - } else { - sortKeyframes(); - } - } - - public static int getKeyframeIndex(TimeKeyframe timeKeyframe) { - int index = 0; - for(Keyframe kf : keyframes) { - if(kf == timeKeyframe) return index; - else if(kf instanceof TimeKeyframe) index++; - } - return -1; - } - - public static int getKeyframeIndex(PositionKeyframe posKeyframe) { - int index = 0; - for(Keyframe kf : keyframes) { - if(kf == posKeyframe) return index; - else if(kf instanceof PositionKeyframe) index++; - } - return -1; - } - - public static int getPosKeyframeCount() { - int size = 0; - for(Keyframe kf : keyframes) { - if(kf instanceof PositionKeyframe) size++; - } - return size; - } - - public static int getTimeKeyframeCount() { - int size = 0; - for(Keyframe kf : keyframes) { - if(kf instanceof TimeKeyframe) size++; - } - return size; - } - - public static TimeKeyframe getClosestTimeKeyframeForRealTime(int realTime, int tolerance) { - List found = new ArrayList(); - for(Keyframe kf : keyframes) { - if(!(kf instanceof TimeKeyframe)) continue; - if(Math.abs(kf.getRealTimestamp()-realTime) <= tolerance) { - found.add((TimeKeyframe)kf); - } - } - - TimeKeyframe closest = null; - - for(TimeKeyframe kf : found) { - if(closest == null || Math.abs(closest.getTimestamp()-realTime) > Math.abs(kf.getRealTimestamp()-realTime)) { - closest = kf; - } - } - return closest; - } - - public static PositionKeyframe getClosestPlaceKeyframeForRealTime(int realTime, int tolerance) { - List found = new ArrayList(); - for(Keyframe kf : keyframes) { - if(!(kf instanceof PositionKeyframe)) continue; - if(Math.abs(kf.getRealTimestamp()-realTime) <= tolerance) { - found.add((PositionKeyframe)kf); - } - } - - PositionKeyframe closest = null; - - for(PositionKeyframe kf : found) { - if(closest == null || Math.abs(closest.getRealTimestamp()-realTime) > Math.abs(kf.getRealTimestamp()-realTime)) { - closest = kf; - } - } - return closest; - } - - public static PositionKeyframe getPreviousPositionKeyframe(int realTime) { - if(keyframes.isEmpty()) return null; - List found = new ArrayList(); - for(Keyframe kf : keyframes) { - if(!(kf instanceof PositionKeyframe)) continue; - if(kf.getRealTimestamp() < realTime) { - found.add((PositionKeyframe)kf); - } - } - - if(found.size() > 0) - return found.get(found.size()-1); //last element is nearest - else return null; - } - - public static PositionKeyframe getNextPositionKeyframe(int realTime) { - if(keyframes.isEmpty()) return null; - for(Keyframe kf : keyframes) { - if(!(kf instanceof PositionKeyframe)) continue; - if(kf.getRealTimestamp() >= realTime) { - return (PositionKeyframe)kf; //first found element is next - } - } - return null; - } - - public static TimeKeyframe getPreviousTimeKeyframe(int realTime) { - if(keyframes.isEmpty()) return null; - List found = new ArrayList(); - for(Keyframe kf : keyframes) { - if(!(kf instanceof TimeKeyframe)) continue; - if(kf.getRealTimestamp() < realTime) { - found.add((TimeKeyframe)kf); - } - } - - if(found.size() > 0) - return found.get(found.size()-1); //last element is nearest - else return null; - } - - public static TimeKeyframe getNextTimeKeyframe(int realTime) { - if(keyframes.isEmpty()) return null; - for(Keyframe kf : keyframes) { - if(!(kf instanceof TimeKeyframe)) continue; - if(kf.getRealTimestamp() >= realTime) { - return (TimeKeyframe)kf; //first found element is next - } - } - return null; - } - - public static List getKeyframes() { - return new ArrayList(keyframes); - } - - public static void resetKeyframes() { - keyframes = new ArrayList(); - - selectKeyframe(null); - } - - public static void setReplayTime(int pos) { - if(replaySender != null) { - replaySender.jumpToTime(pos); - } - } - - public static boolean isHurrying() { - if(replaySender != null) { - return replaySender.isHurrying(); - } - return false; - } - - public static int getReplayLength() { - if(replaySender != null) { - return replaySender.replayLength(); - } - - return 1; - } - - public static boolean isSelected(Keyframe kf) { - return kf == selectedKeyframe; - } - - public static void selectKeyframe(Keyframe kf) { - selectedKeyframe = kf; - sortKeyframes(); - } - - public static boolean isInReplay() { - return inReplay; - } - - public static boolean isPaused() { - if(replaySender != null) { - return replaySender.paused(); - } - return true; - } - - public static void setSpeed(double d) { - if(replaySender != null) { - replaySender.setReplaySpeed(d); - } - } - - public static double getSpeed() { - if(replaySender != null) { - return replaySender.getReplaySpeed(); - } - return 0; - } - - public static void startReplay(File file) throws NoSuchMethodException, SecurityException, NoSuchFieldException { - - ChatMessageRequests.initialize(); - mc.ingameGUI.getChatGUI().clearChatMessages(); - resetKeyframes(); - - if(replaySender != null) { - replaySender.terminateReplay(); - } - - if(channel != null) { - channel.close(); - } - - networkManager = new NetworkManager(EnumPacketDirection.CLIENTBOUND); - INetHandlerPlayClient pc = new NetHandlerPlayClient(mc, (GuiScreen)null, networkManager, new GameProfile(UUID.randomUUID(), "Player")); - networkManager.setNetHandler(pc); - - channel = new OpenEmbeddedChannel(networkManager); - - replaySender = new ReplaySender(file, networkManager); - channel.pipeline().addFirst(replaySender); - channel.pipeline().fireChannelActive(); - - try { - ReplayMod.overlay.resetUI(); - } catch(Exception e) {} - - //Load lighting and trigger update - ReplayMod.replaySettings.setLightingEnabled(ReplayMod.replaySettings.isLightingEnabled()); - - inReplay = true; - } - - public static void restartReplay() { - //mc.setRenderViewEntity(mc.thePlayer); - mc.ingameGUI.getChatGUI().clearChatMessages(); - - if(channel != null) { - channel.close(); - } - - networkManager = new NetworkManager(EnumPacketDirection.CLIENTBOUND); - INetHandlerPlayClient pc = new NetHandlerPlayClient(mc, (GuiScreen)null, networkManager, new GameProfile(UUID.randomUUID(), "Player")); - networkManager.setNetHandler(pc); - - EmbeddedChannel channel = new OpenEmbeddedChannel(networkManager); - - channel.pipeline().addFirst(replaySender); - channel.pipeline().fireChannelActive(); - - ChannelPipeline pipeline = networkManager.channel().pipeline(); - - mc.addScheduledTask(new Runnable() { - @Override - public void run() { - try { - ReplayMod.overlay.resetUI(); - } catch(Exception e) { - e.printStackTrace(); - } - } - }); - - inReplay = true; - } - - public static void endReplay() { - if(replaySender != null) { - replaySender.terminateReplay(); - } - - resetKeyframes(); - - /* - if(channel != null && channel.isOpen()) { - channel.close(); - } - */ - - inReplay = false; - } - - public static Keyframe getSelected() { - return selectedKeyframe; - } - - public static int getRealTimelineCursor() { - return realTimelinePosition; - } - - public static void setRealTimelineCursor(int pos) { - realTimelinePosition = pos; - } - - private static Position lastPosition = null; - public static void setLastPosition(Position position) { - lastPosition = position; - } + public static long lastExit = 0; + private static NetworkManager networkManager; + private static Minecraft mc = Minecraft.getMinecraft(); + //private static ReplaySender replaySender; + private static OpenEmbeddedChannel channel; + private static int realTimelinePosition = 0; + private static Keyframe selectedKeyframe; + private static boolean inPath = false; + private static CameraEntity cameraEntity; + private static List keyframes = new ArrayList(); + private static boolean inReplay = false; + private static Entity currentEntity = null; + private static Position lastPosition = null; + + public static void spectateEntity(Entity e) { + currentEntity = e; + mc.setRenderViewEntity(currentEntity); + } + + public static void spectateCamera() { + if(currentEntity != null) { + Position prev = new Position(currentEntity); + cameraEntity.movePath(prev); + } + currentEntity = cameraEntity; + mc.setRenderViewEntity(cameraEntity); + } + + public static boolean isCamera() { + return currentEntity == cameraEntity; + } + + public static void startPath(boolean save) { + if(!ReplayHandler.isInPath()) ReplayProcess.startReplayProcess(save); + } + + public static void interruptReplay() { + ReplayProcess.stopReplayProcess(false); + } + + public static boolean isInPath() { + return inPath; + } + + public static void setInPath(boolean replaying) { + inPath = replaying; + } + + public static CameraEntity getCameraEntity() { + return cameraEntity; + } + + public static void setCameraEntity(CameraEntity entity) { + if(entity == null) return; + cameraEntity = entity; + spectateCamera(); + } + + public static void sortKeyframes() { + Collections.sort(keyframes, new KeyframeComparator()); + } + + public static void addKeyframe(Keyframe keyframe) { + keyframes.add(keyframe); + selectKeyframe(keyframe); + } + + public static void removeKeyframe(Keyframe keyframe) { + keyframes.remove(keyframe); + if(keyframe == selectedKeyframe) { + selectKeyframe(null); + } else { + sortKeyframes(); + } + } + + public static int getKeyframeIndex(TimeKeyframe timeKeyframe) { + int index = 0; + for(Keyframe kf : keyframes) { + if(kf == timeKeyframe) return index; + else if(kf instanceof TimeKeyframe) index++; + } + return -1; + } + + public static int getKeyframeIndex(PositionKeyframe posKeyframe) { + int index = 0; + for(Keyframe kf : keyframes) { + if(kf == posKeyframe) return index; + else if(kf instanceof PositionKeyframe) index++; + } + return -1; + } + + public static int getPosKeyframeCount() { + int size = 0; + for(Keyframe kf : keyframes) { + if(kf instanceof PositionKeyframe) size++; + } + return size; + } + + public static int getTimeKeyframeCount() { + int size = 0; + for(Keyframe kf : keyframes) { + if(kf instanceof TimeKeyframe) size++; + } + return size; + } + + public static TimeKeyframe getClosestTimeKeyframeForRealTime(int realTime, int tolerance) { + List found = new ArrayList(); + for(Keyframe kf : keyframes) { + if(!(kf instanceof TimeKeyframe)) continue; + if(Math.abs(kf.getRealTimestamp() - realTime) <= tolerance) { + found.add((TimeKeyframe) kf); + } + } + + TimeKeyframe closest = null; + + for(TimeKeyframe kf : found) { + if(closest == null || Math.abs(closest.getTimestamp() - realTime) > Math.abs(kf.getRealTimestamp() - realTime)) { + closest = kf; + } + } + return closest; + } + + public static PositionKeyframe getClosestPlaceKeyframeForRealTime(int realTime, int tolerance) { + List found = new ArrayList(); + for(Keyframe kf : keyframes) { + if(!(kf instanceof PositionKeyframe)) continue; + if(Math.abs(kf.getRealTimestamp() - realTime) <= tolerance) { + found.add((PositionKeyframe) kf); + } + } + + PositionKeyframe closest = null; + + for(PositionKeyframe kf : found) { + if(closest == null || Math.abs(closest.getRealTimestamp() - realTime) > Math.abs(kf.getRealTimestamp() - realTime)) { + closest = kf; + } + } + return closest; + } + + public static PositionKeyframe getPreviousPositionKeyframe(int realTime) { + if(keyframes.isEmpty()) return null; + List found = new ArrayList(); + for(Keyframe kf : keyframes) { + if(!(kf instanceof PositionKeyframe)) continue; + if(kf.getRealTimestamp() < realTime) { + found.add((PositionKeyframe) kf); + } + } + + if(found.size() > 0) + return found.get(found.size() - 1); //last element is nearest + else return null; + } + + public static PositionKeyframe getNextPositionKeyframe(int realTime) { + if(keyframes.isEmpty()) return null; + for(Keyframe kf : keyframes) { + if(!(kf instanceof PositionKeyframe)) continue; + if(kf.getRealTimestamp() >= realTime) { + return (PositionKeyframe) kf; //first found element is next + } + } + return null; + } + + public static TimeKeyframe getPreviousTimeKeyframe(int realTime) { + if(keyframes.isEmpty()) return null; + List found = new ArrayList(); + for(Keyframe kf : keyframes) { + if(!(kf instanceof TimeKeyframe)) continue; + if(kf.getRealTimestamp() < realTime) { + found.add((TimeKeyframe) kf); + } + } + + if(found.size() > 0) + return found.get(found.size() - 1); //last element is nearest + else return null; + } + + public static TimeKeyframe getNextTimeKeyframe(int realTime) { + if(keyframes.isEmpty()) return null; + for(Keyframe kf : keyframes) { + if(!(kf instanceof TimeKeyframe)) continue; + if(kf.getRealTimestamp() >= realTime) { + return (TimeKeyframe) kf; //first found element is next + } + } + return null; + } + + public static List getKeyframes() { + return new ArrayList(keyframes); + } + + public static void resetKeyframes() { + keyframes = new ArrayList(); + + selectKeyframe(null); + } + + public static boolean isSelected(Keyframe kf) { + return kf == selectedKeyframe; + } + + public static void selectKeyframe(Keyframe kf) { + selectedKeyframe = kf; + sortKeyframes(); + } + + public static boolean isInReplay() { + return inReplay; + } + + public static void startReplay(File file) throws NoSuchMethodException, SecurityException, NoSuchFieldException { + + ReplayMod.chatMessageHandler.initialize(); + mc.ingameGUI.getChatGUI().clearChatMessages(); + resetKeyframes(); + + ReplayMod.replaySender.terminateReplay(); + + if(channel != null) { + channel.close(); + } + + networkManager = new NetworkManager(EnumPacketDirection.CLIENTBOUND); + INetHandlerPlayClient pc = new NetHandlerPlayClient(mc, (GuiScreen) null, networkManager, new GameProfile(UUID.randomUUID(), "Player")); + networkManager.setNetHandler(pc); + + channel = new OpenEmbeddedChannel(networkManager); + + ReplayMod.replaySender = new ReplaySender(file, networkManager); + channel.pipeline().addFirst(ReplayMod.replaySender); + channel.pipeline().fireChannelActive(); + + try { + ReplayMod.overlay.resetUI(); + } catch(Exception e) {} + + //Load lighting and trigger update + ReplayMod.replaySettings.setLightingEnabled(ReplayMod.replaySettings.isLightingEnabled()); + + inReplay = true; + } + + public static void restartReplay() { + mc.ingameGUI.getChatGUI().clearChatMessages(); + + if(channel != null) { + channel.close(); + } + + networkManager = new NetworkManager(EnumPacketDirection.CLIENTBOUND); + INetHandlerPlayClient pc = new NetHandlerPlayClient(mc, (GuiScreen) null, networkManager, new GameProfile(UUID.randomUUID(), "Player")); + networkManager.setNetHandler(pc); + + EmbeddedChannel channel = new OpenEmbeddedChannel(networkManager); + + channel.pipeline().addFirst(ReplayMod.replaySender); + channel.pipeline().fireChannelActive(); + + mc.addScheduledTask(new Runnable() { + @Override + public void run() { + try { + ReplayMod.overlay.resetUI(); + } catch(Exception e) { + e.printStackTrace(); + } + } + }); + + inReplay = true; + } + + public static void endReplay() { + if(ReplayMod.replaySender != null) { + ReplayMod.replaySender.terminateReplay(); + } + + resetKeyframes(); - public static Position getLastPosition() { - return lastPosition; - } - - public static File getReplayFile() { - if(replaySender != null) { - return replaySender.getReplayFile(); - } - return null; - } + inReplay = false; + } + + public static Keyframe getSelected() { + return selectedKeyframe; + } + + public static int getRealTimelineCursor() { + return realTimelinePosition; + } + + public static void setRealTimelineCursor(int pos) { + realTimelinePosition = pos; + } + + public static Position getLastPosition() { + return lastPosition; + } + + public static void setLastPosition(Position position) { + lastPosition = position; + } + + public static File getReplayFile() { + if(ReplayMod.replaySender != null) { + return ReplayMod.replaySender.getReplayFile(); + } + return null; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/replay/ReplayProcess.java b/src/main/java/eu/crushedpixel/replaymod/replay/ReplayProcess.java index 433ea92b..e2a44052 100755 --- a/src/main/java/eu/crushedpixel/replaymod/replay/ReplayProcess.java +++ b/src/main/java/eu/crushedpixel/replaymod/replay/ReplayProcess.java @@ -1,18 +1,7 @@ package eu.crushedpixel.replaymod.replay; -import java.awt.image.BufferedImage; -import java.lang.reflect.Field; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiDownloadTerrain; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.renderer.ChunkRenderContainer; -import net.minecraft.client.renderer.RenderGlobal; -import net.minecraft.client.renderer.chunk.RenderChunk; -import net.minecraft.client.renderer.entity.RenderEntity; import eu.crushedpixel.replaymod.ReplayMod; -import eu.crushedpixel.replaymod.chat.ChatMessageRequests; -import eu.crushedpixel.replaymod.chat.ChatMessageRequests.ChatMessageType; +import eu.crushedpixel.replaymod.chat.ChatMessageHandler.ChatMessageType; import eu.crushedpixel.replaymod.gui.GuiCancelRender; import eu.crushedpixel.replaymod.holders.Keyframe; import eu.crushedpixel.replaymod.holders.Position; @@ -21,371 +10,370 @@ import eu.crushedpixel.replaymod.holders.TimeKeyframe; import eu.crushedpixel.replaymod.interpolation.LinearPoint; import eu.crushedpixel.replaymod.interpolation.LinearTimestamp; import eu.crushedpixel.replaymod.interpolation.SplinePoint; -import eu.crushedpixel.replaymod.reflection.MCPNames; import eu.crushedpixel.replaymod.timer.EnchantmentTimer; import eu.crushedpixel.replaymod.timer.MCTimerHandler; import eu.crushedpixel.replaymod.video.ScreenCapture; import eu.crushedpixel.replaymod.video.VideoWriter; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.chunk.RenderChunk; + +import java.awt.image.BufferedImage; public class ReplayProcess { - private static Minecraft mc = Minecraft.getMinecraft(); - - private static long startRealTime; - private static int lastRealReplayTime; - private static long lastRealTime = 0; - - private static boolean linear = false; - - private static Position lastPosition = null; - private static int lastTimestamp = -1; - - private static SplinePoint motionSpline = null; - private static LinearPoint motionLinear = null; - private static LinearTimestamp timeLinear = null; - - private static double lastSpeed = 1f; - - private static double previousReplaySpeed = 0; - - private static boolean calculated = false; - - private static boolean isVideoRecording = false; - - public static boolean isVideoRecording() { - return isVideoRecording; - } - - public static void startReplayProcess(boolean record) { - ReplayHandler.selectKeyframe(null); - - firstTime = true; - - isVideoRecording = record; - lastPosition = null; - motionSpline = null; - motionLinear = null; - timeLinear = null; - calculated = false; - requestFinish = false; - - ReplayHandler.resetToleratedTimestamp(); - - ChatMessageRequests.initialize(); - if(ReplayHandler.getPosKeyframeCount() < 2 && ReplayHandler.getTimeKeyframeCount() < 2) { - ChatMessageRequests.addChatMessage("At least 2 position or time keyframes required!", ChatMessageType.WARNING); - return; - } - - blocked = deepBlock = false; - - startRealTime = System.currentTimeMillis(); - lastRealTime = startRealTime; - lastRealReplayTime = 0; - lastTimestamp = -1; - lastSpeed = 1f; - linear = ReplayMod.replaySettings.isLinearMovement(); - ReplayHandler.sortKeyframes(); - ReplayHandler.setInPath(true); - previousReplaySpeed = ReplayHandler.getSpeed(); - - EnchantmentTimer.resetRecordingTime(); - - TimeKeyframe tf = ReplayHandler.getNextTimeKeyframe(-1); - if(tf != null) { - int ts = tf.getTimestamp(); - if(ts < ReplayHandler.getReplayTime()) { - mc.displayGuiScreen(null); - } - ReplayHandler.setReplayTime(ts); - } - - ChatMessageRequests.addChatMessage("Replay started!", ChatMessageType.INFORMATION); - - if(isVideoRecording()) { - MCTimerHandler.setTimerSpeed(1f); - MCTimerHandler.setPassiveTimer(); - } - } - - public static void stopReplayProcess(boolean finished) { - if(!ReplayHandler.isInPath()) return; - if(finished) ChatMessageRequests.addChatMessage("Replay finished!", ChatMessageType.INFORMATION); - else { - ChatMessageRequests.addChatMessage("Replay stopped!", ChatMessageType.INFORMATION); - if(isVideoRecording()) { - VideoWriter.abortRecording(); - } - } - ReplayHandler.setInPath(false); - ReplayHandler.stopHurrying(); - MCTimerHandler.setActiveTimer(); - ReplayHandler.setSpeed(previousReplaySpeed); - ReplayHandler.setSpeed(0); - } - - private static boolean blocked = false; - private static boolean deepBlock = false; - - private static boolean requestFinish = false; - - public static void unblockAndTick(boolean justCheck) { - if(!deepBlock) blocked = false; - if(!blocked || !isVideoRecording()) - ReplayProcess.tickReplay(justCheck); - } - - public static void tickReplay(boolean justCheck) { - pathTick(isVideoRecording(), justCheck); - } - - private static float lastPartialTicks, lastRenderPartialTicks; - private static int lastTicks; - - private static boolean resetTimer = false; - - private static boolean firstTime = false; - - private static void pathTick(boolean recording, boolean justCheck) { - if(ReplayHandler.isHurrying()) { - lastRealTime = System.currentTimeMillis(); - return; - } - - if(firstTime) { - firstTime = false; - lastPartialTicks = 100; - lastRenderPartialTicks = 100; - lastTicks = 100; - MCTimerHandler.setRenderPartialTicks(100); - MCTimerHandler.setPartialTicks(100); - MCTimerHandler.setTicks(100); - System.out.println(ReplayHandler.getReplayTime()); - } - - if(recording && ((ReplayMod.replaySettings.getWaitForChunks() && RenderChunk.renderChunksUpdated != 0) || mc.currentScreen instanceof GuiCancelRender)) { - if(!firstTime) { - MCTimerHandler.setTimerSpeed(0f); - MCTimerHandler.setPartialTicks(0f); - MCTimerHandler.setRenderPartialTicks(0f); - MCTimerHandler.setTicks(0); - resetTimer = true; - } - return; - } else if (recording && ReplayMod.replaySettings.getWaitForChunks()) { - MCTimerHandler.setTimerSpeed((float)lastSpeed); - //MCTimerHandler.setRenderPartialTicks(lastRenderPartialTicks); - if(resetTimer) { - MCTimerHandler.setPartialTicks(lastPartialTicks); - MCTimerHandler.setRenderPartialTicks(lastRenderPartialTicks); - MCTimerHandler.setTicks(lastTicks); - resetTimer = false; - } - } - - if(justCheck) return; - - if(recording) { - if(blocked) return; - - deepBlock = true; - blocked = true; - } - - int posCount = ReplayHandler.getPosKeyframeCount(); - int timeCount = ReplayHandler.getTimeKeyframeCount(); - - if(!linear && motionSpline == null) { - //set up spline path - motionSpline = new SplinePoint(); - for(Keyframe kf : ReplayHandler.getKeyframes()) { - if(kf instanceof PositionKeyframe) { - PositionKeyframe pkf = (PositionKeyframe)kf; - Position pos = pkf.getPosition(); - motionSpline.addPoint(pos); - } - } - } - - if(linear && motionLinear == null) { - //set up linear path - motionLinear = new LinearPoint(); - for(Keyframe kf : ReplayHandler.getKeyframes()) { - if(kf instanceof PositionKeyframe) { - PositionKeyframe pkf = (PositionKeyframe)kf; - Position pos = pkf.getPosition(); - motionLinear.addPoint(pos); - } - } - } - if(timeLinear == null) { - timeLinear = new LinearTimestamp(); - for(Keyframe kf : ReplayHandler.getKeyframes()) { - if(kf instanceof TimeKeyframe) { - timeLinear.addPoint(((TimeKeyframe)kf).getTimestamp()); - } - } - } - - if(!calculated) { - calculated = true; - if(posCount > 1 && motionSpline != null) - motionSpline.calcSpline(); - } - - long curTime = System.currentTimeMillis(); - long timeStep; - if(recording) { - timeStep = 1000/ReplayMod.replaySettings.getVideoFramerate(); - } else { - timeStep = curTime - lastRealTime; - } - - int curRealReplayTime = (int)(lastRealReplayTime + timeStep); - - PositionKeyframe lastPos = ReplayHandler.getPreviousPositionKeyframe(curRealReplayTime); - PositionKeyframe nextPos = ReplayHandler.getNextPositionKeyframe(curRealReplayTime); - - ReplayHandler.setRealTimelineCursor(curRealReplayTime); - - int lastPosStamp = 0; - int nextPosStamp = 0; - - if(nextPos != null || lastPos != null) { - if(nextPos != null) { - nextPosStamp = nextPos.getRealTimestamp(); - } else { - nextPosStamp = lastPos.getRealTimestamp(); - } - - if(lastPos != null) { - lastPosStamp = lastPos.getRealTimestamp(); - } else { - lastPosStamp = nextPos.getRealTimestamp(); - } - } - - TimeKeyframe lastTime = ReplayHandler.getPreviousTimeKeyframe(curRealReplayTime); - TimeKeyframe nextTime = ReplayHandler.getNextTimeKeyframe(curRealReplayTime); - - int lastTimeStamp = 0; - int nextTimeStamp = 0; - - double curSpeed = 0; - - if(timeCount > 1 && (nextTime != null || lastTime != null)) { - - if(nextTime != null && lastTime != null && nextTime.getRealTimestamp() == lastTime.getRealTimestamp()) { - curSpeed = 0; - } else { - if(nextTime != null) { - nextTimeStamp = nextTime.getRealTimestamp(); - } else { - nextTimeStamp = lastTime.getRealTimestamp(); - } - - if(lastTime != null) { - lastTimeStamp = lastTime.getRealTimestamp(); - } else { - lastTimeStamp = nextTime.getRealTimestamp(); - } - - if(!(nextTime == null || lastTime == null)) { - if(lastTimeStamp == nextTimeStamp) curSpeed = 0f; - else curSpeed = ((double)((nextTime.getTimestamp()-lastTime.getTimestamp())))/((double)((nextTimeStamp-lastTimeStamp))); - } - - if(lastTimeStamp == nextTimeStamp) { - curSpeed = 0f; - } - } - } - - int currentPosDiff = nextPosStamp - lastPosStamp; - int currentPos = curRealReplayTime - lastPosStamp; - - float currentPosStepPerc = (float)currentPos/(float)currentPosDiff; //The percentage of the travelled path between the current positions - if(Float.isInfinite(currentPosStepPerc)) currentPosStepPerc = 0; - - int currentTimeDiff = nextTimeStamp - lastTimeStamp; - int currentTime = curRealReplayTime - lastTimeStamp; - - float currentTimeStepPerc = (float)currentTime/(float)currentTimeDiff; //The percentage of the travelled path between the current timestamps - if(Float.isInfinite(currentTimeStepPerc)) currentTimeStepPerc = 0; - - float splinePos = ((float)ReplayHandler.getKeyframeIndex(lastPos) + currentPosStepPerc)/(float)(posCount-1); - float timePos = ((float)ReplayHandler.getKeyframeIndex(lastTime) + currentTimeStepPerc)/(float)(timeCount-1); - - Position pos = null; - if(posCount > 1) { - if(!linear) { - pos = motionSpline.getPoint(Math.max(0, Math.min(1, splinePos))); - } else { - pos = motionLinear.getPoint(Math.max(0, Math.min(1, splinePos))); - } - } else { - if(posCount == 1) { - pos = ReplayHandler.getNextPositionKeyframe(-1).getPosition(); - } - } - - Integer curTimestamp = null; - if(timeLinear != null && timeCount > 1) { - curTimestamp = timeLinear.getPoint(Math.max(0, Math.min(1, timePos))); - } - - if(pos != null) { - ReplayHandler.getCameraEntity().movePath(pos); - } - - if(curSpeed > 0) { - ReplayHandler.setSpeed(curSpeed); - lastSpeed = curSpeed; - } - - if(recording) { - MCTimerHandler.updateTimer((1f/ReplayMod.replaySettings.getVideoFramerate())); - EnchantmentTimer.increaseRecordingTime((1000/ReplayMod.replaySettings.getVideoFramerate())); - } - - lastPartialTicks = MCTimerHandler.getPartialTicks(); - lastRenderPartialTicks = MCTimerHandler.getRenderTicks(); - lastTicks = MCTimerHandler.getTicks(); - - if(curTimestamp != null && curTimestamp != ReplayHandler.getDesiredTimestamp()) ReplayHandler.setReplayTime(curTimestamp); - - //splinePos = (index of last entry + add) / total entries - - lastRealReplayTime = curRealReplayTime; - lastRealTime = curTime; - - if(isVideoRecording()) { - try { - if(!VideoWriter.isRecording() && ReplayHandler.isInPath()) { - VideoWriter.startRecording(mc.displayWidth, mc.displayHeight); - } else { - final BufferedImage screen = ScreenCapture.captureScreen(); - VideoWriter.writeImage(screen); - } - } catch(Exception e) { - e.printStackTrace(); - } - } - - if(requestFinish) { - stopReplayProcess(true); - requestFinish = false; - if(recording) { - VideoWriter.endRecording(); - } - } - - if((splinePos >= 1 || posCount <= 1) && (timePos >= 1 || timeCount <= 1)) { - requestFinish = true; - } - - if(recording) { - deepBlock = false; - } - } + private static Minecraft mc = Minecraft.getMinecraft(); + + private static long startRealTime; + private static int lastRealReplayTime; + private static long lastRealTime = 0; + + private static boolean linear = false; + + private static Position lastPosition = null; + private static int lastTimestamp = -1; + + private static SplinePoint motionSpline = null; + private static LinearPoint motionLinear = null; + private static LinearTimestamp timeLinear = null; + + private static double lastSpeed = 1f; + + private static double previousReplaySpeed = 0; + + private static boolean calculated = false; + + private static boolean isVideoRecording = false; + private static boolean blocked = false; + private static boolean deepBlock = false; + private static boolean requestFinish = false; + private static float lastPartialTicks, lastRenderPartialTicks; + private static int lastTicks; + private static boolean resetTimer = false; + private static boolean firstTime = false; + + public static boolean isVideoRecording() { + return isVideoRecording; + } + + public static void startReplayProcess(boolean record) { + ReplayHandler.selectKeyframe(null); + + firstTime = true; + + isVideoRecording = record; + lastPosition = null; + motionSpline = null; + motionLinear = null; + timeLinear = null; + calculated = false; + requestFinish = false; + + ReplayMod.replaySender.resetToleratedTimeStamp(); + + ReplayMod.chatMessageHandler.initialize(); + if(ReplayHandler.getPosKeyframeCount() < 2 && ReplayHandler.getTimeKeyframeCount() < 2) { + ReplayMod.chatMessageHandler.addChatMessage("At least 2 position or time keyframes required!", ChatMessageType.WARNING); + return; + } + + blocked = deepBlock = false; + + startRealTime = System.currentTimeMillis(); + lastRealTime = startRealTime; + lastRealReplayTime = 0; + lastTimestamp = -1; + lastSpeed = 1f; + linear = ReplayMod.replaySettings.isLinearMovement(); + ReplayHandler.sortKeyframes(); + ReplayHandler.setInPath(true); + previousReplaySpeed = ReplayMod.replaySender.getReplaySpeed(); + + EnchantmentTimer.resetRecordingTime(); + + TimeKeyframe tf = ReplayHandler.getNextTimeKeyframe(-1); + if(tf != null) { + int ts = tf.getTimestamp(); + if(ts < ReplayMod.replaySender.currentTimeStamp()) { + mc.displayGuiScreen(null); + } + ReplayMod.replaySender.jumpToTime(ts); + } + + ReplayMod.chatMessageHandler.addChatMessage("Replay started!", ChatMessageType.INFORMATION); + + if(isVideoRecording()) { + MCTimerHandler.setTimerSpeed(1f); + MCTimerHandler.setPassiveTimer(); + } + } + + public static void stopReplayProcess(boolean finished) { + if(!ReplayHandler.isInPath()) return; + if(finished) ReplayMod.chatMessageHandler.addChatMessage("Replay finished!", ChatMessageType.INFORMATION); + else { + ReplayMod.chatMessageHandler.addChatMessage("Replay stopped!", ChatMessageType.INFORMATION); + if(isVideoRecording()) { + VideoWriter.abortRecording(); + } + } + ReplayHandler.setInPath(false); + ReplayMod.replaySender.stopHurrying(); + MCTimerHandler.setActiveTimer(); + ReplayMod.replaySender.setReplaySpeed(previousReplaySpeed); + ReplayMod.replaySender.setReplaySpeed(0); + } + + public static void unblockAndTick(boolean justCheck) { + if(!deepBlock) blocked = false; + if(!blocked || !isVideoRecording()) + ReplayProcess.tickReplay(justCheck); + } + + public static void tickReplay(boolean justCheck) { + pathTick(isVideoRecording(), justCheck); + } + + private static void pathTick(boolean recording, boolean justCheck) { + if(ReplayMod.replaySender.isHurrying()) { + lastRealTime = System.currentTimeMillis(); + return; + } + + if(firstTime) { + firstTime = false; + lastPartialTicks = 100; + lastRenderPartialTicks = 100; + lastTicks = 100; + MCTimerHandler.setRenderPartialTicks(100); + MCTimerHandler.setPartialTicks(100); + MCTimerHandler.setTicks(100); + } + + if(recording && ((ReplayMod.replaySettings.getWaitForChunks() && RenderChunk.renderChunksUpdated != 0) || mc.currentScreen instanceof GuiCancelRender)) { + if(!firstTime) { + MCTimerHandler.setTimerSpeed(0f); + MCTimerHandler.setPartialTicks(0f); + MCTimerHandler.setRenderPartialTicks(0f); + MCTimerHandler.setTicks(0); + resetTimer = true; + } + return; + } else if(recording && ReplayMod.replaySettings.getWaitForChunks()) { + MCTimerHandler.setTimerSpeed((float) lastSpeed); + //MCTimerHandler.setRenderPartialTicks(lastRenderPartialTicks); + if(resetTimer) { + MCTimerHandler.setPartialTicks(lastPartialTicks); + MCTimerHandler.setRenderPartialTicks(lastRenderPartialTicks); + MCTimerHandler.setTicks(lastTicks); + resetTimer = false; + } + } + + if(justCheck) return; + + if(recording) { + if(blocked) return; + + deepBlock = true; + blocked = true; + } + + int posCount = ReplayHandler.getPosKeyframeCount(); + int timeCount = ReplayHandler.getTimeKeyframeCount(); + + if(!linear && motionSpline == null) { + //set up spline path + motionSpline = new SplinePoint(); + for(Keyframe kf : ReplayHandler.getKeyframes()) { + if(kf instanceof PositionKeyframe) { + PositionKeyframe pkf = (PositionKeyframe) kf; + Position pos = pkf.getPosition(); + motionSpline.addPoint(pos); + } + } + } + + if(linear && motionLinear == null) { + //set up linear path + motionLinear = new LinearPoint(); + for(Keyframe kf : ReplayHandler.getKeyframes()) { + if(kf instanceof PositionKeyframe) { + PositionKeyframe pkf = (PositionKeyframe) kf; + Position pos = pkf.getPosition(); + motionLinear.addPoint(pos); + } + } + } + if(timeLinear == null) { + timeLinear = new LinearTimestamp(); + for(Keyframe kf : ReplayHandler.getKeyframes()) { + if(kf instanceof TimeKeyframe) { + timeLinear.addPoint(((TimeKeyframe) kf).getTimestamp()); + } + } + } + + if(!calculated) { + calculated = true; + if(posCount > 1 && motionSpline != null) + motionSpline.calcSpline(); + } + + long curTime = System.currentTimeMillis(); + long timeStep; + if(recording) { + timeStep = 1000 / ReplayMod.replaySettings.getVideoFramerate(); + } else { + timeStep = curTime - lastRealTime; + } + + int curRealReplayTime = (int) (lastRealReplayTime + timeStep); + + PositionKeyframe lastPos = ReplayHandler.getPreviousPositionKeyframe(curRealReplayTime); + PositionKeyframe nextPos = ReplayHandler.getNextPositionKeyframe(curRealReplayTime); + + ReplayHandler.setRealTimelineCursor(curRealReplayTime); + + int lastPosStamp = 0; + int nextPosStamp = 0; + + if(nextPos != null || lastPos != null) { + if(nextPos != null) { + nextPosStamp = nextPos.getRealTimestamp(); + } else { + nextPosStamp = lastPos.getRealTimestamp(); + } + + if(lastPos != null) { + lastPosStamp = lastPos.getRealTimestamp(); + } else { + lastPosStamp = nextPos.getRealTimestamp(); + } + } + + TimeKeyframe lastTime = ReplayHandler.getPreviousTimeKeyframe(curRealReplayTime); + TimeKeyframe nextTime = ReplayHandler.getNextTimeKeyframe(curRealReplayTime); + + int lastTimeStamp = 0; + int nextTimeStamp = 0; + + double curSpeed = 0; + + if(timeCount > 1 && (nextTime != null || lastTime != null)) { + + if(nextTime != null && lastTime != null && nextTime.getRealTimestamp() == lastTime.getRealTimestamp()) { + curSpeed = 0; + } else { + if(nextTime != null) { + nextTimeStamp = nextTime.getRealTimestamp(); + } else { + nextTimeStamp = lastTime.getRealTimestamp(); + } + + if(lastTime != null) { + lastTimeStamp = lastTime.getRealTimestamp(); + } else { + lastTimeStamp = nextTime.getRealTimestamp(); + } + + if(!(nextTime == null || lastTime == null)) { + if(lastTimeStamp == nextTimeStamp) curSpeed = 0f; + else + curSpeed = ((double) ((nextTime.getTimestamp() - lastTime.getTimestamp()))) / ((double) ((nextTimeStamp - lastTimeStamp))); + } + + if(lastTimeStamp == nextTimeStamp) { + curSpeed = 0f; + } + } + } + + int currentPosDiff = nextPosStamp - lastPosStamp; + int currentPos = curRealReplayTime - lastPosStamp; + + float currentPosStepPerc = (float) currentPos / (float) currentPosDiff; //The percentage of the travelled path between the current positions + if(Float.isInfinite(currentPosStepPerc)) currentPosStepPerc = 0; + + int currentTimeDiff = nextTimeStamp - lastTimeStamp; + int currentTime = curRealReplayTime - lastTimeStamp; + + float currentTimeStepPerc = (float) currentTime / (float) currentTimeDiff; //The percentage of the travelled path between the current timestamps + if(Float.isInfinite(currentTimeStepPerc)) currentTimeStepPerc = 0; + + float splinePos = ((float) ReplayHandler.getKeyframeIndex(lastPos) + currentPosStepPerc) / (float) (posCount - 1); + float timePos = ((float) ReplayHandler.getKeyframeIndex(lastTime) + currentTimeStepPerc) / (float) (timeCount - 1); + + Position pos = null; + if(posCount > 1) { + if(!linear) { + pos = motionSpline.getPoint(Math.max(0, Math.min(1, splinePos))); + } else { + pos = motionLinear.getPoint(Math.max(0, Math.min(1, splinePos))); + } + } else { + if(posCount == 1) { + pos = ReplayHandler.getNextPositionKeyframe(-1).getPosition(); + } + } + + Integer curTimestamp = null; + if(timeLinear != null && timeCount > 1) { + curTimestamp = timeLinear.getPoint(Math.max(0, Math.min(1, timePos))); + } + + if(pos != null) { + ReplayHandler.getCameraEntity().movePath(pos); + } + + if(curSpeed > 0) { + ReplayMod.replaySender.setReplaySpeed(curSpeed); + lastSpeed = curSpeed; + } + + if(recording) { + MCTimerHandler.updateTimer((1f / ReplayMod.replaySettings.getVideoFramerate())); + EnchantmentTimer.increaseRecordingTime((1000 / ReplayMod.replaySettings.getVideoFramerate())); + } + + lastPartialTicks = MCTimerHandler.getPartialTicks(); + lastRenderPartialTicks = MCTimerHandler.getRenderTicks(); + lastTicks = MCTimerHandler.getTicks(); + + if(curTimestamp != null && curTimestamp != ReplayMod.replaySender.getDesiredTimestamp()) + ReplayMod.replaySender.jumpToTime(curTimestamp); + + //splinePos = (index of last entry + add) / total entries + + lastRealReplayTime = curRealReplayTime; + lastRealTime = curTime; + + if(isVideoRecording()) { + try { + if(!VideoWriter.isRecording() && ReplayHandler.isInPath()) { + VideoWriter.startRecording(mc.displayWidth, mc.displayHeight); + } else { + final BufferedImage screen = ScreenCapture.captureScreen(); + VideoWriter.writeImage(screen); + } + } catch(Exception e) { + e.printStackTrace(); + } + } + + if(requestFinish) { + stopReplayProcess(true); + requestFinish = false; + if(recording) { + VideoWriter.endRecording(); + } + } + + if((splinePos >= 1 || posCount <= 1) && (timePos >= 1 || timeCount <= 1)) { + requestFinish = true; + } + + if(recording) { + deepBlock = false; + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/replay/ReplaySender.java b/src/main/java/eu/crushedpixel/replaymod/replay/ReplaySender.java index 01feec1c..ae508d14 100755 --- a/src/main/java/eu/crushedpixel/replaymod/replay/ReplaySender.java +++ b/src/main/java/eu/crushedpixel/replaymod/replay/ReplaySender.java @@ -1,66 +1,6 @@ package eu.crushedpixel.replaymod.replay; -import io.netty.channel.ChannelHandler.Sharable; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandlerAdapter; - -import java.io.BufferedReader; -import java.io.DataInputStream; -import java.io.EOFException; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.lang.reflect.Field; -import java.net.URL; -import java.util.ArrayList; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiDownloadTerrain; -import net.minecraft.client.particle.EffectRenderer; -import net.minecraft.client.resources.ResourcePackRepository; -import net.minecraft.entity.Entity; -import net.minecraft.network.EnumConnectionState; -import net.minecraft.network.NetworkManager; -import net.minecraft.network.Packet; -import net.minecraft.network.play.server.S01PacketJoinGame; -import net.minecraft.network.play.server.S02PacketChat; -import net.minecraft.network.play.server.S03PacketTimeUpdate; -import net.minecraft.network.play.server.S06PacketUpdateHealth; -import net.minecraft.network.play.server.S07PacketRespawn; -import net.minecraft.network.play.server.S08PacketPlayerPosLook; -import net.minecraft.network.play.server.S0BPacketAnimation; -import net.minecraft.network.play.server.S0CPacketSpawnPlayer; -import net.minecraft.network.play.server.S1CPacketEntityMetadata; -import net.minecraft.network.play.server.S1DPacketEntityEffect; -import net.minecraft.network.play.server.S1FPacketSetExperience; -import net.minecraft.network.play.server.S28PacketEffect; -import net.minecraft.network.play.server.S29PacketSoundEffect; -import net.minecraft.network.play.server.S2APacketParticles; -import net.minecraft.network.play.server.S2BPacketChangeGameState; -import net.minecraft.network.play.server.S2DPacketOpenWindow; -import net.minecraft.network.play.server.S2EPacketCloseWindow; -import net.minecraft.network.play.server.S2FPacketSetSlot; -import net.minecraft.network.play.server.S30PacketWindowItems; -import net.minecraft.network.play.server.S36PacketSignEditorOpen; -import net.minecraft.network.play.server.S37PacketStatistics; -import net.minecraft.network.play.server.S38PacketPlayerListItem; -import net.minecraft.network.play.server.S39PacketPlayerAbilities; -import net.minecraft.network.play.server.S43PacketCamera; -import net.minecraft.network.play.server.S45PacketTitle; -import net.minecraft.network.play.server.S48PacketResourcePackSend; -import net.minecraft.world.EnumDifficulty; -import net.minecraft.world.WorldSettings.GameType; -import net.minecraft.world.WorldType; -import net.minecraftforge.fml.client.FMLClientHandler; - -import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; -import org.apache.commons.compress.archivers.zip.ZipFile; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.FilenameUtils; - import com.google.gson.Gson; - import eu.crushedpixel.replaymod.ReplayMod; import eu.crushedpixel.replaymod.entities.CameraEntity; import eu.crushedpixel.replaymod.events.RecordingHandler; @@ -69,465 +9,371 @@ import eu.crushedpixel.replaymod.holders.Position; import eu.crushedpixel.replaymod.recording.ConnectionEventHandler; import eu.crushedpixel.replaymod.recording.ReplayMetaData; import eu.crushedpixel.replaymod.reflection.MCPNames; -import eu.crushedpixel.replaymod.registry.LightingHandler; import eu.crushedpixel.replaymod.timer.MCTimerHandler; import eu.crushedpixel.replaymod.utils.ReplayFileIO; +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import net.minecraft.client.Minecraft; +import net.minecraft.client.particle.EffectRenderer; +import net.minecraft.client.resources.ResourcePackRepository; +import net.minecraft.entity.Entity; +import net.minecraft.network.EnumConnectionState; +import net.minecraft.network.NetworkManager; +import net.minecraft.network.Packet; +import net.minecraft.network.play.server.*; +import net.minecraft.world.EnumDifficulty; +import net.minecraft.world.WorldSettings.GameType; +import net.minecraft.world.WorldType; +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.ZipFile; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.FilenameUtils; + +import java.io.*; +import java.lang.reflect.Field; +import java.net.URL; +import java.util.ArrayList; @Sharable public class ReplaySender extends ChannelInboundHandlerAdapter { - private long currentTimeStamp; - private boolean hurryToTimestamp; - private long desiredTimeStamp = -1; - private long toleratedTimeStamp = -1; - private long lastTimeStamp, lastPacketSent; + private static Field playerUUIDField; + private static Field gameProfileField; - private boolean hasRestarted = false; + static { + try { + playerUUIDField = S0CPacketSpawnPlayer.class.getDeclaredField(MCPNames.field("field_179820_b")); + playerUUIDField.setAccessible(true); - private File replayFile; - private boolean active = true; - private ZipFile archive; - private DataInputStream dis; - private ChannelHandlerContext ctx = null; + gameProfileField = S38PacketPlayerListItem.AddPlayerData.class.getDeclaredField("field_179964_d"); + gameProfileField.setAccessible(true); - private boolean startFromBeginning = true; + //dataWatcherField = S0CPacketSpawnPlayer.class.getDeclaredField(MCPNames.field("field_148960_i")); + //dataWatcherField.setAccessible(true); + } catch(Exception e) { + e.printStackTrace(); + } + } - private NetworkManager networkManager; - private boolean terminate = false; + private int currentTimeStamp; + private boolean hurryToTimestamp; + private long desiredTimeStamp = -1; + private long toleratedTimeStamp = -1; + private long lastTimeStamp, lastPacketSent; + private boolean hasRestarted = false; + private File replayFile; + private boolean active = true; + private ZipFile archive; + private DataInputStream dis; + private ChannelHandlerContext ctx = null; + private boolean startFromBeginning = true; + private NetworkManager networkManager; + private boolean terminate = false; + private double replaySpeed = 1f; + private boolean hasWorldLoaded = false; + private Field joinPacketEntityId, joinPacketWorldType, + joinPacketDimension, joinPacketDifficulty, joinPacketMaxPlayers; + private Field effectPacketEntityId; + private Field metadataPacketEntityId, metadataPacketList; + private Field animationPacketEntityId; + private Field entityDataWatcher; + private Field chatPacketPosition; + private Minecraft mc = Minecraft.getMinecraft(); + private long now = System.currentTimeMillis(); + private int replayLength = 0; + private int actualID = -1; + private EffectRenderer old = mc.effectRenderer; + private ZipArchiveEntry replayEntry; + private ArrayList badPackets = new ArrayList() { + { + add(S28PacketEffect.class); + add(S2BPacketChangeGameState.class); + add(S06PacketUpdateHealth.class); + add(S2DPacketOpenWindow.class); + add(S2EPacketCloseWindow.class); + add(S2FPacketSetSlot.class); + add(S30PacketWindowItems.class); + add(S36PacketSignEditorOpen.class); + add(S37PacketStatistics.class); + add(S1FPacketSetExperience.class); + add(S43PacketCamera.class); + add(S39PacketPlayerAbilities.class); + } + }; + private boolean allowMovement = false; + private Thread sender = new Thread(new Runnable() { - private double replaySpeed = 1f; - - private boolean hasWorldLoaded = false; + @Override + public void run() { + try { + dis = new DataInputStream(archive.getInputStream(replayEntry)); + } catch(Exception e) { + e.printStackTrace(); + } - private Field joinPacketEntityId, joinPacketWorldType, - joinPacketDimension, joinPacketDifficulty, joinPacketMaxPlayers; + try { + while(ctx == null && !terminate) { + Thread.sleep(10); + } + while(!terminate) { + if(startFromBeginning) { + hasRestarted = true; + hasWorldLoaded = false; + currentTimeStamp = 0; + dis.close(); + dis = new DataInputStream(archive.getInputStream(replayEntry)); + startFromBeginning = false; + lastPacketSent = System.currentTimeMillis(); + ReplayHandler.restartReplay(); + } - private Field effectPacketEntityId; - private Field metadataPacketEntityId, metadataPacketList; - - private Field animationPacketEntityId; - private Field entityDataWatcher; - - private Field chatPacketPosition; - - private Minecraft mc = Minecraft.getMinecraft(); - - private long now = System.currentTimeMillis(); - - private int replayLength = 0; - - private int actualID = -1; - - private EffectRenderer old = mc.effectRenderer; - - private ZipArchiveEntry replayEntry; - - public boolean isHurrying() { - return hurryToTimestamp; - } - - public long currentTimeStamp() { - return currentTimeStamp; - } - - public int replayLength() { - return replayLength; - } - - public void stopHurrying() { - hurryToTimestamp = false; - } - - public void terminateReplay() { - terminate = true; - try { - channelInactive(ctx); - ctx.channel().pipeline().close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public long getDesiredTimestamp() { - return desiredTimeStamp; - } - - public void resetToleratedTimeStamp() { - toleratedTimeStamp = -1; - } - - public void jumpToTime(int millis) { - if(!(ReplayHandler.isInPath() && ReplayProcess.isVideoRecording())) setReplaySpeed(replaySpeed); - - if((millis < currentTimeStamp && !isHurrying())) { - if(ReplayHandler.isInPath()) { - if(millis >= toleratedTimeStamp && toleratedTimeStamp >= 0) { - return; - } - } - startFromBeginning = true; - } - - desiredTimeStamp = millis; - if(ReplayHandler.isInPath()) { - toleratedTimeStamp = millis; - } - hurryToTimestamp = true; - - } - - public void setReplaySpeed(final double d) { - if(d != 0) this.replaySpeed = d; - MCTimerHandler.setTimerSpeed((float)d); - } - - public ReplaySender(final File replayFile, NetworkManager nm) { - try { - joinPacketEntityId = S01PacketJoinGame.class.getDeclaredField(MCPNames.field("field_149206_a")); - joinPacketEntityId.setAccessible(true); - - joinPacketDifficulty = S01PacketJoinGame.class.getDeclaredField(MCPNames.field("field_149203_e")); - joinPacketDifficulty.setAccessible(true); - - joinPacketDimension = S01PacketJoinGame.class.getDeclaredField(MCPNames.field("field_149202_d")); - joinPacketDimension.setAccessible(true); - - joinPacketMaxPlayers = S01PacketJoinGame.class.getDeclaredField(MCPNames.field("field_149200_f")); - joinPacketMaxPlayers.setAccessible(true); - - joinPacketWorldType = S01PacketJoinGame.class.getDeclaredField(MCPNames.field("field_149201_g")); - joinPacketWorldType.setAccessible(true); - - effectPacketEntityId = S1DPacketEntityEffect.class.getDeclaredField(MCPNames.field("field_149434_a")); - effectPacketEntityId.setAccessible(true); - - metadataPacketEntityId = S1CPacketEntityMetadata.class.getDeclaredField(MCPNames.field("field_149379_a")); - metadataPacketEntityId.setAccessible(true); - - metadataPacketList = S1CPacketEntityMetadata.class.getDeclaredField(MCPNames.field("field_149378_b")); - metadataPacketList.setAccessible(true); - - animationPacketEntityId = S0BPacketAnimation.class.getDeclaredField(MCPNames.field("field_148981_a")); - animationPacketEntityId.setAccessible(true); - - entityDataWatcher = Entity.class.getDeclaredField(MCPNames.field("field_70180_af")); - entityDataWatcher.setAccessible(true); - - chatPacketPosition = S02PacketChat.class.getDeclaredField(MCPNames.field("field_179842_b")); - chatPacketPosition.setAccessible(true); - - } catch (Exception e) { - e.printStackTrace(); - } - - this.replayFile = replayFile; - this.networkManager = nm; - if(("."+FilenameUtils.getExtension(replayFile.getAbsolutePath())).equals(ConnectionEventHandler.ZIP_FILE_EXTENSION)) { - try { - archive = new ZipFile(replayFile); - replayEntry = archive.getEntry("recording"+ConnectionEventHandler.TEMP_FILE_EXTENSION); - - ZipArchiveEntry metadata = archive.getEntry("metaData"+ConnectionEventHandler.JSON_FILE_EXTENSION); - InputStream is = archive.getInputStream(metadata); - BufferedReader br = new BufferedReader(new InputStreamReader(is)); - - String json = br.readLine(); - - ReplayMetaData metaData = new Gson().fromJson(json, ReplayMetaData.class); - - this.replayLength = metaData.getDuration(); - - sender.start(); - } catch(Exception e) { - e.printStackTrace(); - } - } - } - - private Thread sender = new Thread(new Runnable() { - - @Override - public void run() { - try { - dis = new DataInputStream(archive.getInputStream(replayEntry)); - } catch(Exception e) { - e.printStackTrace(); - } - - try { - while(ctx == null && !terminate) { - Thread.sleep(10); - } - while(!terminate) { - if(startFromBeginning) { - hasRestarted = true; - hasWorldLoaded = false; - currentTimeStamp = 0; - dis.close(); - dis = new DataInputStream(archive.getInputStream(replayEntry)); - startFromBeginning = false; - lastPacketSent = System.currentTimeMillis(); - ReplayHandler.restartReplay(); - } - - while(!terminate && !startFromBeginning && (!paused() || !hasWorldLoaded)) { - try { - /* - * LOGIC: + while(!terminate && !startFromBeginning && (!paused() || !hasWorldLoaded)) { + try { + /* + * LOGIC: * While behind desired timestamp, only send packets * until desired timestamp is reached, * then increase desired timestamp by 1/20th of a second - * + * * Desired timestamp is divided through stretch factor. - * + * * If hurrying, don't wait for correct timing. */ - if(!hurryToTimestamp && ReplayHandler.isInPath()) { - continue; - } + if(!hurryToTimestamp && ReplayHandler.isInPath()) { + continue; + } - PacketData pd = ReplayFileIO.readPacketData(dis); + PacketData pd = ReplayFileIO.readPacketData(dis); - currentTimeStamp = pd.getTimestamp(); - //System.out.println(currentTimeStamp); + currentTimeStamp = pd.getTimestamp(); + //System.out.println(currentTimeStamp); - if(!ReplayHandler.isInPath() && !hurryToTimestamp && hasWorldLoaded) { - int timeWait = (int)Math.round((currentTimeStamp - lastTimeStamp)/replaySpeed); - long timeDiff = System.currentTimeMillis() - lastPacketSent; - lastPacketSent = System.currentTimeMillis(); - long timeToSleep = Math.max(0, timeWait-timeDiff); - Thread.sleep(timeToSleep); - } + if(!ReplayHandler.isInPath() && !hurryToTimestamp && hasWorldLoaded) { + int timeWait = (int) Math.round((currentTimeStamp - lastTimeStamp) / replaySpeed); + long timeDiff = System.currentTimeMillis() - lastPacketSent; + lastPacketSent = System.currentTimeMillis(); + long timeToSleep = Math.max(0, timeWait - timeDiff); + Thread.sleep(timeToSleep); + } - ReplaySender.this.channelRead(ctx, pd.getByteArray()); + ReplaySender.this.channelRead(ctx, pd.getByteArray()); - lastTimeStamp = currentTimeStamp; + lastTimeStamp = currentTimeStamp; - if(hurryToTimestamp && currentTimeStamp >= desiredTimeStamp && !startFromBeginning) { - hurryToTimestamp = false; - if(!ReplayHandler.isInPath() || hasRestarted) { - MCTimerHandler.advanceRenderPartialTicks(5); - MCTimerHandler.advancePartialTicks(5); - MCTimerHandler.advanceTicks(5); - } - if(!ReplayHandler.isInPath()) { - Position pos = ReplayHandler.getLastPosition(); - CameraEntity cam = ReplayHandler.getCameraEntity(); - if(cam != null) { - if(Math.abs(pos.getX() - cam.posX) < ReplayMod.TP_DISTANCE_LIMIT && Math.abs(pos.getZ() - cam.posZ) < ReplayMod.TP_DISTANCE_LIMIT) - if(pos != null) { - cam.moveAbsolute(pos.getX(), pos.getY(), pos.getZ()); - cam.rotationPitch = pos.getPitch(); - cam.rotationYaw = pos.getYaw(); - } - } - } - if(!ReplayHandler.isInPath()) { - setReplaySpeed(0); - } - hasRestarted = false; - } + if(hurryToTimestamp && currentTimeStamp >= desiredTimeStamp && !startFromBeginning) { + hurryToTimestamp = false; + if(!ReplayHandler.isInPath() || hasRestarted) { + MCTimerHandler.advanceRenderPartialTicks(5); + MCTimerHandler.advancePartialTicks(5); + MCTimerHandler.advanceTicks(5); + } + if(!ReplayHandler.isInPath()) { + Position pos = ReplayHandler.getLastPosition(); + CameraEntity cam = ReplayHandler.getCameraEntity(); + if(cam != null) { + if(Math.abs(pos.getX() - cam.posX) < ReplayMod.TP_DISTANCE_LIMIT && Math.abs(pos.getZ() - cam.posZ) < ReplayMod.TP_DISTANCE_LIMIT) + if(pos != null) { + cam.moveAbsolute(pos.getX(), pos.getY(), pos.getZ()); + cam.rotationPitch = pos.getPitch(); + cam.rotationYaw = pos.getYaw(); + } + } + } + if(!ReplayHandler.isInPath()) { + setReplaySpeed(0); + } + hasRestarted = false; + } - } catch(EOFException eof) { - System.out.println("End of File encountered!"); - dis = new DataInputStream(archive.getInputStream(replayEntry)); - setReplaySpeed(0); - } catch(IOException e) { - e.printStackTrace(); - } - } - } - } catch(Exception e) { - e.printStackTrace(); - } - } - }); + } catch(EOFException eof) { + System.out.println("End of File encountered!"); + dis = new DataInputStream(archive.getInputStream(replayEntry)); + setReplaySpeed(0); + } catch(IOException e) { + e.printStackTrace(); + } + } + } + } catch(Exception e) { + e.printStackTrace(); + } + } + }); - private ArrayList badPackets = new ArrayList() { - { - add(S28PacketEffect.class); - add(S2BPacketChangeGameState.class); - add(S06PacketUpdateHealth.class); - add(S2DPacketOpenWindow.class); - add(S2EPacketCloseWindow.class); - add(S2FPacketSetSlot.class); - add(S30PacketWindowItems.class); - add(S36PacketSignEditorOpen.class); - add(S37PacketStatistics.class); - add(S1FPacketSetExperience.class); - add(S43PacketCamera.class); - add(S39PacketPlayerAbilities.class); - } - }; + public ReplaySender(final File replayFile, NetworkManager nm) { + try { + joinPacketEntityId = S01PacketJoinGame.class.getDeclaredField(MCPNames.field("field_149206_a")); + joinPacketEntityId.setAccessible(true); - private boolean allowMovement = false; + joinPacketDifficulty = S01PacketJoinGame.class.getDeclaredField(MCPNames.field("field_149203_e")); + joinPacketDifficulty.setAccessible(true); - private static Field playerUUIDField; - private static Field gameProfileField; + joinPacketDimension = S01PacketJoinGame.class.getDeclaredField(MCPNames.field("field_149202_d")); + joinPacketDimension.setAccessible(true); - //private static Field dataWatcherField; + joinPacketMaxPlayers = S01PacketJoinGame.class.getDeclaredField(MCPNames.field("field_149200_f")); + joinPacketMaxPlayers.setAccessible(true); - private static class ResourcePackCheck extends Thread { + joinPacketWorldType = S01PacketJoinGame.class.getDeclaredField(MCPNames.field("field_149201_g")); + joinPacketWorldType.setAccessible(true); - public ResourcePackCheck(String url, String hash) { - this.url = url; - this.hash = hash; - } + effectPacketEntityId = S1DPacketEntityEffect.class.getDeclaredField(MCPNames.field("field_149434_a")); + effectPacketEntityId.setAccessible(true); - private String url, hash; + metadataPacketEntityId = S1CPacketEntityMetadata.class.getDeclaredField(MCPNames.field("field_149379_a")); + metadataPacketEntityId.setAccessible(true); - private static Field serverResourcePackDirectory; - private static Minecraft mc = Minecraft.getMinecraft(); - private static ResourcePackRepository repo = mc.getResourcePackRepository(); + metadataPacketList = S1CPacketEntityMetadata.class.getDeclaredField(MCPNames.field("field_149378_b")); + metadataPacketList.setAccessible(true); - static { - try { - serverResourcePackDirectory = ResourcePackRepository.class.getDeclaredField(MCPNames.field("field_148534_e")); - serverResourcePackDirectory.setAccessible(true); - } catch(Exception e) { - e.printStackTrace(); - } - } + animationPacketEntityId = S0BPacketAnimation.class.getDeclaredField(MCPNames.field("field_148981_a")); + animationPacketEntityId.setAccessible(true); - private File getServerResourcePackLocation(String url, String hash) throws IOException, IllegalArgumentException, IllegalAccessException { + entityDataWatcher = Entity.class.getDeclaredField(MCPNames.field("field_70180_af")); + entityDataWatcher.setAccessible(true); - String filename; + chatPacketPosition = S02PacketChat.class.getDeclaredField(MCPNames.field("field_179842_b")); + chatPacketPosition.setAccessible(true); - if (hash.matches("^[a-f0-9]{40}$")) { - filename = hash; - } else { - filename = url.substring(url.lastIndexOf("/") + 1); + } catch(Exception e) { + e.printStackTrace(); + } - if (filename.contains("?")) - { - filename = filename.substring(0, filename.indexOf("?")); - } + this.replayFile = replayFile; + this.networkManager = nm; + if(("." + FilenameUtils.getExtension(replayFile.getAbsolutePath())).equals(ConnectionEventHandler.ZIP_FILE_EXTENSION)) { + try { + archive = new ZipFile(replayFile); + replayEntry = archive.getEntry("recording" + ConnectionEventHandler.TEMP_FILE_EXTENSION); - if (!filename.endsWith(".zip")) - { - return null; - } + ZipArchiveEntry metadata = archive.getEntry("metaData" + ConnectionEventHandler.JSON_FILE_EXTENSION); + InputStream is = archive.getInputStream(metadata); + BufferedReader br = new BufferedReader(new InputStreamReader(is)); - filename = "legacy_" + filename.replaceAll("\\W", ""); - } + String json = br.readLine(); - File folder = (File)serverResourcePackDirectory.get(repo); - File rp = new File(folder, filename); + ReplayMetaData metaData = new Gson().fromJson(json, ReplayMetaData.class); - return rp; - } + this.replayLength = metaData.getDuration(); - private boolean downloadServerResourcePack(String url, File file) { - try { - FileUtils.copyURLToFile(new URL(url), file); - return true; - } catch(Exception e) { - e.printStackTrace(); - } - return false; - } + sender.start(); + } catch(Exception e) { + e.printStackTrace(); + } + } + } - @Override - public void run() { - try { - boolean use = ReplayMod.instance.replaySettings.getUseResourcePacks(); - if(!use) return; + public boolean isHurrying() { + return hurryToTimestamp; + } - System.out.println("Looking for downloaded Resource Pack..."); - File rp = getServerResourcePackLocation(url, hash); - if(rp == null) { - System.out.println("Invalid Resource Pack provided"); - return; - } - if(rp.exists()) { - System.out.println("Resource Pack found!"); - repo.func_177319_a(rp); + public int currentTimeStamp() { + return currentTimeStamp; + } - } else { - System.out.println("No Resource Pack found."); - System.out.println("Attempting to download Resource Pack..."); - boolean success = downloadServerResourcePack(url, rp); - System.out.println(success ? "Resource pack was successfully downloaded!" : "Resource Pack download failed."); - if(success) { - repo.func_177319_a(rp); - } - } + public int replayLength() { + return replayLength; + } - } catch(Exception e) { - e.printStackTrace(); - } - } - } + public void stopHurrying() { + hurryToTimestamp = false; + } - static { - try { - playerUUIDField = S0CPacketSpawnPlayer.class.getDeclaredField(MCPNames.field("field_179820_b")); - playerUUIDField.setAccessible(true); + public void terminateReplay() { + terminate = true; + try { + channelInactive(ctx); + ctx.channel().pipeline().close(); + } catch(Exception e) { + e.printStackTrace(); + } + } - gameProfileField = S38PacketPlayerListItem.AddPlayerData.class.getDeclaredField("field_179964_d"); - gameProfileField.setAccessible(true); + public long getDesiredTimestamp() { + return desiredTimeStamp; + } - //dataWatcherField = S0CPacketSpawnPlayer.class.getDeclaredField(MCPNames.field("field_148960_i")); - //dataWatcherField.setAccessible(true); - } catch(Exception e) { - e.printStackTrace(); - } - } + public void resetToleratedTimeStamp() { + toleratedTimeStamp = -1; + } - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) - throws Exception { - if(terminate) { - return; - } + public void jumpToTime(int millis) { + if(!(ReplayHandler.isInPath() && ReplayProcess.isVideoRecording())) setReplaySpeed(replaySpeed); - if(ctx == null) { - ctx = this.ctx; - } + if((millis < currentTimeStamp && !isHurrying())) { + if(ReplayHandler.isInPath()) { + if(millis >= toleratedTimeStamp && toleratedTimeStamp >= 0) { + return; + } + } + startFromBeginning = true; + } - if(msg instanceof Packet) { - super.channelRead(ctx, msg); - return; - } - byte[] ba = (byte[])msg; + desiredTimeStamp = millis; + if(ReplayHandler.isInPath()) { + toleratedTimeStamp = millis; + } + hurryToTimestamp = true; - try { - Packet p = ReplayFileIO.deserializePacket(ba); + } - if(p == null) return; + //private static Field dataWatcherField; - //If hurrying, ignore some packets, unless during Replay Path and *not* in initial hurry - if(hurryToTimestamp && (!ReplayHandler.isInPath() || (desiredTimeStamp-currentTimeStamp > 1000))) { - if(p instanceof S45PacketTitle || - p instanceof S2APacketParticles) return; - } + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) + throws Exception { + if(terminate) { + return; + } - if(p instanceof S29PacketSoundEffect && ReplayHandler.isInPath() && ReplayProcess.isVideoRecording()) { - return; - } + if(ctx == null) { + ctx = this.ctx; + } - if(p instanceof S03PacketTimeUpdate) { - p = TimeHandler.getTimePacket((S03PacketTimeUpdate)p); - } + if(msg instanceof Packet) { + super.channelRead(ctx, msg); + return; + } + byte[] ba = (byte[]) msg; - if(p instanceof S48PacketResourcePackSend) { - S48PacketResourcePackSend pa = (S48PacketResourcePackSend)p; - Thread t = new ResourcePackCheck(pa.func_179783_a(), pa.func_179784_b()); - t.start(); + try { + Packet p = ReplayFileIO.deserializePacket(ba); - return; - } + if(p == null) return; - if(p instanceof S02PacketChat) { - byte pos = (Byte)chatPacketPosition.get(p); - if(pos == 1) { //Ignores command block output sent - return; - } - } + //If hurrying, ignore some packets, unless during Replay Path and *not* in initial hurry + if(hurryToTimestamp && (!ReplayHandler.isInPath() || (desiredTimeStamp - currentTimeStamp > 1000))) { + if(p instanceof S45PacketTitle || + p instanceof S2APacketParticles) return; + } - if(badPackets.contains(p.getClass())) return; + if(p instanceof S29PacketSoundEffect && ReplayHandler.isInPath() && ReplayProcess.isVideoRecording()) { + return; + } + + if(p instanceof S03PacketTimeUpdate) { + p = TimeHandler.getTimePacket((S03PacketTimeUpdate) p); + } + + if(p instanceof S48PacketResourcePackSend) { + S48PacketResourcePackSend pa = (S48PacketResourcePackSend) p; + Thread t = new ResourcePackCheck(pa.func_179783_a(), pa.func_179784_b()); + t.start(); + + return; + } + + if(p instanceof S02PacketChat) { + byte pos = (Byte) chatPacketPosition.get(p); + if(pos == 1) { //Ignores command block output sent + return; + } + } + + if(badPackets.contains(p.getClass())) return; /* if(p instanceof S0EPacketSpawnObject) { @@ -545,35 +391,35 @@ public class ReplaySender extends ChannelInboundHandlerAdapter { } */ - try { - if(p instanceof S1CPacketEntityMetadata) { - if((Integer)metadataPacketEntityId.get(p) == actualID) { - metadataPacketEntityId.set(p, RecordingHandler.entityID); - } - } + try { + if(p instanceof S1CPacketEntityMetadata) { + if((Integer) metadataPacketEntityId.get(p) == actualID) { + metadataPacketEntityId.set(p, RecordingHandler.entityID); + } + } - if(p instanceof S01PacketJoinGame) { - //System.out.println("FOUND JOIN PACKET"); - allowMovement = true; - int entId = (Integer)joinPacketEntityId.get(p); - actualID = entId; - entId = Integer.MIN_VALUE+9002; - int dimension = (Integer)joinPacketDimension.get(p); - EnumDifficulty difficulty = (EnumDifficulty)joinPacketDifficulty.get(p); - int maxPlayers = (Integer)joinPacketMaxPlayers.get(p); - WorldType worldType = (WorldType)joinPacketWorldType.get(p); + if(p instanceof S01PacketJoinGame) { + //System.out.println("FOUND JOIN PACKET"); + allowMovement = true; + int entId = (Integer) joinPacketEntityId.get(p); + actualID = entId; + entId = Integer.MIN_VALUE + 9002; + int dimension = (Integer) joinPacketDimension.get(p); + EnumDifficulty difficulty = (EnumDifficulty) joinPacketDifficulty.get(p); + int maxPlayers = (Integer) joinPacketMaxPlayers.get(p); + WorldType worldType = (WorldType) joinPacketWorldType.get(p); - p = new S01PacketJoinGame(entId, GameType.SPECTATOR, false, dimension, - difficulty, maxPlayers, worldType, false); - } + p = new S01PacketJoinGame(entId, GameType.SPECTATOR, false, dimension, + difficulty, maxPlayers, worldType, false); + } - if(p instanceof S07PacketRespawn) { - S07PacketRespawn respawn = (S07PacketRespawn)p; - p = new S07PacketRespawn(respawn.func_149082_c(), - respawn.func_149081_d(), respawn.func_149080_f(), GameType.SPECTATOR); + if(p instanceof S07PacketRespawn) { + S07PacketRespawn respawn = (S07PacketRespawn) p; + p = new S07PacketRespawn(respawn.func_149082_c(), + respawn.func_149081_d(), respawn.func_149080_f(), GameType.SPECTATOR); - allowMovement = true; - } + allowMovement = true; + } /* * Proof of concept for some nasty player manipulation ;) @@ -583,8 +429,8 @@ public class ReplaySender extends ChannelInboundHandlerAdapter { if(p instanceof S38PacketPlayerListItem) { S38PacketPlayerListItem pp = (S38PacketPlayerListItem)p; if(((AddPlayerData)pp.func_179767_a().get(0)).func_179962_a().getId().toString().replace("-", "").equals(crPxl)) { - GameProfile johniGP = new GameProfile(UUID.fromString(johni.replaceAll( - "(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", + GameProfile johniGP = new GameProfile(UUID.fromString(johni.replaceAll( + "(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")), "Johni0702"); gameProfileField.set(pp.func_179767_a().get(0), johniGP); //pp.func_179767_a().set(0, johniGP); @@ -597,8 +443,8 @@ public class ReplaySender extends ChannelInboundHandlerAdapter { S0CPacketSpawnPlayer sp = (S0CPacketSpawnPlayer)p; if(sp.func_179819_c().toString().replace("-", "").equals(crPxl)) { - playerUUIDField.set(sp, UUID.fromString(johni.replaceAll( - "(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", + playerUUIDField.set(sp, UUID.fromString(johni.replaceAll( + "(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5"))); } @@ -613,91 +459,187 @@ public class ReplaySender extends ChannelInboundHandlerAdapter { } */ - if(p instanceof S08PacketPlayerPosLook) { - if(!hasWorldLoaded) hasWorldLoaded = true; - final S08PacketPlayerPosLook ppl = (S08PacketPlayerPosLook)p; + if(p instanceof S08PacketPlayerPosLook) { + if(!hasWorldLoaded) hasWorldLoaded = true; + final S08PacketPlayerPosLook ppl = (S08PacketPlayerPosLook) p; - if(ReplayHandler.isInPath() && !hurryToTimestamp) return; + if(ReplayHandler.isInPath() && !hurryToTimestamp) return; - CameraEntity cent = ReplayHandler.getCameraEntity(); + CameraEntity cent = ReplayHandler.getCameraEntity(); - if(cent != null) { - if(!allowMovement && !((Math.abs(cent.posX - ppl.func_148932_c()) > ReplayMod.TP_DISTANCE_LIMIT) || - (Math.abs(cent.posZ - ppl.func_148933_e()) > ReplayMod.TP_DISTANCE_LIMIT))) { - return; - } else { - allowMovement = false; - } - } + if(cent != null) { + if(!allowMovement && !((Math.abs(cent.posX - ppl.func_148932_c()) > ReplayMod.TP_DISTANCE_LIMIT) || + (Math.abs(cent.posZ - ppl.func_148933_e()) > ReplayMod.TP_DISTANCE_LIMIT))) { + return; + } else { + allowMovement = false; + } + } - Thread t = new Thread(new Runnable() { + Thread t = new Thread(new Runnable() { - @Override - public void run() { - while(mc.theWorld == null) { - try { - Thread.sleep(10); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } + @Override + public void run() { + while(mc.theWorld == null) { + try { + Thread.sleep(10); + } catch(InterruptedException e) { + e.printStackTrace(); + } + } - Entity ent = ReplayHandler.getCameraEntity(); + Entity ent = ReplayHandler.getCameraEntity(); - if(ent == null || !(ent instanceof CameraEntity)) ent = new CameraEntity(mc.theWorld); - CameraEntity cent = (CameraEntity)ent; - cent.moveAbsolute(ppl.func_148932_c(), ppl.func_148928_d(), ppl.func_148933_e()); + if(ent == null || !(ent instanceof CameraEntity)) ent = new CameraEntity(mc.theWorld); + CameraEntity cent = (CameraEntity) ent; + cent.moveAbsolute(ppl.func_148932_c(), ppl.func_148928_d(), ppl.func_148933_e()); - ReplayHandler.setCameraEntity(cent); - } - }); + ReplayHandler.setCameraEntity(cent); + } + }); - t.start(); - } + t.start(); + } - if(p instanceof S43PacketCamera) { - return; - } + if(p instanceof S43PacketCamera) { + return; + } - super.channelRead(ctx, p); - } catch(Exception e) { - System.out.println(p.getClass()); - e.printStackTrace(); - } + super.channelRead(ctx, p); + } catch(Exception e) { + System.out.println(p.getClass()); + e.printStackTrace(); + } - } catch(Exception e) { - e.printStackTrace(); - } + } catch(Exception e) { + e.printStackTrace(); + } - } + } - @Override - public void channelActive(ChannelHandlerContext ctx) throws Exception { - this.ctx = ctx; - networkManager.channel().attr(networkManager.attrKeyConnectionState).set(EnumConnectionState.PLAY); - super.channelActive(ctx); - } + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + this.ctx = ctx; + networkManager.channel().attr(networkManager.attrKeyConnectionState).set(EnumConnectionState.PLAY); + super.channelActive(ctx); + } - @Override - public void channelInactive(ChannelHandlerContext ctx) throws Exception { - archive.close(); - super.channelInactive(ctx); - } + @Override + public void channelInactive(ChannelHandlerContext ctx) throws Exception { + archive.close(); + super.channelInactive(ctx); + } - public boolean paused() { - try { - return MCTimerHandler.getTimerSpeed() == 0; - } catch(Exception e) {} - return true; - } + public boolean paused() { + try { + return MCTimerHandler.getTimerSpeed() == 0; + } catch(Exception e) { + } + return true; + } - public double getReplaySpeed() { - if(!paused()) return replaySpeed; - else return 0; - } + public double getReplaySpeed() { + if(!paused()) return replaySpeed; + else return 0; + } - public File getReplayFile() { - return replayFile; - } + public void setReplaySpeed(final double d) { + if(d != 0) this.replaySpeed = d; + MCTimerHandler.setTimerSpeed((float) d); + } + + public File getReplayFile() { + return replayFile; + } + + private static class ResourcePackCheck extends Thread { + + private static Field serverResourcePackDirectory; + private static Minecraft mc = Minecraft.getMinecraft(); + private static ResourcePackRepository repo = mc.getResourcePackRepository(); + + static { + try { + serverResourcePackDirectory = ResourcePackRepository.class.getDeclaredField(MCPNames.field("field_148534_e")); + serverResourcePackDirectory.setAccessible(true); + } catch(Exception e) { + e.printStackTrace(); + } + } + + private String url, hash; + + public ResourcePackCheck(String url, String hash) { + this.url = url; + this.hash = hash; + } + + private File getServerResourcePackLocation(String url, String hash) throws IOException, IllegalArgumentException, IllegalAccessException { + + String filename; + + if(hash.matches("^[a-f0-9]{40}$")) { + filename = hash; + } else { + filename = url.substring(url.lastIndexOf("/") + 1); + + if(filename.contains("?")) { + filename = filename.substring(0, filename.indexOf("?")); + } + + if(!filename.endsWith(".zip")) { + return null; + } + + filename = "legacy_" + filename.replaceAll("\\W", ""); + } + + File folder = (File) serverResourcePackDirectory.get(repo); + File rp = new File(folder, filename); + + return rp; + } + + private boolean downloadServerResourcePack(String url, File file) { + try { + FileUtils.copyURLToFile(new URL(url), file); + return true; + } catch(Exception e) { + e.printStackTrace(); + } + return false; + } + + @Override + public void run() { + try { + boolean use = ReplayMod.instance.replaySettings.getUseResourcePacks(); + if(!use) return; + + System.out.println("Looking for downloaded Resource Pack..."); + File rp = getServerResourcePackLocation(url, hash); + if(rp == null) { + System.out.println("Invalid Resource Pack provided"); + return; + } + if(rp.exists()) { + System.out.println("Resource Pack found!"); + repo.func_177319_a(rp); + + } else { + System.out.println("No Resource Pack found."); + System.out.println("Attempting to download Resource Pack..."); + boolean success = downloadServerResourcePack(url, rp); + System.out.println(success ? "Resource pack was successfully downloaded!" : "Resource Pack download failed."); + if(success) { + repo.func_177319_a(rp); + } + } + + } catch(Exception e) { + e.printStackTrace(); + } + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/replay/TimeHandler.java b/src/main/java/eu/crushedpixel/replaymod/replay/TimeHandler.java index 437b03f9..f118e81c 100755 --- a/src/main/java/eu/crushedpixel/replaymod/replay/TimeHandler.java +++ b/src/main/java/eu/crushedpixel/replaymod/replay/TimeHandler.java @@ -4,25 +4,25 @@ import net.minecraft.network.play.server.S03PacketTimeUpdate; public class TimeHandler { - private static long actualDaytime; - private static long desiredDaytime; - - private static boolean timeOverridden = false; - - public static boolean isTimeOverridden() { - return timeOverridden; - } - - public static void setDesiredDaytime(long ddt) { - desiredDaytime = ddt; - } - - public static void setTimeOverridden(boolean overridden) { - timeOverridden = overridden; - } - - public static S03PacketTimeUpdate getTimePacket(S03PacketTimeUpdate packet) { - if(!timeOverridden) return packet; - return new S03PacketTimeUpdate(packet.func_149366_c(), desiredDaytime, true); - } + private static long actualDaytime; + private static long desiredDaytime; + + private static boolean timeOverridden = false; + + public static boolean isTimeOverridden() { + return timeOverridden; + } + + public static void setTimeOverridden(boolean overridden) { + timeOverridden = overridden; + } + + public static void setDesiredDaytime(long ddt) { + desiredDaytime = ddt; + } + + public static S03PacketTimeUpdate getTimePacket(S03PacketTimeUpdate packet) { + if(!timeOverridden) return packet; + return new S03PacketTimeUpdate(packet.func_149366_c(), desiredDaytime, true); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/replay/spectate/SpectateHandler.java b/src/main/java/eu/crushedpixel/replaymod/replay/spectate/SpectateHandler.java index ca29254a..2a3cf225 100755 --- a/src/main/java/eu/crushedpixel/replaymod/replay/spectate/SpectateHandler.java +++ b/src/main/java/eu/crushedpixel/replaymod/replay/spectate/SpectateHandler.java @@ -1,34 +1,32 @@ package eu.crushedpixel.replaymod.replay.spectate; -import java.util.List; - -import net.minecraft.client.Minecraft; -import net.minecraft.entity.player.EntityPlayer; - import com.google.common.base.Predicate; - import eu.crushedpixel.replaymod.entities.CameraEntity; import eu.crushedpixel.replaymod.gui.GuiSpectateSelection; import eu.crushedpixel.replaymod.replay.ReplayHandler; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.EntityPlayer; + +import java.util.List; public class SpectateHandler { - private static Minecraft mc = Minecraft.getMinecraft(); - - private static Predicate playerPredicate = new Predicate() { - @Override - public boolean apply(EntityPlayer input) { - if(input instanceof CameraEntity || input == mc.thePlayer) return false; - return true; - } - }; - - public static void openSpectateSelection() { - if(!ReplayHandler.isInReplay()) { - return; - } - - List players = mc.theWorld.getEntities(EntityPlayer.class, playerPredicate); - mc.displayGuiScreen(new GuiSpectateSelection(players)); - } + private static Minecraft mc = Minecraft.getMinecraft(); + + private static Predicate playerPredicate = new Predicate() { + @Override + public boolean apply(EntityPlayer input) { + if(input instanceof CameraEntity || input == mc.thePlayer) return false; + return true; + } + }; + + public static void openSpectateSelection() { + if(!ReplayHandler.isInReplay()) { + return; + } + + List players = mc.theWorld.getEntities(EntityPlayer.class, playerPredicate); + mc.displayGuiScreen(new GuiSpectateSelection(players)); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/settings/ReplaySettings.java b/src/main/java/eu/crushedpixel/replaymod/settings/ReplaySettings.java index de6ccaa2..ca4e4632 100755 --- a/src/main/java/eu/crushedpixel/replaymod/settings/ReplaySettings.java +++ b/src/main/java/eu/crushedpixel/replaymod/settings/ReplaySettings.java @@ -1,276 +1,291 @@ package eu.crushedpixel.replaymod.settings; -import java.lang.reflect.Field; +import eu.crushedpixel.replaymod.ReplayMod; +import eu.crushedpixel.replaymod.registry.LightingHandler; +import net.minecraftforge.common.config.Configuration; +import net.minecraftforge.common.config.Property; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import net.minecraft.client.Minecraft; -import net.minecraft.client.settings.GameSettings.Options; -import net.minecraft.util.Timer; -import net.minecraftforge.common.config.Configuration; -import net.minecraftforge.common.config.Property; -import eu.crushedpixel.replaymod.ReplayMod; -import eu.crushedpixel.replaymod.reflection.MCPNames; -import eu.crushedpixel.replaymod.registry.LightingHandler; -import eu.crushedpixel.replaymod.replay.ReplayHandler; - public class ReplaySettings { - public static interface ValueEnum { - public Object getValue(); - public void setValue(Object value); - } + public List getValueEnums() { + List enums = new ArrayList(); + enums.addAll(Arrays.asList(ReplayOptions.values())); + enums.addAll(Arrays.asList(RenderOptions.values())); + return enums; + } - public enum RecordingOptions implements ValueEnum { - recordServer(true), recordSingleplayer(true), notifications(true), indicator(true); + public void readValues() { + Configuration config = ReplayMod.config; - private Object value; + for(RecordingOptions o : RecordingOptions.values()) { + Property p = getConfigSetting(ReplayMod.instance.config, o.name(), o.getValue(), "recording", false); + o.setValue(getValueObject(p)); + } - public Object getValue() { - return value; - } + for(ReplayOptions o : ReplayOptions.values()) { + Property p = getConfigSetting(ReplayMod.instance.config, o.name(), o.getValue(), "replay", false); + o.setValue(getValueObject(p)); + } - public void setValue(Object value) { - this.value = value; - } + for(RenderOptions o : RenderOptions.values()) { + Property p = getConfigSetting(ReplayMod.instance.config, o.name(), o.getValue(), "render", false); + o.setValue(getValueObject(p)); + } - RecordingOptions(Object value) { - this.value = value; - } - } + for(AdvancedOptions o : AdvancedOptions.values()) { + Property p = getConfigSetting(ReplayMod.instance.config, o.name(), o.getValue(), "advanced", true); + o.setValue(getValueObject(p)); + } - public enum ReplayOptions implements ValueEnum { - linear(false), lighting(false), useResources(true); + config.save(); + } - private Object value; + public String getRecordingPath() { + return (String) AdvancedOptions.recordingPath.getValue(); + } - public Object getValue() { - return value; - } + public String getRenderPath() { + return (String) AdvancedOptions.renderPath.getValue(); + } - public void setValue(Object value) { - this.value = value; - } + public int getVideoFramerate() { + return (Integer) RenderOptions.videoFramerate.getValue(); + } - ReplayOptions(Object value) { - this.value = value; - } - } + public void setVideoFramerate(int framerate) { + RenderOptions.videoFramerate.setValue(Math.min(120, Math.max(10, framerate))); + rewriteSettings(); + } - public enum RenderOptions implements ValueEnum { - videoQuality(0.5f), videoFramerate(30), waitForChunks(true); + public double getVideoQuality() { + return (Double) RenderOptions.videoQuality.getValue(); + } - private Object value; + public void setVideoQuality(double videoQuality) { + RenderOptions.videoQuality.setValue(Math.min(0.9f, Math.max(0.1f, videoQuality))); + rewriteSettings(); + } - public Object getValue() { - return value; - } + public void setEnableIndicator(boolean enable) { + RecordingOptions.indicator.setValue(enable); + rewriteSettings(); + } - public void setValue(Object value) { - this.value = value; - } + public boolean showRecordingIndicator() { + return (Boolean) RecordingOptions.indicator.getValue(); + } - RenderOptions(Object value) { - this.value = value; - } - } + public boolean isEnableRecordingServer() { + return (Boolean) RecordingOptions.recordServer.getValue(); + } - public enum AdvancedOptions implements ValueEnum { - recordingPath("./replay_recordings/"), renderPath("./replay_videos/"); + public void setEnableRecordingServer(boolean enableRecordingServer) { + RecordingOptions.recordServer.setValue(enableRecordingServer); + rewriteSettings(); + } - private Object value; + public boolean isEnableRecordingSingleplayer() { + return (Boolean) RecordingOptions.recordSingleplayer.getValue(); + } - public Object getValue() { - return value; - } + public void setEnableRecordingSingleplayer(boolean enableRecordingSingleplayer) { + RecordingOptions.recordSingleplayer.setValue(enableRecordingSingleplayer); + rewriteSettings(); + } - public void setValue(Object value) { - this.value = value; - } + public boolean isShowNotifications() { + return (Boolean) RecordingOptions.notifications.getValue(); + } - AdvancedOptions(Object value) { - this.value = value; - } - } + public void setShowNotifications(boolean showNotifications) { + RecordingOptions.notifications.setValue(showNotifications); + rewriteSettings(); + } - public List getValueEnums() { - List enums = new ArrayList(); - enums.addAll(Arrays.asList(ReplayOptions.values())); - enums.addAll(Arrays.asList(RenderOptions.values())); - return enums; - } + public boolean isLinearMovement() { + return (Boolean) ReplayOptions.linear.getValue(); + } - public void readValues() { - Configuration config = ReplayMod.config; + public void setLinearMovement(boolean linear) { + ReplayOptions.linear.setValue(linear); + rewriteSettings(); + } - for(RecordingOptions o : RecordingOptions.values()) { - Property p = getConfigSetting(ReplayMod.instance.config, o.name(), o.getValue(), "recording", false); - o.setValue(getValueObject(p)); - } + public boolean isLightingEnabled() { + return (Boolean) ReplayOptions.lighting.getValue(); + } - for(ReplayOptions o : ReplayOptions.values()) { - Property p = getConfigSetting(ReplayMod.instance.config, o.name(), o.getValue(), "replay", false); - o.setValue(getValueObject(p)); - } + public void setLightingEnabled(boolean enabled) { + ReplayOptions.lighting.setValue(enabled); + LightingHandler.setLighting(enabled); + rewriteSettings(); + } - for(RenderOptions o : RenderOptions.values()) { - Property p = getConfigSetting(ReplayMod.instance.config, o.name(), o.getValue(), "render", false); - o.setValue(getValueObject(p)); - } + public boolean getUseResourcePacks() { + return (Boolean) ReplayOptions.useResources.getValue(); + } - for(AdvancedOptions o : AdvancedOptions.values()) { - Property p = getConfigSetting(ReplayMod.instance.config, o.name(), o.getValue(), "advanced", true); - o.setValue(getValueObject(p)); - } + public void setUseResourcePacks(boolean use) { + ReplayOptions.useResources.setValue(use); + rewriteSettings(); + } - config.save(); - } + public boolean getWaitForChunks() { + return (Boolean) RenderOptions.waitForChunks.getValue(); + } - public String getRecordingPath() { - return (String)AdvancedOptions.recordingPath.getValue(); - } - public String getRenderPath() { - return (String)AdvancedOptions.renderPath.getValue(); - } + public void setWaitForChunks(boolean wait) { + RenderOptions.waitForChunks.setValue(wait); + rewriteSettings(); + } - public int getVideoFramerate() { - return (Integer)RenderOptions.videoFramerate.getValue(); - } - public void setVideoFramerate(int framerate) { - RenderOptions.videoFramerate.setValue(Math.min(120, Math.max(10, framerate))); - rewriteSettings(); - } - public double getVideoQuality() { - return (Double)RenderOptions.videoQuality.getValue(); - } - public void setEnableIndicator(boolean enable) { - RecordingOptions.indicator.setValue(enable); - rewriteSettings(); - } - public boolean showRecordingIndicator() { - return (Boolean)RecordingOptions.indicator.getValue(); - } - public void setVideoQuality(double videoQuality) { - RenderOptions.videoQuality.setValue(Math.min(0.9f, Math.max(0.1f, videoQuality))); - rewriteSettings(); - } - public boolean isEnableRecordingServer() { - return (Boolean)RecordingOptions.recordServer.getValue(); - } - public void setEnableRecordingServer(boolean enableRecordingServer) { - RecordingOptions.recordServer.setValue(enableRecordingServer); - rewriteSettings(); - } - public boolean isEnableRecordingSingleplayer() { - return (Boolean)RecordingOptions.recordSingleplayer.getValue(); - } - public void setEnableRecordingSingleplayer(boolean enableRecordingSingleplayer) { - RecordingOptions.recordSingleplayer.setValue(enableRecordingSingleplayer); - rewriteSettings(); - } - public boolean isShowNotifications() { - return (Boolean)RecordingOptions.notifications.getValue(); - } - public void setShowNotifications(boolean showNotifications) { - RecordingOptions.notifications.setValue(showNotifications); - rewriteSettings(); - } - public boolean isLinearMovement() { - return (Boolean)ReplayOptions.linear.getValue(); - } - public void setLinearMovement(boolean linear) { - ReplayOptions.linear.setValue(linear); - rewriteSettings(); - } - public boolean isLightingEnabled() { - return (Boolean)ReplayOptions.lighting.getValue(); - } - public void setUseResourcePacks(boolean use) { - ReplayOptions.useResources.setValue(use); - rewriteSettings(); - } - public boolean getUseResourcePacks() { - return (Boolean)ReplayOptions.useResources.getValue(); - } - public void setWaitForChunks(boolean wait) { - RenderOptions.waitForChunks.setValue(wait); - rewriteSettings(); - } - public boolean getWaitForChunks() { - return (Boolean)RenderOptions.waitForChunks.getValue(); - } + public void rewriteSettings() { + ReplayMod.instance.config.load(); - public void setLightingEnabled(boolean enabled) { - ReplayOptions.lighting.setValue(enabled); - LightingHandler.setLighting(enabled); - rewriteSettings(); - } + for(String cat : ReplayMod.instance.config.getCategoryNames()) { + ReplayMod.instance.config.removeCategory(ReplayMod.instance.config.getCategory(cat)); + } - public void rewriteSettings() { - ReplayMod.instance.config.load(); + for(RecordingOptions o : RecordingOptions.values()) { + getConfigSetting(ReplayMod.instance.config, o.name(), o.getValue(), "recording", false); + } - for(String cat : ReplayMod.instance.config.getCategoryNames()) { - ReplayMod.instance.config.removeCategory(ReplayMod.instance.config.getCategory(cat)); - } - - for(RecordingOptions o : RecordingOptions.values()) { - getConfigSetting(ReplayMod.instance.config, o.name(), o.getValue(), "recording", false); - } + for(ReplayOptions o : ReplayOptions.values()) { + getConfigSetting(ReplayMod.instance.config, o.name(), o.getValue(), "replay", false); + } - for(ReplayOptions o : ReplayOptions.values()) { - getConfigSetting(ReplayMod.instance.config, o.name(), o.getValue(), "replay", false); - } + for(RenderOptions o : RenderOptions.values()) { + getConfigSetting(ReplayMod.instance.config, o.name(), o.getValue(), "render", false); + } - for(RenderOptions o : RenderOptions.values()) { - getConfigSetting(ReplayMod.instance.config, o.name(), o.getValue(), "render", false); - } - - for(AdvancedOptions o : AdvancedOptions.values()) { - getConfigSetting(ReplayMod.instance.config, o.name(), o.getValue(), "advanced", false); - } + for(AdvancedOptions o : AdvancedOptions.values()) { + getConfigSetting(ReplayMod.instance.config, o.name(), o.getValue(), "advanced", false); + } - ReplayMod.instance.config.save(); - } + ReplayMod.instance.config.save(); + } - private Property getConfigSetting(Configuration config, String name, Object value, String category, boolean warning) { - if(warning) { - String warningMsg = "Please be careful when modifying this setting, as setting it to an invalid value might harm your computer."; - if(value instanceof Integer) { - return config.get(category, name, (Integer)value, warningMsg); - } else if(value instanceof Boolean) { - return config.get(category, name, (Boolean)value, warningMsg); - } else if(value instanceof Double) { - return config.get(category, name, (Double)value, warningMsg); - } else if(value instanceof Float) { - return config.get(category, name, (double)(Float)value, warningMsg); - } else if(value instanceof String) { - return config.get(category, name, (String)value, warningMsg); - } - } else { - if(value instanceof Integer) { - return config.get(category, name, (Integer)value); - } else if(value instanceof Boolean) { - return config.get(category, name, (Boolean)value); - } else if(value instanceof Double) { - return config.get(category, name, (Double)value); - } else if(value instanceof Float) { - return config.get(category, name, (double)(Float)value); - } else if(value instanceof String) { - return config.get(category, name, (String)value); - } - } - return null; - } - private Object getValueObject(Property p) { - if(p.isIntValue()) { - return p.getInt(); - } else if(p.isDoubleValue()) { - return p.getDouble(); - } else if(p.isBooleanValue()) { - return p.getBoolean(); - } else { - return p.getString(); - } - } + private Property getConfigSetting(Configuration config, String name, Object value, String category, boolean warning) { + if(warning) { + String warningMsg = "Please be careful when modifying this setting, as setting it to an invalid value might harm your computer."; + if(value instanceof Integer) { + return config.get(category, name, (Integer) value, warningMsg); + } else if(value instanceof Boolean) { + return config.get(category, name, (Boolean) value, warningMsg); + } else if(value instanceof Double) { + return config.get(category, name, (Double) value, warningMsg); + } else if(value instanceof Float) { + return config.get(category, name, (double) (Float) value, warningMsg); + } else if(value instanceof String) { + return config.get(category, name, (String) value, warningMsg); + } + } else { + if(value instanceof Integer) { + return config.get(category, name, (Integer) value); + } else if(value instanceof Boolean) { + return config.get(category, name, (Boolean) value); + } else if(value instanceof Double) { + return config.get(category, name, (Double) value); + } else if(value instanceof Float) { + return config.get(category, name, (double) (Float) value); + } else if(value instanceof String) { + return config.get(category, name, (String) value); + } + } + return null; + } + + private Object getValueObject(Property p) { + if(p.isIntValue()) { + return p.getInt(); + } else if(p.isDoubleValue()) { + return p.getDouble(); + } else if(p.isBooleanValue()) { + return p.getBoolean(); + } else { + return p.getString(); + } + } + + public enum RecordingOptions implements ValueEnum { + recordServer(true), recordSingleplayer(true), notifications(true), indicator(true); + + private Object value; + + RecordingOptions(Object value) { + this.value = value; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + } + + public enum ReplayOptions implements ValueEnum { + linear(false), lighting(false), useResources(true); + + private Object value; + + ReplayOptions(Object value) { + this.value = value; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + } + + public enum RenderOptions implements ValueEnum { + videoQuality(0.5f), videoFramerate(30), waitForChunks(true); + + private Object value; + + RenderOptions(Object value) { + this.value = value; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + } + + public enum AdvancedOptions implements ValueEnum { + recordingPath("./replay_recordings/"), renderPath("./replay_videos/"); + + private Object value; + + AdvancedOptions(Object value) { + this.value = value; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + } + + public static interface ValueEnum { + public Object getValue(); + + public void setValue(Object value); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/studio/StudioImplementation.java b/src/main/java/eu/crushedpixel/replaymod/studio/StudioImplementation.java index 3146011a..a1f2bed4 100755 --- a/src/main/java/eu/crushedpixel/replaymod/studio/StudioImplementation.java +++ b/src/main/java/eu/crushedpixel/replaymod/studio/StudioImplementation.java @@ -1,13 +1,6 @@ package eu.crushedpixel.replaymod.studio; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.List; - import com.google.gson.JsonObject; - import de.johni0702.replaystudio.PacketData; import de.johni0702.replaystudio.filter.ChangeTimestampFilter; import de.johni0702.replaystudio.filter.RemoveFilter; @@ -18,48 +11,55 @@ import de.johni0702.replaystudio.studio.ReplayStudio; import eu.crushedpixel.replaymod.recording.ReplayMetaData; import eu.crushedpixel.replaymod.utils.ReplayFileIO; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.List; + public class StudioImplementation { - - public static void trimReplay(File replayFile, boolean isTmcpr, int beginning, int ending, File outputFile) throws IOException { - ReplayStudio studio = new ReplayStudio(); - studio.setWrappingEnabled(false); + + public static void trimReplay(File replayFile, boolean isTmcpr, int beginning, int ending, File outputFile) throws IOException { + ReplayStudio studio = new ReplayStudio(); + studio.setWrappingEnabled(false); PacketStream stream = studio.createReplayStream(new FileInputStream(replayFile), isTmcpr); stream.addFilter(new SquashFilter(), -1, beginning); stream.addFilter(new RemoveFilter(), ending, -1); - + ChangeTimestampFilter ctf = new ChangeTimestampFilter(); JsonObject cfg = new JsonObject(); cfg.addProperty("offset", -beginning); ctf.init(studio, cfg); - + stream.addFilter(ctf, beginning, ending); - + File temp = File.createTempFile("trimmed", "tmcpr"); temp.deleteOnExit(); - + FileOutputStream fos = new FileOutputStream(temp); ReplayOutputStream out = new ReplayOutputStream(studio, fos); PacketData packetData; - + while((packetData = stream.next()) != null) { out.write(packetData); } for(PacketData data : stream.end()) { out.write(data); } - + out.close(); - + ReplayMetaData metaData = ReplayFileIO.getMetaData(replayFile); ending = Math.min(metaData.getDuration(), ending); - metaData.setDuration(ending-beginning); - + metaData.setDuration(ending - beginning); + outputFile.createNewFile(); - + ReplayFileIO.writeReplayFile(outputFile, temp, metaData); - } - - public static void connectReplayFiles(List filesToConnect, File outputFile) { - - } + } + + //TODO Work with Johni to connect multiple Replay Files + public static void connectReplayFiles(List filesToConnect, File outputFile) { + + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/studio/VersionValidator.java b/src/main/java/eu/crushedpixel/replaymod/studio/VersionValidator.java index e9c3ceda..1786c6f4 100755 --- a/src/main/java/eu/crushedpixel/replaymod/studio/VersionValidator.java +++ b/src/main/java/eu/crushedpixel/replaymod/studio/VersionValidator.java @@ -2,19 +2,19 @@ package eu.crushedpixel.replaymod.studio; public class VersionValidator { - public static final boolean isValid; - - static { - String version = Runtime.class.getPackage().getSpecificationVersion(); - if(version != null) { - String[] split = version.split("\\."); - if(split.length > 1) { - isValid = Integer.valueOf(split[1]) >= 7; - } else { - isValid = false; - } - } else { - isValid = false; - } - } + public static final boolean isValid; + + static { + String version = Runtime.class.getPackage().getSpecificationVersion(); + if(version != null) { + String[] split = version.split("\\."); + if(split.length > 1) { + isValid = Integer.valueOf(split[1]) >= 7; + } else { + isValid = false; + } + } else { + isValid = false; + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/timer/EnchantmentTimer.java b/src/main/java/eu/crushedpixel/replaymod/timer/EnchantmentTimer.java index 8f5ea4b0..27857e62 100755 --- a/src/main/java/eu/crushedpixel/replaymod/timer/EnchantmentTimer.java +++ b/src/main/java/eu/crushedpixel/replaymod/timer/EnchantmentTimer.java @@ -1,35 +1,36 @@ package eu.crushedpixel.replaymod.timer; +import eu.crushedpixel.replaymod.ReplayMod; import eu.crushedpixel.replaymod.replay.ReplayHandler; import eu.crushedpixel.replaymod.replay.ReplayProcess; public class EnchantmentTimer { - private static long lastRealTime = System.currentTimeMillis(); - private static long lastFakeTime = System.currentTimeMillis(); - - private static long recordingTime = 0; - - public static void resetRecordingTime() { - recordingTime = 0; - } - - public static void increaseRecordingTime(long amount) { - recordingTime += amount; - } - - public static long getEnchantmentTime() { - if(!(ReplayHandler.isInPath() && ReplayProcess.isVideoRecording())) { - if(ReplayHandler.isInReplay()) { - long timeDiff = System.currentTimeMillis() - lastRealTime; - double toAdd = timeDiff*ReplayHandler.getSpeed(); - lastFakeTime = Math.round(lastFakeTime+toAdd); - lastRealTime = System.currentTimeMillis(); - return lastFakeTime; - } - lastFakeTime = lastRealTime = System.currentTimeMillis(); - return lastRealTime; - } - return recordingTime; - } + private static long lastRealTime = System.currentTimeMillis(); + private static long lastFakeTime = System.currentTimeMillis(); + + private static long recordingTime = 0; + + public static void resetRecordingTime() { + recordingTime = 0; + } + + public static void increaseRecordingTime(long amount) { + recordingTime += amount; + } + + public static long getEnchantmentTime() { + if(!(ReplayHandler.isInPath() && ReplayProcess.isVideoRecording())) { + if(ReplayHandler.isInReplay()) { + long timeDiff = System.currentTimeMillis() - lastRealTime; + double toAdd = timeDiff * ReplayMod.replaySender.getReplaySpeed(); + lastFakeTime = Math.round(lastFakeTime + toAdd); + lastRealTime = System.currentTimeMillis(); + return lastFakeTime; + } + lastFakeTime = lastRealTime = System.currentTimeMillis(); + return lastRealTime; + } + return recordingTime; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/timer/MCTimerHandler.java b/src/main/java/eu/crushedpixel/replaymod/timer/MCTimerHandler.java index d0034284..9a08ff74 100755 --- a/src/main/java/eu/crushedpixel/replaymod/timer/MCTimerHandler.java +++ b/src/main/java/eu/crushedpixel/replaymod/timer/MCTimerHandler.java @@ -1,175 +1,172 @@ package eu.crushedpixel.replaymod.timer; +import eu.crushedpixel.replaymod.reflection.MCPNames; +import eu.crushedpixel.replaymod.video.ReplayTimer; +import net.minecraft.client.Minecraft; +import net.minecraft.util.Timer; + import java.lang.reflect.Field; -import net.minecraft.client.Minecraft; -import net.minecraft.util.MathHelper; -import net.minecraft.util.Timer; -import eu.crushedpixel.replaymod.reflection.MCPNames; -import eu.crushedpixel.replaymod.replay.ReplayHandler; -import eu.crushedpixel.replaymod.video.ReplayTimer; - public class MCTimerHandler { - private static Field mcTimer; - private static Minecraft mc = Minecraft.getMinecraft(); + private static Field mcTimer; + private static Minecraft mc = Minecraft.getMinecraft(); - private static ReplayTimer rpt = new ReplayTimer(20); - private static Timer timerBefore; + private static ReplayTimer rpt = new ReplayTimer(20); + private static Timer timerBefore; - static { - try { - mcTimer = Minecraft.class.getDeclaredField(MCPNames.field("field_71428_T")); - mcTimer.setAccessible(true); - } catch(Exception e) { - e.printStackTrace(); - } - } + static { + try { + mcTimer = Minecraft.class.getDeclaredField(MCPNames.field("field_71428_T")); + mcTimer.setAccessible(true); + } catch(Exception e) { + e.printStackTrace(); + } + } - public static void setActiveTimer() { - try { - if(timerBefore != null) { - mcTimer.set(mc, timerBefore); - } - } catch(Exception e) { - e.printStackTrace(); - } - } + public static void setActiveTimer() { + try { + if(timerBefore != null) { + mcTimer.set(mc, timerBefore); + } + } catch(Exception e) { + e.printStackTrace(); + } + } - public static void setPassiveTimer() { - try { - if(!(getTimer() instanceof ReplayTimer)) { - timerBefore = getTimer(); - mcTimer.set(mc, rpt); - } - } catch(Exception e) { - e.printStackTrace(); - } - } + public static void setPassiveTimer() { + try { + if(!(getTimer() instanceof ReplayTimer)) { + timerBefore = getTimer(); + mcTimer.set(mc, rpt); + } + } catch(Exception e) { + e.printStackTrace(); + } + } - public static int getTicks() { - try { - Timer t = getTimer(); - return t.elapsedTicks; - } catch(Exception e) { - e.printStackTrace(); - } - return 0; - } + public static int getTicks() { + try { + Timer t = getTimer(); + return t.elapsedTicks; + } catch(Exception e) { + e.printStackTrace(); + } + return 0; + } - public static float getPartialTicks() { - try { - Timer t = getTimer(); - return t.elapsedPartialTicks; - } catch(Exception e) { - e.printStackTrace(); - } - return 0; - } + public static void setTicks(int ticks) { + try { + getTimer().elapsedTicks = ticks; + } catch(Exception e) { + e.printStackTrace(); + } + } - public static float getRenderTicks() { - try { - Timer t = getTimer(); - return t.renderPartialTicks; - } catch(Exception e) { - e.printStackTrace(); - } - return 0; - } + public static float getPartialTicks() { + try { + Timer t = getTimer(); + return t.elapsedPartialTicks; + } catch(Exception e) { + e.printStackTrace(); + } + return 0; + } - private static Timer getTimer() throws IllegalArgumentException, IllegalAccessException { - return (Timer)mcTimer.get(mc); - } + public static void setPartialTicks(float ticks) { + try { + getTimer().elapsedPartialTicks = ticks; + } catch(Exception e) { + e.printStackTrace(); + } + } - public static void advanceTicks(int ticks) { - try { - Timer t = getTimer(); - t.elapsedTicks += ticks; - } catch(Exception e) { - e.printStackTrace(); - } - } + public static float getRenderTicks() { + try { + Timer t = getTimer(); + return t.renderPartialTicks; + } catch(Exception e) { + e.printStackTrace(); + } + return 0; + } - public static void advancePartialTicks(float ticks) { - try { - Timer t = getTimer(); - t.elapsedPartialTicks += ticks; - } catch(Exception e) { - e.printStackTrace(); - } - } + private static Timer getTimer() throws IllegalArgumentException, IllegalAccessException { + return (Timer) mcTimer.get(mc); + } - public static void advanceRenderPartialTicks(float ticks) { - try { - Timer t = getTimer(); - t.renderPartialTicks += ticks; - } catch(Exception e) { - e.printStackTrace(); - } - } + public static void advanceTicks(int ticks) { + try { + Timer t = getTimer(); + t.elapsedTicks += ticks; + } catch(Exception e) { + e.printStackTrace(); + } + } - public static void setTimerSpeed(float speed) { - try { - Timer t = getTimer(); - t.timerSpeed = speed; - if(timerBefore != null) { - timerBefore.timerSpeed = speed; - } - } catch(Exception e) { - e.printStackTrace(); - } - } + public static void advancePartialTicks(float ticks) { + try { + Timer t = getTimer(); + t.elapsedPartialTicks += ticks; + } catch(Exception e) { + e.printStackTrace(); + } + } - public static void setRenderPartialTicks(float ticks) { - try { - getTimer().renderPartialTicks = ticks; - } catch(Exception e) { - e.printStackTrace(); - } - } + public static void advanceRenderPartialTicks(float ticks) { + try { + Timer t = getTimer(); + t.renderPartialTicks += ticks; + } catch(Exception e) { + e.printStackTrace(); + } + } - public static void setPartialTicks(float ticks) { - try { - getTimer().elapsedPartialTicks = ticks; - } catch(Exception e) { - e.printStackTrace(); - } - } + public static void setRenderPartialTicks(float ticks) { + try { + getTimer().renderPartialTicks = ticks; + } catch(Exception e) { + e.printStackTrace(); + } + } - public static void setTicks(int ticks) { - try { - getTimer().elapsedTicks = ticks; - } catch(Exception e) { - e.printStackTrace(); - } - } + public static float getTimerSpeed() { + try { + return getTimer().timerSpeed; + } catch(Exception e) { + e.printStackTrace(); + } + return 1; + } - public static float getTimerSpeed() { - try { - return getTimer().timerSpeed; - } catch(Exception e) { - e.printStackTrace(); - } - return 1; - } - - public static void updateTimer(double d) { - try { - Timer t = getTimer(); - double d2 = d; - //d2 = MathHelper.clamp_double(d2, 0.0D, 1.0D); - t.elapsedPartialTicks = (float)((double)t.elapsedPartialTicks + d2 * (double)t.timerSpeed * 20); - t.elapsedTicks = (int)t.elapsedPartialTicks; - t.elapsedPartialTicks -= (float)t.elapsedTicks; + public static void setTimerSpeed(float speed) { + try { + Timer t = getTimer(); + t.timerSpeed = speed; + if(timerBefore != null) { + timerBefore.timerSpeed = speed; + } + } catch(Exception e) { + e.printStackTrace(); + } + } - if (t.elapsedTicks > 10) - { - t.elapsedTicks = 10; - } + public static void updateTimer(double d) { + try { + Timer t = getTimer(); + double d2 = d; + //d2 = MathHelper.clamp_double(d2, 0.0D, 1.0D); + t.elapsedPartialTicks = (float) ((double) t.elapsedPartialTicks + d2 * (double) t.timerSpeed * 20); + t.elapsedTicks = (int) t.elapsedPartialTicks; + t.elapsedPartialTicks -= (float) t.elapsedTicks; - t.renderPartialTicks = t.elapsedPartialTicks; - } catch(Exception e) { - e.printStackTrace(); - } - } + if(t.elapsedTicks > 10) { + t.elapsedTicks = 10; + } + + t.renderPartialTicks = t.elapsedPartialTicks; + } catch(Exception e) { + e.printStackTrace(); + } + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/utils/ImageUtils.java b/src/main/java/eu/crushedpixel/replaymod/utils/ImageUtils.java index f171e390..a7ad650d 100755 --- a/src/main/java/eu/crushedpixel/replaymod/utils/ImageUtils.java +++ b/src/main/java/eu/crushedpixel/replaymod/utils/ImageUtils.java @@ -1,69 +1,73 @@ package eu.crushedpixel.replaymod.utils; -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.RenderingHints; +import java.awt.*; import java.awt.image.BufferedImage; public class ImageUtils { - public static BufferedImage scaleImage(BufferedImage img, Dimension d) { - img = scaleByHalf(img, d); - img = scaleExact(img, d); - return img; - } + public static BufferedImage scaleImage(BufferedImage img, Dimension d) { + img = scaleByHalf(img, d); + img = scaleExact(img, d); + return img; + } - private static BufferedImage scaleByHalf(BufferedImage img, Dimension d) { - int w = img.getWidth(); - int h = img.getHeight(); - float factor = getBinFactor(w, h, d); + private static BufferedImage scaleByHalf(BufferedImage img, Dimension d) { + int w = img.getWidth(); + int h = img.getHeight(); + float factor = getBinFactor(w, h, d); - // make new size - w *= factor; - h *= factor; - BufferedImage scaled = new BufferedImage(w, h, - BufferedImage.TYPE_INT_RGB); - Graphics2D g = scaled.createGraphics(); - g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, - RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); - g.drawImage(img, 0, 0, w, h, null); - g.dispose(); - return scaled; - } + // make new size + w *= factor; + h *= factor; + BufferedImage scaled = new BufferedImage(w, h, + BufferedImage.TYPE_INT_RGB); + Graphics2D g = scaled.createGraphics(); + g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, + RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); + g.drawImage(img, 0, 0, w, h, null); + g.dispose(); + return scaled; + } - private static BufferedImage scaleExact(BufferedImage img, Dimension d) { - float factor = getFactor(img.getWidth(), img.getHeight(), d); + private static BufferedImage scaleExact(BufferedImage img, Dimension d) { + float factor = getFactor(img.getWidth(), img.getHeight(), d); - // create the image - int w = (int) (img.getWidth() * factor); - int h = (int) (img.getHeight() * factor); - BufferedImage scaled = new BufferedImage(w, h, - BufferedImage.TYPE_INT_RGB); + // create the image + int w = (int) (img.getWidth() * factor); + int h = (int) (img.getHeight() * factor); + BufferedImage scaled = new BufferedImage(w, h, + BufferedImage.TYPE_INT_RGB); - Graphics2D g = scaled.createGraphics(); - g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, - RenderingHints.VALUE_INTERPOLATION_BILINEAR); - g.drawImage(img, 0, 0, w, h, null); - g.dispose(); - return scaled; - } + Graphics2D g = scaled.createGraphics(); + g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, + RenderingHints.VALUE_INTERPOLATION_BILINEAR); + g.drawImage(img, 0, 0, w, h, null); + g.dispose(); + return scaled; + } - static float getBinFactor(int width, int height, Dimension dim) { - float factor = 1; - float target = getFactor(width, height, dim); - if (target <= 1) { while (factor / 2 > target) { factor /= 2; } - } else { while (factor * 2 < target) { factor *= 2; } } - return factor; - } + static float getBinFactor(int width, int height, Dimension dim) { + float factor = 1; + float target = getFactor(width, height, dim); + if(target <= 1) { + while(factor / 2 > target) { + factor /= 2; + } + } else { + while(factor * 2 < target) { + factor *= 2; + } + } + return factor; + } - static float getFactor(int width, int height, Dimension dim) { - float sx = dim.width / (float) width; - float sy = dim.height / (float) height; - return Math.min(sx, sy); - } + static float getFactor(int width, int height, Dimension dim) { + float sx = dim.width / (float) width; + float sy = dim.height / (float) height; + return Math.min(sx, sy); + } - public static BufferedImage cropImage(BufferedImage src, Rectangle rect) { - return src.getSubimage(rect.x, rect.y, rect.width, rect.height); - } + public static BufferedImage cropImage(BufferedImage src, Rectangle rect) { + return src.getSubimage(rect.x, rect.y, rect.width, rect.height); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/utils/MouseUtils.java b/src/main/java/eu/crushedpixel/replaymod/utils/MouseUtils.java index 6e23768c..0210b9b6 100755 --- a/src/main/java/eu/crushedpixel/replaymod/utils/MouseUtils.java +++ b/src/main/java/eu/crushedpixel/replaymod/utils/MouseUtils.java @@ -1,32 +1,31 @@ package eu.crushedpixel.replaymod.utils; -import java.awt.Point; - import net.minecraft.client.Minecraft; import net.minecraft.client.gui.ScaledResolution; - import org.lwjgl.input.Mouse; +import java.awt.*; + public class MouseUtils { - private static final Minecraft mc = Minecraft.getMinecraft(); - - public static Point getMousePos() { - Point scaled = getScaledDimensions(); - int width = (int)scaled.getX(); - int height = (int)scaled.getY(); + private static final Minecraft mc = Minecraft.getMinecraft(); - final int mouseX = (Mouse.getX() * width / mc.displayWidth); - final int mouseY = (height - Mouse.getY() * height / mc.displayHeight); - - return new Point(mouseX, mouseY); - } - - public static Point getScaledDimensions() { - ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); - final int width = sr.getScaledWidth(); - final int heigth = sr.getScaledHeight(); - - return new Point(width, heigth); - } + public static Point getMousePos() { + Point scaled = getScaledDimensions(); + int width = (int) scaled.getX(); + int height = (int) scaled.getY(); + + final int mouseX = (Mouse.getX() * width / mc.displayWidth); + final int mouseY = (height - Mouse.getY() * height / mc.displayHeight); + + return new Point(mouseX, mouseY); + } + + public static Point getScaledDimensions() { + ScaledResolution sr = new ScaledResolution(mc, mc.displayWidth, mc.displayHeight); + final int width = sr.getScaledWidth(); + final int heigth = sr.getScaledHeight(); + + return new Point(width, heigth); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/utils/ReplayFileIO.java b/src/main/java/eu/crushedpixel/replaymod/utils/ReplayFileIO.java index 2ed8474c..5ebec2bf 100755 --- a/src/main/java/eu/crushedpixel/replaymod/utils/ReplayFileIO.java +++ b/src/main/java/eu/crushedpixel/replaymod/utils/ReplayFileIO.java @@ -7,7 +7,6 @@ import eu.crushedpixel.replaymod.holders.PacketData; import eu.crushedpixel.replaymod.recording.ConnectionEventHandler; import eu.crushedpixel.replaymod.recording.PacketSerializer; import eu.crushedpixel.replaymod.recording.ReplayMetaData; -import eu.crushedpixel.replaymod.replay.PacketDeserializer; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.minecraft.network.EnumConnectionState; @@ -21,9 +20,6 @@ import org.apache.commons.compress.archivers.zip.ZipFile; import org.apache.commons.io.FilenameUtils; import java.io.*; -import java.nio.file.CopyOption; -import java.nio.file.Files; -import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -34,329 +30,328 @@ import java.util.zip.ZipOutputStream; @SuppressWarnings("resource") //Gets handled by finalizer public class ReplayFileIO { - public static File getRenderFolder() { - File folder = new File(ReplayMod.replaySettings.getRenderPath()); - folder.mkdirs(); - return folder; - } + private static final PacketSerializer packetSerializer = new PacketSerializer(EnumPacketDirection.CLIENTBOUND); + private static final byte[] uniqueBytes = new byte[]{0, 1, 1, 2, 3, 5, 8}; + private static File lastReplayFile = null; + private static boolean lastContainsJoinPacket = false; - public static File getReplayFolder() { - String path = ReplayMod.replaySettings.getRecordingPath(); - File folder = new File(path); - folder.mkdirs(); - return folder; - } + public static File getRenderFolder() { + File folder = new File(ReplayMod.replaySettings.getRenderPath()); + folder.mkdirs(); + return folder; + } - public static List getAllReplayFiles() { - List files = new ArrayList(); - File folder = getReplayFolder(); - for(File file : folder.listFiles()) { - if(("."+FilenameUtils.getExtension(file.getAbsolutePath())).equals( - ConnectionEventHandler.ZIP_FILE_EXTENSION)) { - files.add(file); - } - } - return files; - } + public static File getReplayFolder() { + String path = ReplayMod.replaySettings.getRecordingPath(); + File folder = new File(path); + folder.mkdirs(); + return folder; + } - private static DataInputStream getMetaDataInputStream(File replayFile) throws IOException { - ZipFile archive = null; + public static List getAllReplayFiles() { + List files = new ArrayList(); + File folder = getReplayFolder(); + for(File file : folder.listFiles()) { + if(("." + FilenameUtils.getExtension(file.getAbsolutePath())).equals( + ConnectionEventHandler.ZIP_FILE_EXTENSION)) { + files.add(file); + } + } + return files; + } - try { - archive = new ZipFile(replayFile); - ZipArchiveEntry tmcpr = archive.getEntry("metaData"+ - ConnectionEventHandler.JSON_FILE_EXTENSION); + private static DataInputStream getMetaDataInputStream(File replayFile) throws IOException { + ZipFile archive = null; - return new DataInputStream(archive.getInputStream(tmcpr)); - } catch(IOException e) { - throw e; - } - } + try { + archive = new ZipFile(replayFile); + ZipArchiveEntry tmcpr = archive.getEntry("metaData" + + ConnectionEventHandler.JSON_FILE_EXTENSION); - public static void writeReplayFile(File replayFile, File tempFile, ReplayMetaData metaData) throws IOException { - byte[] buffer = new byte[1024]; + return new DataInputStream(archive.getInputStream(tmcpr)); + } catch(IOException e) { + throw e; + } + } - if(!replayFile.exists()) { - replayFile.createNewFile(); - } + public static void writeReplayFile(File replayFile, File tempFile, ReplayMetaData metaData) throws IOException { + byte[] buffer = new byte[1024]; - FileOutputStream fos = new FileOutputStream(replayFile); - ZipOutputStream zos = new ZipOutputStream(fos); + if(!replayFile.exists()) { + replayFile.createNewFile(); + } - String json = new Gson().toJson(metaData); + FileOutputStream fos = new FileOutputStream(replayFile); + ZipOutputStream zos = new ZipOutputStream(fos); - zos.putNextEntry(new ZipEntry("metaData.json")); - PrintWriter pw = new PrintWriter(zos); - pw.write(json); - pw.flush(); - zos.closeEntry(); + String json = new Gson().toJson(metaData); - zos.putNextEntry(new ZipEntry("recording"+ConnectionEventHandler.TEMP_FILE_EXTENSION)); - FileInputStream fis = new FileInputStream(tempFile); - int len; - while((len = fis.read(buffer)) > 0) { - zos.write(buffer, 0, len); - } + zos.putNextEntry(new ZipEntry("metaData.json")); + PrintWriter pw = new PrintWriter(zos); + pw.write(json); + pw.flush(); + zos.closeEntry(); - fis.close(); - zos.closeEntry(); + zos.putNextEntry(new ZipEntry("recording" + ConnectionEventHandler.TEMP_FILE_EXTENSION)); + FileInputStream fis = new FileInputStream(tempFile); + int len; + while((len = fis.read(buffer)) > 0) { + zos.write(buffer, 0, len); + } - zos.close(); - } + fis.close(); + zos.closeEntry(); - private static Pair getTempFileInputStream(File replayFile) throws Exception { - ZipFile archive = null; + zos.close(); + } - try { - archive = new ZipFile(replayFile); - ZipArchiveEntry tmcpr = archive.getEntry("recording"+ - ConnectionEventHandler.TEMP_FILE_EXTENSION); - long size = tmcpr.getSize(); + private static Pair getTempFileInputStream(File replayFile) throws Exception { + ZipFile archive = null; - return new Pair(size, new DataInputStream(archive.getInputStream(tmcpr))); - } catch(Exception e) { - throw e; - } - } + try { + archive = new ZipFile(replayFile); + ZipArchiveEntry tmcpr = archive.getEntry("recording" + + ConnectionEventHandler.TEMP_FILE_EXTENSION); + long size = tmcpr.getSize(); - public static ReplayMetaData getMetaData(File replayFile) throws IOException { - BufferedReader br = new BufferedReader(new InputStreamReader(getMetaDataInputStream(replayFile))); - String json = br.readLine(); + return new Pair(size, new DataInputStream(archive.getInputStream(tmcpr))); + } catch(Exception e) { + throw e; + } + } - return new Gson().fromJson(json, ReplayMetaData.class); - } + public static ReplayMetaData getMetaData(File replayFile) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(getMetaDataInputStream(replayFile))); + String json = br.readLine(); - /** - * @param replayFile - * @return Whether the given Replay File contains a {@link S01PacketJoinGame}. - */ - public static boolean containsJoinPacket(File replayFile) { - DataInputStream dis = null; - if(replayFile == lastReplayFile) { - return lastContainsJoinPacket; - } + return new Gson().fromJson(json, ReplayMetaData.class); + } - lastReplayFile = replayFile; - lastContainsJoinPacket = false; - try { - Pair pair = getTempFileInputStream(replayFile); - dis = pair.second(); - PacketData pd = readPacketData(dis); - while(dis.available() > 0) { - Packet p = deserializePacket(pd.getByteArray()); - if(p instanceof S01PacketJoinGame) { - lastContainsJoinPacket = true; - return lastContainsJoinPacket; - } if(p instanceof S08PacketPlayerPosLook) { - lastContainsJoinPacket = false; - return lastContainsJoinPacket; - } - } - } catch(Exception e) { - e.printStackTrace(); - } finally { - try { - if(dis != null) { - dis.close(); - } - } catch(Exception e) {} - } + /** + * @param replayFile + * @return Whether the given Replay File contains a {@link S01PacketJoinGame}. + */ + public static boolean containsJoinPacket(File replayFile) { + DataInputStream dis = null; + if(replayFile == lastReplayFile) { + return lastContainsJoinPacket; + } - return false; - } + lastReplayFile = replayFile; + lastContainsJoinPacket = false; + try { + Pair pair = getTempFileInputStream(replayFile); + dis = pair.second(); + PacketData pd = readPacketData(dis); + while(dis.available() > 0) { + Packet p = deserializePacket(pd.getByteArray()); + if(p instanceof S01PacketJoinGame) { + lastContainsJoinPacket = true; + return lastContainsJoinPacket; + } + if(p instanceof S08PacketPlayerPosLook) { + lastContainsJoinPacket = false; + return lastContainsJoinPacket; + } + } + } catch(Exception e) { + e.printStackTrace(); + } finally { + try { + if(dis != null) { + dis.close(); + } + } catch(Exception e) { + } + } - public static PacketData readPacketData(DataInputStream dis) throws IOException { - int timestamp = dis.readInt(); - int bytes = dis.readInt(); - byte[] bb = new byte[bytes]; - dis.readFully(bb); + return false; + } - return new PacketData(bb, timestamp); - } + public static PacketData readPacketData(DataInputStream dis) throws IOException { + int timestamp = dis.readInt(); + int bytes = dis.readInt(); + byte[] bb = new byte[bytes]; + dis.readFully(bb); - public static Packet deserializePacket(byte[] bytes) throws InstantiationException, IllegalAccessException, IOException { - try { - ByteBuf bb = Unpooled.wrappedBuffer(bytes); - PacketBuffer pb = new PacketBuffer(bb); + return new PacketData(bb, timestamp); + } - int i = pb.readVarIntFromBuffer(); + public static Packet deserializePacket(byte[] bytes) throws InstantiationException, IllegalAccessException, IOException { + try { + ByteBuf bb = Unpooled.wrappedBuffer(bytes); + PacketBuffer pb = new PacketBuffer(bb); - Packet p = EnumConnectionState.PLAY.getPacket(EnumPacketDirection.CLIENTBOUND, i); - p.readPacketData(pb); + int i = pb.readVarIntFromBuffer(); - return p; - } catch(Exception e) { - return null; - } - } + Packet p = EnumConnectionState.PLAY.getPacket(EnumPacketDirection.CLIENTBOUND, i); + p.readPacketData(pb); - public static byte[] serializePacket(Packet packet) throws IOException { - ByteBuf bb = Unpooled.buffer(); - packetSerializer.encode(EnumConnectionState.PLAY, packet, bb); - bb.readerIndex(0); - byte[] array = new byte[bb.readableBytes()]; - bb.readBytes(array); + return p; + } catch(Exception e) { + return null; + } + } - bb.readerIndex(0); + public static byte[] serializePacket(Packet packet) throws IOException { + ByteBuf bb = Unpooled.buffer(); + packetSerializer.encode(EnumConnectionState.PLAY, packet, bb); + bb.readerIndex(0); + byte[] array = new byte[bb.readableBytes()]; + bb.readBytes(array); - return array; - } + bb.readerIndex(0); - public static void writePacket(PacketData pd, DataOutput out) throws IOException { - out.writeInt(pd.getTimestamp()); - out.writeInt(pd.getByteArray().length); - out.write(pd.getByteArray()); - } + return array; + } - public static int getWrittenByteSize(PacketData pd) { - return (2*4)+pd.getByteArray().length; - } + public static void writePacket(PacketData pd, DataOutput out) throws IOException { + out.writeInt(pd.getTimestamp()); + out.writeInt(pd.getByteArray().length); + out.write(pd.getByteArray()); + } - public static void writePackets(Collection p, DataOutput out) throws IOException { - for(PacketData pd : p) { - writePacket(pd, out); - } - } + public static int getWrittenByteSize(PacketData pd) { + return (2 * 4) + pd.getByteArray().length; + } - private static final PacketSerializer packetSerializer = new PacketSerializer(EnumPacketDirection.CLIENTBOUND); - private static final PacketDeserializer deserializer = new PacketDeserializer(EnumPacketDirection.SERVERBOUND); + public static void writePackets(Collection p, DataOutput out) throws IOException { + for(PacketData pd : p) { + writePacket(pd, out); + } + } - private static File lastReplayFile = null; - private static boolean lastContainsJoinPacket = false; + /** + * @param replayFile The File to reverse + * @param outputFile The File to save the reversed Packets in + * @param seekJoinPacket Whether a {@link S01PacketJoinGame} should be seeked in the Replay File. If containsJoinPacket is being + * called with the same File directly afterwards, this will reduce the amount of calculations. Only use if needed, + * because this consumes a significant amount of time! + * @param boundaries Two timestamps which make a boundary for excluded Packets + * @return Whether the action was successful + */ + public static boolean reversePackets(File replayFile, File outputFile, boolean seekJoinPacket, int... boundaries) { + lastReplayFile = replayFile; + lastContainsJoinPacket = false; - /** - * - * @param replayFile The File to reverse - * @param outputFile The File to save the reversed Packets in - * @param seekJoinPacket Whether a {@link S01PacketJoinGame} should be seeked in the Replay File. If containsJoinPacket is being - * called with the same File directly afterwards, this will reduce the amount of calculations. Only use if needed, - * because this consumes a significant amount of time! - * @param boundaries Two timestamps which make a boundary for excluded Packets - * @return Whether the action was successful - */ - public static boolean reversePackets(File replayFile, File outputFile, boolean seekJoinPacket, int... boundaries) { - lastReplayFile = replayFile; - lastContainsJoinPacket = false; + RandomAccessFile raf = null; + DataInputStream dis = null; - RandomAccessFile raf = null; - DataInputStream dis = null; + boolean bounds = false; + int lower = 0, upper = 0; + if(boundaries.length >= 2) { + if(boundaries[0] > boundaries[1]) { + upper = boundaries[0]; + lower = boundaries[1]; + } else { + upper = boundaries[1]; + lower = boundaries[0]; + } + } + try { + if(!outputFile.exists()) { + outputFile.createNewFile(); + } + raf = new RandomAccessFile(outputFile, "rw"); - boolean bounds = false; - int lower = 0, upper = 0; - if(boundaries.length >= 2) { - if(boundaries[0] > boundaries[1]) { - upper = boundaries[0]; - lower = boundaries[1]; - } else { - upper = boundaries[1]; - lower = boundaries[0]; - } - } - try { - if(!outputFile.exists()) { - outputFile.createNewFile(); - } - raf = new RandomAccessFile(outputFile, "rw"); + Pair pair = getTempFileInputStream(replayFile); + dis = pair.second(); + long fileLength = pair.first(); - Pair pair = getTempFileInputStream(replayFile); - dis = pair.second(); - long fileLength = pair.first(); + raf.setLength(fileLength); - raf.setLength(fileLength); + long pointerBefore = fileLength; - long pointerBefore = fileLength; + while(dis.available() > 0) { + try { + PacketData pd = readPacketData(dis); - while(dis.available() > 0) { - try { - PacketData pd = readPacketData(dis); + boolean write = true; + if(bounds) { + if(pd.getTimestamp() < lower || pd.getTimestamp() > upper) { + write = false; + } + } - boolean write = true; - if(bounds) { - if(pd.getTimestamp() < lower || pd.getTimestamp() > upper) { - write = false; - } - } + if(write) { + if(seekJoinPacket && !lastContainsJoinPacket) { + Packet p = deserializePacket(pd.getByteArray()); + if(p instanceof S01PacketJoinGame) lastContainsJoinPacket = true; + } + pointerBefore = pointerBefore - getWrittenByteSize(pd); + raf.seek(pointerBefore); + writePacket(pd, raf); + } + } catch(EOFException e) { + e.printStackTrace(); + break; + } + } + return true; + } catch(Exception e) { + e.printStackTrace(); + } finally { + try { + if(raf != null) { + raf.close(); + } + if(dis != null) { + dis.close(); + } + } catch(Exception e) { + } + } - if(write) { - if(seekJoinPacket && !lastContainsJoinPacket) { - Packet p = deserializePacket(pd.getByteArray()); - if(p instanceof S01PacketJoinGame) lastContainsJoinPacket = true; - } - pointerBefore = pointerBefore - getWrittenByteSize(pd); - raf.seek(pointerBefore); - writePacket(pd, raf); - } - } catch(EOFException e) { - e.printStackTrace(); - break; - } - } - return true; - } catch(Exception e) { - e.printStackTrace(); - } finally { - try { - if(raf != null) { - raf.close(); - } - if(dis != null) { - dis.close(); - } - } catch(Exception e) {} - } + return false; + } - return false; - } + public static void addThumbToZip(File zipFile, File thumb) throws IOException { + // get a temp file + File tempFile = File.createTempFile(zipFile.getName(), null, zipFile.getParentFile()); + // delete it, otherwise you cannot rename your existing zip to it. - private static final byte[] uniqueBytes = new byte[]{0,1,1,2,3,5,8}; + byte[] buf = new byte[1024]; - public static void addThumbToZip(File zipFile, File thumb) throws IOException { - // get a temp file - File tempFile = File.createTempFile(zipFile.getName(), null, zipFile.getParentFile()); - // delete it, otherwise you cannot rename your existing zip to it. + ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile)); + ZipOutputStream out = new ZipOutputStream(new FileOutputStream(tempFile)); - byte[] buf = new byte[1024]; + ZipEntry entry = zin.getNextEntry(); + while(entry != null) { + String name = entry.getName(); + boolean isThumb = name.contains("thumb"); + if(!isThumb) { + // Add ZIP entry to output stream. + out.putNextEntry(new ZipEntry(name)); + // Transfer bytes from the ZIP file to the output file + int len; + while((len = zin.read(buf)) > 0) { + out.write(buf, 0, len); + } + } + entry = zin.getNextEntry(); + } + // Close the streams + zin.close(); + // Compress the files - ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile)); - ZipOutputStream out = new ZipOutputStream(new FileOutputStream(tempFile)); + InputStream in = new FileInputStream(thumb); + // Add ZIP entry to output stream. + out.putNextEntry(new ZipEntry("thumb")); + // Transfer bytes from the file to the ZIP file + int len; - ZipEntry entry = zin.getNextEntry(); - while (entry != null) { - String name = entry.getName(); - boolean isThumb = name.contains("thumb"); - if (!isThumb) { - // Add ZIP entry to output stream. - out.putNextEntry(new ZipEntry(name)); - // Transfer bytes from the ZIP file to the output file - int len; - while ((len = zin.read(buf)) > 0) { - out.write(buf, 0, len); - } - } - entry = zin.getNextEntry(); - } - // Close the streams - zin.close(); - // Compress the files + out.write(uniqueBytes); - InputStream in = new FileInputStream(thumb); - // Add ZIP entry to output stream. - out.putNextEntry(new ZipEntry("thumb")); - // Transfer bytes from the file to the ZIP file - int len; + while((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + // Complete the entry + out.closeEntry(); + in.close(); - out.write(uniqueBytes); + // Complete the ZIP file + out.close(); - while ((len = in.read(buf)) > 0) { - out.write(buf, 0, len); - } - // Complete the entry - out.closeEntry(); - in.close(); - - // Complete the ZIP file - out.close(); - - ReplayMod.fileCopyHandler.registerModifiedFile(tempFile, zipFile); - } + ReplayMod.fileCopyHandler.registerModifiedFile(tempFile, zipFile); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/utils/ResourceHelper.java b/src/main/java/eu/crushedpixel/replaymod/utils/ResourceHelper.java index dc2c73bb..b2ebd416 100755 --- a/src/main/java/eu/crushedpixel/replaymod/utils/ResourceHelper.java +++ b/src/main/java/eu/crushedpixel/replaymod/utils/ResourceHelper.java @@ -1,47 +1,46 @@ package eu.crushedpixel.replaymod.utils; -import java.awt.image.BufferedImage; -import java.util.ArrayList; -import java.util.List; - -import javax.imageio.ImageIO; - import eu.crushedpixel.replaymod.reflection.MCPNames; import net.minecraft.client.Minecraft; import net.minecraft.util.ResourceLocation; +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.util.ArrayList; +import java.util.List; + public class ResourceHelper { - private static BufferedImage defaultThumb; + private static BufferedImage defaultThumb; + private static List openResources = new ArrayList(); - static { - try { - defaultThumb = ImageIO.read(MCPNames.class.getClassLoader().getResourceAsStream("default_thumb.jpg")); - } catch(Exception e) { - defaultThumb = new BufferedImage(1, 1, BufferedImage.TYPE_3BYTE_BGR); - e.printStackTrace(); - } - } - private static List openResources = new ArrayList(); + static { + try { + defaultThumb = ImageIO.read(MCPNames.class.getClassLoader().getResourceAsStream("default_thumb.jpg")); + } catch(Exception e) { + defaultThumb = new BufferedImage(1, 1, BufferedImage.TYPE_3BYTE_BGR); + e.printStackTrace(); + } + } - public static void registerResource(ResourceLocation loc) { - openResources.add(loc); - } + public static void registerResource(ResourceLocation loc) { + openResources.add(loc); + } - public static void freeResource(ResourceLocation loc) { - Minecraft.getMinecraft().getTextureManager().deleteTexture(loc); - openResources.remove(loc); - } + public static void freeResource(ResourceLocation loc) { + Minecraft.getMinecraft().getTextureManager().deleteTexture(loc); + openResources.remove(loc); + } - public static void freeAllResources() { - for(ResourceLocation loc : openResources) { - Minecraft.getMinecraft().getTextureManager().deleteTexture(loc); - } + public static void freeAllResources() { + for(ResourceLocation loc : openResources) { + Minecraft.getMinecraft().getTextureManager().deleteTexture(loc); + } - openResources = new ArrayList(); - } + openResources = new ArrayList(); + } - public static BufferedImage getDefaultThumbnail() { - return defaultThumb; - } + public static BufferedImage getDefaultThumbnail() { + return defaultThumb; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/utils/StreamTools.java b/src/main/java/eu/crushedpixel/replaymod/utils/StreamTools.java index 64142d5a..af886928 100755 --- a/src/main/java/eu/crushedpixel/replaymod/utils/StreamTools.java +++ b/src/main/java/eu/crushedpixel/replaymod/utils/StreamTools.java @@ -17,21 +17,13 @@ */ package eu.crushedpixel.replaymod.utils; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.Reader; -import java.io.StringWriter; +import java.io.*; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** - * * @author Marc Schunk, created on 21.06.2004 - * + *

* A Class to provide helpers of commonly user operations with binary * and character Streams, such as read to an OutputStream/Writer, * String, ByteArray. In addition streams can be compressed. @@ -39,209 +31,196 @@ import java.util.zip.GZIPOutputStream; public class StreamTools { - /** - * Checks weather the given array is contained in the first array - * - * @param ar1 - * - the containing array - * @param index1 - * - the index where the search starts - * @param ar2 - * - the array that schould be contained - * @return - true of ar2 is contained in ar1 - */ - public static final boolean arrayMatch(char[] ar1, int index1, char[] ar2) { - if((ar1.length - index1 - ar2.length) < 0) - return false; - for(int i = 0; i < ar2.length; i++) { - if(ar1[index1 + i] != ar2[i]) - return false; - } - return true; - } + public static final String[] umlauteString = {"&", "ß", "ä", + "Ä", "ö", "Ö", "ü", "Ü", "ß"}; + public static final String[] umlauteReplacement = {"&", "ß", "ä", "Ä", "ö", + "Ö", "ü", "Ü", "ß"}; - /** - * Reads inStream completly and writes it to outStream. Streams will not be - * closed. - * - * @param inStream - * - an InputStream to be read completely - * @param outStream - * - the destination Stream - * @throws IOException - */ - public static void readStream(InputStream inStream, OutputStream outStream) - throws IOException { - byte[] buffer = new byte[4096]; - int len = 0; - while((len = inStream.read(buffer, 0, buffer.length)) > -1) { - outStream.write(buffer, 0, len); - } - } + /** + * Checks weather the given array is contained in the first array + * + * @param ar1 - the containing array + * @param index1 - the index where the search starts + * @param ar2 - the array that schould be contained + * @return - true of ar2 is contained in ar1 + */ + public static final boolean arrayMatch(char[] ar1, int index1, char[] ar2) { + if((ar1.length - index1 - ar2.length) < 0) + return false; + for(int i = 0; i < ar2.length; i++) { + if(ar1[index1 + i] != ar2[i]) + return false; + } + return true; + } - /** - * Reads inStream completly into an byte[]. Streams will not be closed. - * - * @param inStream - * - an InputStream to be read completely - * @param outStream - * - the destination Stream - * @throws IOException - */ - public static byte[] readStream(InputStream inStream) throws IOException { - byte[] buffer = new byte[4096]; - int len = 0; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - while((len = inStream.read(buffer, 0, buffer.length)) > -1) { - baos.write(buffer, 0, len); - } - return baos.toByteArray(); - } + /** + * Reads inStream completly and writes it to outStream. Streams will not be + * closed. + * + * @param inStream - an InputStream to be read completely + * @param outStream - the destination Stream + * @throws IOException + */ + public static void readStream(InputStream inStream, OutputStream outStream) + throws IOException { + byte[] buffer = new byte[4096]; + int len = 0; + while((len = inStream.read(buffer, 0, buffer.length)) > -1) { + outStream.write(buffer, 0, len); + } + } - /** - * Reads the given Steam into an String * - * - * @throws IOException - */ - public static String readStreamtoString(InputStream inStream) - throws IOException { - StringWriter sw = new StringWriter(); - InputStreamReader isr = new InputStreamReader(inStream); + /** + * Reads inStream completly into an byte[]. Streams will not be closed. + * + * @param inStream - an InputStream to be read completely + * @param outStream - the destination Stream + * @throws IOException + */ + public static byte[] readStream(InputStream inStream) throws IOException { + byte[] buffer = new byte[4096]; + int len = 0; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + while((len = inStream.read(buffer, 0, buffer.length)) > -1) { + baos.write(buffer, 0, len); + } + return baos.toByteArray(); + } - char[] buffer = new char[4096]; - int len = 0; - while((len = isr.read(buffer, 0, buffer.length)) > -1) { - sw.write(buffer, 0, len); - } - return sw.toString(); - } + /** + * Reads the given Steam into an String * + * + * @throws IOException + */ + public static String readStreamtoString(InputStream inStream) + throws IOException { + StringWriter sw = new StringWriter(); + InputStreamReader isr = new InputStreamReader(inStream); - /** - * Reads the given Steam into an String using the given encoding - * - * @throws IOException - */ - public static String readStreamtoString(InputStream inStream, String charSet) - throws IOException { - StringWriter sw = new StringWriter(); - InputStreamReader isr = new InputStreamReader(inStream, charSet); + char[] buffer = new char[4096]; + int len = 0; + while((len = isr.read(buffer, 0, buffer.length)) > -1) { + sw.write(buffer, 0, len); + } + return sw.toString(); + } - char[] buffer = new char[4096]; - int len = 0; - while((len = isr.read(buffer, 0, buffer.length)) > -1) { - sw.write(buffer, 0, len); - } - return sw.toString(); - } + /** + * Reads the given Steam into an String using the given encoding + * + * @throws IOException + */ + public static String readStreamtoString(InputStream inStream, String charSet) + throws IOException { + StringWriter sw = new StringWriter(); + InputStreamReader isr = new InputStreamReader(inStream, charSet); - public static String stripComments(String inString, String newLineDelimiter) - throws IOException { - StringWriter sw = new StringWriter(); - // use both windows and linux/unix line seperators to be independent of the file orgin - String[] lines = inString.split("\r\n|\n"); - for(String line : lines) { - if((line.indexOf("#") == -1) && (line.trim().length() > 0)) { - sw.append(line).append(newLineDelimiter); - } - } - return sw.toString(); - } + char[] buffer = new char[4096]; + int len = 0; + while((len = isr.read(buffer, 0, buffer.length)) > -1) { + sw.write(buffer, 0, len); + } + return sw.toString(); + } - public static final String[] umlauteString = {"&", "ß", "ä", - "Ä", "ö", "Ö", "ü", "Ü", "ß"}; - public static final String[] umlauteReplacement = {"&", "ß", "ä", "Ä", "ö", - "Ö", "ü", "Ü", "ß"}; + public static String stripComments(String inString, String newLineDelimiter) + throws IOException { + StringWriter sw = new StringWriter(); + // use both windows and linux/unix line seperators to be independent of the file orgin + String[] lines = inString.split("\r\n|\n"); + for(String line : lines) { + if((line.indexOf("#") == -1) && (line.trim().length() > 0)) { + sw.append(line).append(newLineDelimiter); + } + } + return sw.toString(); + } - public static String replaceSpecialCharacters(String s) { - for(int i = 0; i < umlauteString.length; i++) { - s = s.replaceAll(umlauteString[i], umlauteReplacement[i]); - } - return s; - } + public static String replaceSpecialCharacters(String s) { + for(int i = 0; i < umlauteString.length; i++) { + s = s.replaceAll(umlauteString[i], umlauteReplacement[i]); + } + return s; + } - /** - * Stores the given Stream in an byte[]. Stream is compressed on the fly. - * Streams will not be closed. - * - * @param inStream - * - an InputStream to be read completely - * @param outStream - * - the destination Stream - * @throws IOException - */ - public static byte[] compressStreamToByteArray(InputStream inStream) - throws IOException { - byte[] buffer = new byte[4096]; - int len = 0; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + /** + * Stores the given Stream in an byte[]. Stream is compressed on the fly. + * Streams will not be closed. + * + * @param inStream - an InputStream to be read completely + * @param outStream - the destination Stream + * @throws IOException + */ + public static byte[] compressStreamToByteArray(InputStream inStream) + throws IOException { + byte[] buffer = new byte[4096]; + int len = 0; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); - GZIPOutputStream zos = new GZIPOutputStream(baos); - while((len = inStream.read(buffer, 0, buffer.length)) > -1) { - zos.write(buffer, 0, len); - } - zos.close(); - return baos.toByteArray(); - } + GZIPOutputStream zos = new GZIPOutputStream(baos); + while((len = inStream.read(buffer, 0, buffer.length)) > -1) { + zos.write(buffer, 0, len); + } + zos.close(); + return baos.toByteArray(); + } - /** - * Stores the given Stream in an byte[]. Stream is compressed on the fly. - * Streams will not be closed. - * - * @param inStream - * - an InputStream to be read completely - * @param outStream - * - the destination Stream - * @throws IOException - */ - public static byte[] compress(byte[] uncompressed) throws IOException { - ByteArrayInputStream bais = new ByteArrayInputStream(uncompressed); - return compressStreamToByteArray(bais); - } + /** + * Stores the given Stream in an byte[]. Stream is compressed on the fly. + * Streams will not be closed. + * + * @param inStream - an InputStream to be read completely + * @param outStream - the destination Stream + * @throws IOException + */ + public static byte[] compress(byte[] uncompressed) throws IOException { + ByteArrayInputStream bais = new ByteArrayInputStream(uncompressed); + return compressStreamToByteArray(bais); + } - /** - * Stores the given Stream in an byte[]. Stream is decompressed on the fly. - * Thus, the input stream should contain compressed content. Streams will - * not be closed. - * - * @param inStream - * - an InputStream to be read completely - * @param outStream - * - the destination Stream - * @throws IOException - */ - public static byte[] decompressStreamToByteArray(InputStream inStream) - throws IOException { - byte[] buffer = new byte[4096]; - int len = 0; + /** + * Stores the given Stream in an byte[]. Stream is decompressed on the fly. + * Thus, the input stream should contain compressed content. Streams will + * not be closed. + * + * @param inStream - an InputStream to be read completely + * @param outStream - the destination Stream + * @throws IOException + */ + public static byte[] decompressStreamToByteArray(InputStream inStream) + throws IOException { + byte[] buffer = new byte[4096]; + int len = 0; - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - GZIPInputStream gzis = new GZIPInputStream(inStream); - while((len = gzis.read(buffer, 0, buffer.length)) > -1) { - baos.write(buffer, 0, len); - } - inStream.close(); - return baos.toByteArray(); - } + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + GZIPInputStream gzis = new GZIPInputStream(inStream); + while((len = gzis.read(buffer, 0, buffer.length)) > -1) { + baos.write(buffer, 0, len); + } + inStream.close(); + return baos.toByteArray(); + } - public static byte[] decompress(byte[] compressed) throws IOException { - ByteArrayInputStream bais = new ByteArrayInputStream(compressed); - return decompressStreamToByteArray(bais); - } + public static byte[] decompress(byte[] compressed) throws IOException { + ByteArrayInputStream bais = new ByteArrayInputStream(compressed); + return decompressStreamToByteArray(bais); + } - /** - * Reads the given Steam into an String * - * - * @throws IOException - */ - public static String readReaderToString(Reader reader) throws IOException { - StringBuffer sb = new StringBuffer(); + /** + * Reads the given Steam into an String * + * + * @throws IOException + */ + public static String readReaderToString(Reader reader) throws IOException { + StringBuffer sb = new StringBuffer(); - char[] buffer = new char[4096]; - int len = 0; - while((len = reader.read(buffer, 0, buffer.length)) > -1) { - sb.append(buffer, 0, len); - } - return sb.toString(); - } + char[] buffer = new char[4096]; + int len = 0; + while((len = reader.read(buffer, 0, buffer.length)) > -1) { + sb.append(buffer, 0, len); + } + return sb.toString(); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/utils/ZipFileUtils.java b/src/main/java/eu/crushedpixel/replaymod/utils/ZipFileUtils.java index e58afab6..61a130bf 100755 --- a/src/main/java/eu/crushedpixel/replaymod/utils/ZipFileUtils.java +++ b/src/main/java/eu/crushedpixel/replaymod/utils/ZipFileUtils.java @@ -10,50 +10,49 @@ import java.util.zip.ZipOutputStream; public class ZipFileUtils { - public static void deleteZipEntry(File zipFile, - String[] files) throws IOException { - // get a temp file - File tempFile = File.createTempFile(zipFile.getName(), null); - // delete it, otherwise you cannot rename your existing zip to it. - tempFile.delete(); - tempFile.deleteOnExit(); - boolean renameOk=zipFile.renameTo(tempFile); - if (!renameOk) - { - throw new RuntimeException("could not rename the file "+zipFile.getAbsolutePath()+" to "+tempFile.getAbsolutePath()); - } - byte[] buf = new byte[1024]; + public static void deleteZipEntry(File zipFile, + String[] files) throws IOException { + // get a temp file + File tempFile = File.createTempFile(zipFile.getName(), null); + // delete it, otherwise you cannot rename your existing zip to it. + tempFile.delete(); + tempFile.deleteOnExit(); + boolean renameOk = zipFile.renameTo(tempFile); + if(!renameOk) { + throw new RuntimeException("could not rename the file " + zipFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath()); + } + byte[] buf = new byte[1024]; - ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile)); - ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(zipFile)); + ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile)); + ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(zipFile)); + + ZipEntry entry = zin.getNextEntry(); + while(entry != null) { + String name = entry.getName(); + boolean toBeDeleted = false; + for(String f : files) { + if(f.equals(name)) { + toBeDeleted = true; + break; + } + } + if(!toBeDeleted) { + // Add ZIP entry to output stream. + zout.putNextEntry(new ZipEntry(name)); + // Transfer bytes from the ZIP file to the output file + int len; + while((len = zin.read(buf)) > 0) { + zout.write(buf, 0, len); + } + } + entry = zin.getNextEntry(); + } + // Close the streams + zin.close(); + // Compress the files + // Complete the ZIP file + zout.close(); + tempFile.delete(); + } - ZipEntry entry = zin.getNextEntry(); - while (entry != null) { - String name = entry.getName(); - boolean toBeDeleted = false; - for (String f : files) { - if (f.equals(name)) { - toBeDeleted = true; - break; - } - } - if (!toBeDeleted) { - // Add ZIP entry to output stream. - zout.putNextEntry(new ZipEntry(name)); - // Transfer bytes from the ZIP file to the output file - int len; - while ((len = zin.read(buf)) > 0) { - zout.write(buf, 0, len); - } - } - entry = zin.getNextEntry(); - } - // Close the streams - zin.close(); - // Compress the files - // Complete the ZIP file - zout.close(); - tempFile.delete(); - } - } diff --git a/src/main/java/eu/crushedpixel/replaymod/video/ReplayScreenshot.java b/src/main/java/eu/crushedpixel/replaymod/video/ReplayScreenshot.java index fa8dcad4..c8261fee 100755 --- a/src/main/java/eu/crushedpixel/replaymod/video/ReplayScreenshot.java +++ b/src/main/java/eu/crushedpixel/replaymod/video/ReplayScreenshot.java @@ -1,113 +1,95 @@ package eu.crushedpixel.replaymod.video; -import java.awt.Dimension; -import java.awt.Rectangle; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.nio.IntBuffer; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; -import java.util.zip.ZipOutputStream; - -import javax.imageio.ImageIO; - +import eu.crushedpixel.replaymod.ReplayMod; +import eu.crushedpixel.replaymod.chat.ChatMessageHandler.ChatMessageType; import eu.crushedpixel.replaymod.events.TickAndRenderListener; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.renderer.OpenGlHelper; -import net.minecraft.client.renderer.texture.TextureUtil; -import net.minecraft.client.shader.Framebuffer; - -import org.lwjgl.BufferUtils; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; - -import eu.crushedpixel.replaymod.chat.ChatMessageRequests; -import eu.crushedpixel.replaymod.chat.ChatMessageRequests.ChatMessageType; import eu.crushedpixel.replaymod.gui.GuiReplaySaving; import eu.crushedpixel.replaymod.replay.ReplayHandler; import eu.crushedpixel.replaymod.utils.ImageUtils; import eu.crushedpixel.replaymod.utils.ReplayFileIO; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.File; public class ReplayScreenshot { - private static Minecraft mc = Minecraft.getMinecraft(); + private static Minecraft mc = Minecraft.getMinecraft(); - private static long last_finish = -1; + private static long last_finish = -1; - private static boolean before; - private static double beforeSpeed; - private static GuiScreen beforeScreen; + private static boolean before; + private static double beforeSpeed; + private static GuiScreen beforeScreen; + private static boolean locked = false; - public static void prepareScreenshot() { - before = mc.gameSettings.hideGUI; - beforeSpeed = ReplayHandler.getSpeed(); - beforeScreen = mc.currentScreen; - } - - private static boolean locked = false; + public static void prepareScreenshot() { + before = mc.gameSettings.hideGUI; + beforeSpeed = ReplayMod.replaySender.getReplaySpeed(); + beforeScreen = mc.currentScreen; + } - public static void saveScreenshot() { + public static void saveScreenshot() { - if(locked) return; - locked = true; - - try { - GuiReplaySaving.replaySaving = true; + if(locked) return; + locked = true; - mc.gameSettings.hideGUI = true; - mc.currentScreen = null; + try { + GuiReplaySaving.replaySaving = true; - mc.entityRenderer.updateCameraAndRender(0); - ReplayHandler.setSpeed(0); + mc.gameSettings.hideGUI = true; + mc.currentScreen = null; - final BufferedImage fbi = ScreenCapture.captureScreen(); + mc.entityRenderer.updateCameraAndRender(0); + ReplayMod.replaySender.setReplaySpeed(0); - mc.gameSettings.hideGUI = before; - mc.currentScreen = beforeScreen; - ReplayHandler.setSpeed(beforeSpeed); + final BufferedImage fbi = ScreenCapture.captureScreen(); - //The actual cropping and saving should be executed in a separate thread - Thread ioThread = new Thread(new Runnable() { + mc.gameSettings.hideGUI = before; + mc.currentScreen = beforeScreen; + ReplayMod.replaySender.setReplaySpeed(beforeSpeed); - @Override - public void run() { - try { - float aspect = 1280f/720f; + //The actual cropping and saving should be executed in a separate thread + Thread ioThread = new Thread(new Runnable() { - Rectangle rect; - if((float)fbi.getWidth()/(float)fbi.getHeight() <= aspect) { - int h = Math.round(fbi.getWidth()/aspect); - int y = (fbi.getHeight()/2) - (h/2); - rect = new Rectangle(0, y, fbi.getWidth(), h); - } else { - int w = Math.round(fbi.getHeight()*aspect); - int x = (fbi.getWidth()/2) - (w/2); - rect = new Rectangle(x, 0, w, fbi.getHeight()); - } + @Override + public void run() { + try { + float aspect = 1280f / 720f; - final BufferedImage nbi = ImageUtils.cropImage(fbi, rect); + Rectangle rect; + if((float) fbi.getWidth() / (float) fbi.getHeight() <= aspect) { + int h = Math.round(fbi.getWidth() / aspect); + int y = (fbi.getHeight() / 2) - (h / 2); + rect = new Rectangle(0, y, fbi.getWidth(), h); + } else { + int w = Math.round(fbi.getHeight() * aspect); + int x = (fbi.getWidth() / 2) - (w / 2); + rect = new Rectangle(x, 0, w, fbi.getHeight()); + } - File replayFile = ReplayHandler.getReplayFile(); + final BufferedImage nbi = ImageUtils.cropImage(fbi, rect); - File tempImage = File.createTempFile("thumb", null); + File replayFile = ReplayHandler.getReplayFile(); - int h = 720; - int w = 1280; + File tempImage = File.createTempFile("thumb", null); - BufferedImage img = ImageUtils.scaleImage(nbi, new Dimension(w, h)); + int h = 720; + int w = 1280; - ImageIO.write(img, "jpg", tempImage); + BufferedImage img = ImageUtils.scaleImage(nbi, new Dimension(w, h)); - ReplayFileIO.addThumbToZip(replayFile, tempImage); + ImageIO.write(img, "jpg", tempImage); - tempImage.delete(); + ReplayFileIO.addThumbToZip(replayFile, tempImage); + + tempImage.delete(); /* - File outputFile = File.createTempFile(replayFile.getName(), null); + File outputFile = File.createTempFile(replayFile.getName(), null); byte[] buf = new byte[1024]; @@ -155,31 +137,29 @@ public class ReplayScreenshot { tempImage.delete(); */ - ChatMessageRequests.addChatMessage("Thumbnail has been successfully saved", ChatMessageType.INFORMATION); - } catch(Exception e) { - e.printStackTrace(); - } - finally { - GuiReplaySaving.replaySaving = false; - locked = false; - TickAndRenderListener.finishScreenshot(); - } - } - }); + ReplayMod.chatMessageHandler.addChatMessage("Thumbnail has been successfully saved", ChatMessageType.INFORMATION); + } catch(Exception e) { + e.printStackTrace(); + } finally { + GuiReplaySaving.replaySaving = false; + locked = false; + TickAndRenderListener.finishScreenshot(); + } + } + }); - ioThread.start(); - } - catch (Exception exception) { - exception.printStackTrace(); - mc.gameSettings.hideGUI = before; - mc.currentScreen = beforeScreen; - ReplayHandler.setSpeed(beforeSpeed); - exception.printStackTrace(); - ChatMessageRequests.addChatMessage("Thumbnail could not be saved", ChatMessageType.WARNING); - } + ioThread.start(); + } catch(Exception exception) { + exception.printStackTrace(); + mc.gameSettings.hideGUI = before; + mc.currentScreen = beforeScreen; + ReplayMod.replaySender.setReplaySpeed(beforeSpeed); + exception.printStackTrace(); + ReplayMod.chatMessageHandler.addChatMessage("Thumbnail could not be saved", ChatMessageType.WARNING); + } - last_finish = System.currentTimeMillis(); - } + last_finish = System.currentTimeMillis(); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/video/ReplayTimer.java b/src/main/java/eu/crushedpixel/replaymod/video/ReplayTimer.java index b0e14cba..99dcfb4e 100755 --- a/src/main/java/eu/crushedpixel/replaymod/video/ReplayTimer.java +++ b/src/main/java/eu/crushedpixel/replaymod/video/ReplayTimer.java @@ -5,13 +5,13 @@ import net.minecraft.util.Timer; public class ReplayTimer extends Timer { - public ReplayTimer(float p_i1018_1_) { - super(p_i1018_1_); - } + public ReplayTimer(float p_i1018_1_) { + super(p_i1018_1_); + } - @Override - public void updateTimer() { - if(ReplayProcess.isVideoRecording()) return; - super.updateTimer(); - } + @Override + public void updateTimer() { + if(ReplayProcess.isVideoRecording()) return; + super.updateTimer(); + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/video/ScreenCapture.java b/src/main/java/eu/crushedpixel/replaymod/video/ScreenCapture.java index d23f06e9..415552a8 100755 --- a/src/main/java/eu/crushedpixel/replaymod/video/ScreenCapture.java +++ b/src/main/java/eu/crushedpixel/replaymod/video/ScreenCapture.java @@ -1,85 +1,73 @@ package eu.crushedpixel.replaymod.video; -import java.awt.AWTException; -import java.awt.Rectangle; -import java.awt.Robot; -import java.awt.image.BufferedImage; -import java.nio.IntBuffer; - import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.texture.TextureUtil; import net.minecraft.client.shader.Framebuffer; - import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -import org.monte.screenrecorder.ScreenRecorder; + +import java.awt.image.BufferedImage; +import java.nio.IntBuffer; public class ScreenCapture { - private static final Minecraft mc = Minecraft.getMinecraft(); - - private static IntBuffer pixelBuffer; - private static int[] pixelValues; - - public static BufferedImage captureScreen() { - int width = mc.displayWidth; - int height = mc.displayHeight; + private static final Minecraft mc = Minecraft.getMinecraft(); - Framebuffer buffer = mc.getFramebuffer(); - - if (OpenGlHelper.isFramebufferEnabled()) - { - width = buffer.framebufferTextureWidth; - height = buffer.framebufferTextureHeight; - } + private static IntBuffer pixelBuffer; + private static int[] pixelValues; - int k = width * height; + public static BufferedImage captureScreen() { + int width = mc.displayWidth; + int height = mc.displayHeight; - if (pixelBuffer == null || pixelBuffer.capacity() < k) - { - pixelBuffer = BufferUtils.createIntBuffer(k); - pixelValues = new int[k]; - } + Framebuffer buffer = mc.getFramebuffer(); - GL11.glPixelStorei(GL11.GL_PACK_ALIGNMENT, 1); - GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1); - pixelBuffer.clear(); + if(OpenGlHelper.isFramebufferEnabled()) { + width = buffer.framebufferTextureWidth; + height = buffer.framebufferTextureHeight; + } - if (OpenGlHelper.isFramebufferEnabled()) { - GlStateManager.bindTexture(buffer.framebufferTexture); - GL11.glGetTexImage(GL11.GL_TEXTURE_2D, 0, GL12.GL_BGRA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV, pixelBuffer); - } - else { - GL11.glReadPixels(0, 0, width, height, GL12.GL_BGRA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV, pixelBuffer); - } + int k = width * height; - pixelBuffer.get(pixelValues); - TextureUtil.processPixelValues(pixelValues, width, height); - BufferedImage bufferedimage = null; + if(pixelBuffer == null || pixelBuffer.capacity() < k) { + pixelBuffer = BufferUtils.createIntBuffer(k); + pixelValues = new int[k]; + } + + GL11.glPixelStorei(GL11.GL_PACK_ALIGNMENT, 1); + GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1); + pixelBuffer.clear(); + + if(OpenGlHelper.isFramebufferEnabled()) { + GlStateManager.bindTexture(buffer.framebufferTexture); + GL11.glGetTexImage(GL11.GL_TEXTURE_2D, 0, GL12.GL_BGRA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV, pixelBuffer); + } else { + GL11.glReadPixels(0, 0, width, height, GL12.GL_BGRA, GL12.GL_UNSIGNED_INT_8_8_8_8_REV, pixelBuffer); + } + + pixelBuffer.get(pixelValues); + TextureUtil.processPixelValues(pixelValues, width, height); + BufferedImage bufferedimage = null; - if (OpenGlHelper.isFramebufferEnabled()) - { - bufferedimage = new BufferedImage(buffer.framebufferWidth, buffer.framebufferHeight, 1); - int l = buffer.framebufferTextureHeight - buffer.framebufferHeight; + if(OpenGlHelper.isFramebufferEnabled()) { + bufferedimage = new BufferedImage(buffer.framebufferWidth, buffer.framebufferHeight, 1); + int l = buffer.framebufferTextureHeight - buffer.framebufferHeight; - for (int i1 = l; i1 < buffer.framebufferTextureHeight; ++i1) - { - for (int j1 = 0; j1 < buffer.framebufferWidth; ++j1) - { - bufferedimage.setRGB(j1, i1 - l, pixelValues[i1 * buffer.framebufferTextureWidth + j1]); - } - } - } - else { - bufferedimage = new BufferedImage(width, height, 1); - bufferedimage.setRGB(0, 0, width, height, pixelValues, 0, width); - } - - - return bufferedimage; - } + for(int i1 = l; i1 < buffer.framebufferTextureHeight; ++i1) { + for(int j1 = 0; j1 < buffer.framebufferWidth; ++j1) { + bufferedimage.setRGB(j1, i1 - l, pixelValues[i1 * buffer.framebufferTextureWidth + j1]); + } + } + } else { + bufferedimage = new BufferedImage(width, height, 1); + bufferedimage.setRGB(0, 0, width, height, pixelValues, 0, width); + } + + + return bufferedimage; + } } diff --git a/src/main/java/eu/crushedpixel/replaymod/video/VideoWriter.java b/src/main/java/eu/crushedpixel/replaymod/video/VideoWriter.java index 5f85a831..6f75a0b8 100755 --- a/src/main/java/eu/crushedpixel/replaymod/video/VideoWriter.java +++ b/src/main/java/eu/crushedpixel/replaymod/video/VideoWriter.java @@ -1,5 +1,11 @@ package eu.crushedpixel.replaymod.video; +import eu.crushedpixel.replaymod.ReplayMod; +import eu.crushedpixel.replaymod.utils.ReplayFileIO; +import org.monte.media.*; +import org.monte.media.FormatKeys.MediaType; +import org.monte.media.math.Rational; + import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; @@ -8,140 +14,127 @@ import java.util.Calendar; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; -import org.monte.media.Buffer; -import org.monte.media.Format; -import org.monte.media.FormatKeys; -import org.monte.media.FormatKeys.MediaType; -import org.monte.media.MovieWriter; -import org.monte.media.Registry; -import org.monte.media.VideoFormatKeys; -import org.monte.media.math.Rational; - -import eu.crushedpixel.replaymod.ReplayMod; -import eu.crushedpixel.replaymod.utils.ReplayFileIO; - public class VideoWriter { - private static final String DATE_FORMAT = "yyyy_MM_dd_HH_mm_ss"; - private static final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); + private static final String DATE_FORMAT = "yyyy_MM_dd_HH_mm_ss"; + private static final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); - private static final String VIDEO_EXTENSION = ".avi"; + private static final String VIDEO_EXTENSION = ".avi"; - private static MovieWriter out; - private static File file; - private static boolean isRecording = false; - private static boolean requestFinish = false; - private static boolean abort = false; + private static MovieWriter out; + private static File file; + private static boolean isRecording = false; + private static boolean requestFinish = false; + private static boolean abort = false; - private static Buffer buf; - private static int track; + private static Buffer buf; + private static int track; + private static Queue toWrite = new LinkedBlockingQueue(); - public static boolean isRecording() { - return isRecording; - } + public static boolean isRecording() { + return isRecording; + } - public static void startRecording(int width, int height) { - if(isRecording) { - IllegalStateException up = new IllegalStateException("VideoWriter is already recording!"); - throw up; //lolololo - } - isRecording = true; + public static void startRecording(int width, int height) { + if(isRecording) { + IllegalStateException up = new IllegalStateException("VideoWriter is already recording!"); + throw up; //lolololo + } + isRecording = true; - toWrite = new LinkedBlockingQueue(); + toWrite = new LinkedBlockingQueue(); - try { - File folder = ReplayFileIO.getRenderFolder(); + try { + File folder = ReplayFileIO.getRenderFolder(); - String fileName = sdf.format(Calendar.getInstance().getTime()); + String fileName = sdf.format(Calendar.getInstance().getTime()); - file = new File(folder, fileName+VIDEO_EXTENSION); - file.createNewFile(); + file = new File(folder, fileName + VIDEO_EXTENSION); + file.createNewFile(); - out = Registry.getInstance().getWriter(file); - Format format = new Format(FormatKeys.MediaTypeKey, MediaType.VIDEO, - FormatKeys.EncodingKey, VideoFormatKeys.ENCODING_AVI_MJPG, - FormatKeys.FrameRateKey, new Rational(ReplayMod.replaySettings.getVideoFramerate(), 1), - VideoFormatKeys.WidthKey, width, - VideoFormatKeys.HeightKey, height, - VideoFormatKeys.DepthKey, 24, - VideoFormatKeys.QualityKey, (float)ReplayMod.replaySettings.getVideoQuality()); + out = Registry.getInstance().getWriter(file); + Format format = new Format(FormatKeys.MediaTypeKey, MediaType.VIDEO, + FormatKeys.EncodingKey, VideoFormatKeys.ENCODING_AVI_MJPG, + FormatKeys.FrameRateKey, new Rational(ReplayMod.replaySettings.getVideoFramerate(), 1), + VideoFormatKeys.WidthKey, width, + VideoFormatKeys.HeightKey, height, + VideoFormatKeys.DepthKey, 24, + VideoFormatKeys.QualityKey, (float) ReplayMod.replaySettings.getVideoQuality()); - track = out.addTrack(format); + track = out.addTrack(format); - buf = new Buffer(); - buf.format = new Format(VideoFormatKeys.DataClassKey, BufferedImage.class); - buf.sampleDuration = out.getFormat(track).get(VideoFormatKeys.FrameRateKey).inverse(); - } catch (IOException e) { - e.printStackTrace(); - } + buf = new Buffer(); + buf.format = new Format(VideoFormatKeys.DataClassKey, BufferedImage.class); + buf.sampleDuration = out.getFormat(track).get(VideoFormatKeys.FrameRateKey).inverse(); + } catch(IOException e) { + e.printStackTrace(); + } - Thread t = new Thread(new Runnable() { + Thread t = new Thread(new Runnable() { - @Override - public void run() { - while(true) { - if(toWrite.isEmpty() || abort) { - if(requestFinish) { - requestFinish = false; - isRecording = false; - try { - out.close(); - if(abort) { - file.delete(); - } - } catch (IOException e) { - e.printStackTrace(); - } - abort = false; - toWrite = new LinkedBlockingQueue(); - return; - } - try { - Thread.sleep(10); - } catch(Exception e) { - e.printStackTrace(); - } - } else { - write(); - } - } - } - }); - t.start(); - } + @Override + public void run() { + while(true) { + if(toWrite.isEmpty() || abort) { + if(requestFinish) { + requestFinish = false; + isRecording = false; + try { + out.close(); + if(abort) { + file.delete(); + } + } catch(IOException e) { + e.printStackTrace(); + } + abort = false; + toWrite = new LinkedBlockingQueue(); + return; + } + try { + Thread.sleep(10); + } catch(Exception e) { + e.printStackTrace(); + } + } else { + write(); + } + } + } + }); + t.start(); + } - private static Queue toWrite = new LinkedBlockingQueue(); + public static void writeImage(BufferedImage image) { + if(requestFinish || !isRecording) { + IllegalStateException up = new IllegalStateException( + "The VideoWriter is currently not available. Please try again later."); + throw up; //lolololo^2 + } - public static void writeImage(BufferedImage image) { - if(requestFinish || !isRecording) { - IllegalStateException up = new IllegalStateException( - "The VideoWriter is currently not available. Please try again later."); - throw up; //lolololo^2 - } + toWrite.add(image); + } - toWrite.add(image); - } + public static void endRecording() { + if(!isRecording) return; + requestFinish = true; + } - public static void endRecording() { - if(!isRecording) return; - requestFinish = true; - } + private static void write() { + try { + BufferedImage img = toWrite.poll(); + if(img != null) { + buf.data = img; + out.write(track, buf); + } + } catch(IOException e) { + e.printStackTrace(); + } + } - private static void write() { - try { - BufferedImage img = toWrite.poll(); - if(img != null) { - buf.data = img; - out.write(track, buf); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static void abortRecording() { - requestFinish = true; - abort = true; - } + public static void abortRecording() { + requestFinish = true; + abort = true; + } }