Delete src/main directory

This commit is contained in:
JoeMolinelli authored and GitHub committed 2026-07-09 22:29:08 -04:00
1 parent e1d7f70eda
commit 800569688a
42 files changed
-7693

No files matched your search

@@ -1,257 +0,0 @@
package WS3000.weatherstar3000;
import org.json.JSONObject;
import util.Utilities;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Objects;
public class Almanac extends Thread {
Utilities utl = new Utilities();
String today;
String tomorrow;
String todaySunrise;
String todaySunset;
String tomorrowSunrise;
String tomorrowSunset;
String todayLow;
String todayHigh;
String tomorrowHigh;
String tomorrowLow;
String normalPrecip;
String getDay(String icaoCode, String key, int dayNum) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/forecast/daily/7day?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
String day = JSONResponse.getJSONArray("dayOfWeek").getString(dayNum);
String[] dayNames = {" SUNDAY ", " MONDAY ", " TUESDAY ", "WEDNESDAY", "THURSDAY ", " FRIDAY ", "SATURDAY "};
return switch (day) {
case "Sunday" -> dayNames[0];
case "Monday" -> dayNames[1];
case "Tuesday" -> dayNames[2];
case "Wednesday" -> dayNames[3];
case "Thursday" -> dayNames[4];
case "Friday" -> dayNames[5];
case "Saturday" -> dayNames[6];
default -> " ";
};
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
String getSunrise(String icaoCode, String key, int dayNum) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/forecast/daily/7day?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
String time = JSONResponse.getJSONArray("sunriseTimeLocal").getString(dayNum);
int hour = Integer.parseInt(time.substring(11, 13));
int dispHour = hour > 12 ? hour - 12 : hour;
String minutes = time.substring(14, 16);
String part = hour < 12 ? " AM" : " PM";
return utl.rjust(dispHour + ":" + minutes + part, 8, " ");
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
String getSunset(String icaoCode, String key, int dayNum) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/forecast/daily/7day?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
String time = JSONResponse.getJSONArray("sunsetTimeLocal").getString(dayNum);
int hour = Integer.parseInt(time.substring(11, 13));
int dispHour = hour > 12 ? hour - 12 : hour;
String minutes = time.substring(14, 16);
String part = hour < 12 ? " AM" : " PM";
return utl.rjust(dispHour + ":" + minutes + part, 8, " ");
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
String getMonth(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/forecast/daily/7day?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return "error";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
return JSONResponse.getJSONArray("validTimeLocal").getString(0).substring(5, 7);
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
String getDayDate(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/forecast/daily/7day?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return "error";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
return JSONResponse.getJSONArray("validTimeLocal").getString(0).substring(8, 10);
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
String getTempMax(String icaoCode, String key, int dayNum, String month, String day) {
if (Objects.equals(month, "error") || Objects.equals(day, "error")) {
return " ";
}
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/almanac/daily/5day?icaoCode=" + icaoCode + "&format=json&units=e&startDay=" + day + "&startMonth=" + month + "&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
int temp = JSONResponse.getJSONArray("temperatureAverageMax").getInt(dayNum);
return utl.rjust(temp + " \\F", 6, " ");
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
String getTempMin(String icaoCode, String key, int dayNum, String month, String day) {
if (Objects.equals(month, "error") || Objects.equals(day, "error")) {
return " ";
}
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/almanac/daily/5day?icaoCode=" + icaoCode + "&format=json&units=e&startDay=" + day + "&startMonth=" + month + "&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
int temp = JSONResponse.getJSONArray("temperatureAverageMin").getInt(dayNum);
return utl.rjust(temp + " \\F", 6, " ");
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
String getPrecip(String icaoCode, String key, String month, String day) {
if (Objects.equals(month, "error") || Objects.equals(day, "error")) {
return " ";
}
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/almanac/daily/5day?icaoCode=" + icaoCode + "&format=json&units=e&startDay=" + day + "&startMonth=" + month + "&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
String[] monthNames = {"", "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"};
JSONObject JSONResponse = new JSONObject(ResponseBody);
float precip = JSONResponse.getJSONArray("precipitationAverage").getFloat(0);
String precipString = utl.rjust(precip + " IN", 8, " ");
String cmonth = utl.ljust("NORMAL " + monthNames[Integer.parseInt(month)] + " PRECIP", 23, " ");
return utl.ljust(cmonth + precipString, 31, " ") + " ";
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
public void run() {
String mainIcao = Main.mainIcao;
String key = Main.key;
String todayMonth = Main.todayMonth;
String todayDay = Main.todayDay;
Main.almanac.today = getDay(mainIcao, key, 0);
Main.almanac.tomorrow = getDay(mainIcao, key, 1);
Main.almanac.todaySunrise = getSunrise(mainIcao, key, 0);
Main.almanac.todaySunset = getSunset(mainIcao, key, 0);
Main.almanac.tomorrowSunrise = getSunrise(mainIcao, key, 1);
Main.almanac.tomorrowSunset = getSunset(mainIcao, key, 1);
Main.almanac.todayHigh = getTempMax(mainIcao, key, 0, todayMonth, todayDay);
Main.almanac.todayLow = getTempMin(mainIcao, key, 0, todayMonth, todayDay);
Main.almanac.tomorrowHigh = getTempMax(mainIcao, key, 1, todayMonth, todayDay);
Main.almanac.tomorrowLow = getTempMin(mainIcao, key, 1, todayMonth, todayDay);
Main.almanac.normalPrecip = getPrecip(mainIcao, key, todayMonth, todayDay);
}
}
@@ -1,86 +0,0 @@
package WS3000.weatherstar3000;
import javazoom.jl.player.Player;
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.List;
public class AudioManager extends Thread {
private Player player;
private List<File> playlist;
private volatile boolean finished;
public AudioManager(String folder) {
this.player = null;
this.finished = true;
File musicFolder = new File(folder);
if (!musicFolder.exists() || !musicFolder.isDirectory()) {
System.err.println("\"" + folder + "\" folder not found.");
return;
}
this.playlist = Arrays.asList(musicFolder.listFiles((dir, name) -> name.toLowerCase().endsWith(".mp3")));
for (int i = 0; i < this.playlist.size(); i++) {
//System.out.println(getSong(i));
}
}
public List<File> getPlayList() {
return this.playlist;
}
public File getSong(int index) {
return this.playlist.get(index);
}
private void playSong(File file) {
try (FileInputStream fis = new FileInputStream(file)) {
player = new Player(fis);
player.play();
} catch (Exception e) {
System.err.println("Error playing file " + file.getName() + ": " + e.getMessage());
return;
}
}
public void close() {
this.finished = true;
if (player != null) {
player.close();
}
}
public boolean isFinished() {
return finished;
}
public void startPlayList() {
finished = false;
while (!this.finished && playlist != null && !playlist.isEmpty()) {
for (int i = 0; i < this.playlist.size(); i++) {
if (this.finished) {
break;
}
//System.out.println("Playing " + this.playlist.get(i));
playSong(this.playlist.get(i));
}
}
if (player != null) {
player.close();
}
finished = true;
}
public void run() {
startPlayList();
}
}
@@ -1,152 +0,0 @@
package WS3000.weatherstar3000;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.Arrays;
import org.json.JSONArray;
import org.json.JSONObject;
import util.Utilities;
public class Bulletin extends Thread {
static Utilities utl = new Utilities();
ArrayList<String> bulletinText = new ArrayList<>();
//String color;
//boolean severe;
//boolean crawl;
public ArrayList<String> getBulletin(String key, String lat, String lon) {
ArrayList<String> words = new ArrayList<>();
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/alerts/headlines?geocode=" + lat + "," + lon + "&format=json&language=en-US&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
words.clear();
words.add("None");
words.add("NOBULLETINCRAWL");
return words;
}
JSONObject responseObject = new JSONObject(Response.body());
for (int i = 0; i < responseObject.getJSONArray("alerts").length(); i++) {
String headline = responseObject.getJSONArray("alerts").getJSONObject(i).getString("eventDescription");
String detailKey = responseObject.getJSONArray("alerts").getJSONObject(i).getString("detailKey");
if (utl.isScroll(headline)) {
return eachAlert(detailKey, key);
} else {
continue;
}
}
words.clear();
words.add("None");
words.add("NOBULLETINCRAWL");
return words;
} catch (Exception e) {
e.printStackTrace();
words.clear();
words.add("None");
words.add("NOBULLETINCRAWL");
return words;
}
}
public ArrayList<String> eachAlert(String detailKey, String key) {
ArrayList<String> words = new ArrayList<>();
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/alerts/detail?alertId=" + detailKey + "&format=json&language=en-US&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
words.clear();
words.add("None");
words.add("NOBULLETINCRAWL");
return words;
}
JSONObject ResponseObj = new JSONObject(Response.body());
String headline = ResponseObj.getJSONObject("alertDetail").getString("eventDescription");
String alert = ResponseObj.getJSONObject("alertDetail").getJSONArray("texts").getJSONObject(0).getString("description").toUpperCase();
words.clear();
words.addAll(Arrays.asList(alert.replace("\n\n", " *newline* ").split("\\s+")));
StringBuilder sb = new StringBuilder();
ArrayList<String> finalWords = new ArrayList<>();
finalWords.add(headline);
for (int i = 0; i <= words.size()-1; i++) {
if (words.get(i).equals("*newline*")) {
if (!sb.isEmpty()) {
finalWords.add(utl.ljust(sb.toString(), 32, " "));
sb.setLength(0);
}
finalWords.add(utl.ljust(sb.toString(), 32, " "));
sb.setLength(0);
continue;
}
int wordlength = words.get(i).length();
if (wordlength > 32) {
finalWords.add(utl.ljust(sb.toString(), 32, " "));
sb.setLength(0);
if (!sb.isEmpty()) {sb.append(" ");}
sb.append(words.get(i));
finalWords.add(utl.ljust(sb.toString(), 32, " "));
sb.setLength(0);
} else {
if (wordlength + sb.length() + 1 <= 32) {
if (!sb.isEmpty()) {sb.append(" ");}
sb.append(words.get(i));
} else {
i--;
finalWords.add(utl.ljust(sb.toString(), 32, " "));
sb.setLength(0);
}
}
}
finalWords.add(utl.ljust(sb.toString(), 32, " "));
sb.setLength(0);
return finalWords;
} catch (Exception e) {
words.clear();
words.add("None");
words.add("NOBULLETINCRAWL");
return words;
}
}
public void run() {
String key = Main.key;
String mainLat = Main.mainLat;
String mainLon = Main.mainLon;
Main.bulletin.bulletinText = getBulletin(key, mainLat, mainLon);
//System.out.println(Main.bulletin.bulletinText);
}
}
@@ -1,34 +0,0 @@
package WS3000.weatherstar3000;
import org.joml.*;
public class Camera {
private Matrix4f projectionMatrix, viewMatrix;
Vector2f position;
public Camera(Vector2f position) {
this.position = position;
this.projectionMatrix = new Matrix4f();
this.viewMatrix = new Matrix4f();
adjustProjection();
}
public void adjustProjection() {
projectionMatrix.identity();
projectionMatrix.ortho(0.0f, 720.0f, 480.0f, 0.0f, 0.0f, 100.0f);
}
public Matrix4f getViewMatrix() {
Vector3f cameraFront = new Vector3f(0.0f, 0.0f, -1.0f);
Vector3f cameraUp = new Vector3f(0.0f, 1.0f, 0.0f);
this.viewMatrix.identity();
viewMatrix = viewMatrix.lookAt(new Vector3f(position.x, position.y, 20.0f),
cameraFront.add(position.x, position.y, 0.0f),
cameraUp);
return this.viewMatrix;
}
public Matrix4f getProjectionMatrix() {
return this.projectionMatrix;
}
}
@@ -1,12 +0,0 @@
package WS3000.weatherstar3000;
public abstract class Component {
public GameObject gameObject = null;
public void start() {
}
public abstract void update(float dt);
}
@@ -1,338 +0,0 @@
package WS3000.weatherstar3000;
import org.json.JSONObject;
import util.Utilities;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
//import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.Month;
public class CurrentConditions extends Thread {
String locName;
String condition;
String temperature;
String feelsLike;
String humidity;
String dewPoint;
String pressure;
String wind;
String gusts;
String visibility;
String ceiling;
String precip;
static Utilities utl = new Utilities();
static String getLocName(String displayName) {return "CONDITIONS AT " + utl.ljust(displayName.toUpperCase(), 14, " ").substring(0, 14);}
static String getCondition(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/observations/current?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return "NO REPORT";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
return JSONResponse.getString("wxPhraseLong").toUpperCase();
} catch (Exception e) {
e.printStackTrace();
return "NO REPORT";
}
}
static String getTemperature(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/observations/current?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
String temp = utl.rjust(Integer.toString(JSONResponse.getInt("temperature")), 3, " ");
return "TEMP: " + temp + "\\F";
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
static String getFeelsLike(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/observations/current?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
int feelTemp = JSONResponse.getInt("temperatureFeelsLike");
int temp = JSONResponse.getInt("temperature");
if (temp == feelTemp) {
return " ";
} else {
if (feelTemp > 65) {
return "HEAT INDEX:" + utl.rjust(Integer.toString(feelTemp), 3, " ") + "\\F";
} else {
return "WIND CHILL:" + utl.rjust(Integer.toString(feelTemp), 3, " ") + "\\F";
}
}
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
static String getHumidity(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/observations/current?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
String humid = utl.rjust(Integer.toString(JSONResponse.getInt("relativeHumidity")), 3, " ");
return "HUMIDITY: " + humid + "%";
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
static String getDewPoint(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/observations/current?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
String dewpt = utl.rjust(Integer.toString(JSONResponse.getInt("temperatureDewPoint")), 3, " ");
return "DEWPOINT:" + dewpt + "\\F";
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
static String getPressure(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/observations/current?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
//DecimalFormat df = new DecimalFormat("#.##");
float pres = JSONResponse.getFloat("pressureAltimeter");
String fpres = String.format("%.2f", pres);
int presCode = JSONResponse.getInt("pressureTendencyCode");
String fpresCode = "";
if (presCode == 0) {
fpresCode = "IN.";
} else if (presCode == 1 || presCode == 3) {
fpresCode = "R";
} else if (presCode == 2 || presCode == 4) {
fpresCode = "F";
}
return "BAROMETRIC PRESSURE: " + fpres + " " + fpresCode;
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
static String getWind(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/observations/current?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
int windDir = JSONResponse.getInt("windDirection");
int windSpeed = JSONResponse.getInt("windSpeed");
if (windSpeed == 0) {
return "WIND: CALM ";
} else {
return "WIND: " + utl.degToThreeLetter(windDir) + utl.rjust(Integer.toString(windSpeed), 3, " ") + " MPH";
}
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
static String getGusts(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/observations/current?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
String gus;
gus = JSONResponse.isNull("windGust") ? " " : "GUSTS TO " + utl.rjust(Integer.toString(JSONResponse.getInt("windGust")), 3, " ");
return gus;
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
static String getVisiblity(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/observations/current?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
String visib = utl.rjust(Integer.toString(JSONResponse.getInt("visibility")) + " MI.", 7, " ");
return "VISIB: " + visib;
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
String getCeiling(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/observations/current?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
String ceil = JSONResponse.isNull("cloudCeiling") ? "UNLIMITED" : utl.rjust(JSONResponse.getInt("cloudCeiling") + " FT.", 9, " ");
return "CEILING:" + ceil;//three length
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
String getPrecip(String key, String lat, String lon) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v1/geocode/" + lat + "/" + lon + "/observations/current.json?language=en-US&units=e&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
LocalDate cdate = LocalDate.now();
Month cmonth = cdate.getMonth();
try {
JSONObject obsObject = JSONResponse.getJSONObject("observation");
JSONObject impObj = obsObject.getJSONObject("imperial");
String fprecip = String.format("%.2f", impObj.getFloat("precip_mtd"));
String prec = utl.rjust(fprecip + " IN", 8, " ");
return cmonth.name().toUpperCase() + " PRECIPITATION:" + prec;
} catch (Exception e) {
return " ";
}
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
public void run() {
String mainLocName = Main.mainLocName.getText();
String key = Main.key;
String mainIcao = Main.mainIcao;
String mainLat = Main.mainLat;
String mainLon = Main.mainLon;
Main.currentConditions.locName = getLocName(mainLocName);
Main.currentConditions.condition = getCondition(mainIcao, key);
Main.currentConditions.temperature = getTemperature(mainIcao, key);
Main.currentConditions.feelsLike = getFeelsLike(mainIcao, key);
Main.currentConditions.humidity = getHumidity(mainIcao, key);
Main.currentConditions.dewPoint = getDewPoint(mainIcao, key);
Main.currentConditions.pressure = getPressure(mainIcao, key);
Main.currentConditions.wind = getWind(mainIcao, key);
Main.currentConditions.gusts = getGusts(mainIcao, key);
Main.currentConditions.visibility = getVisiblity(mainIcao, key);
Main.currentConditions.ceiling = getCeiling(mainIcao, key);
Main.currentConditions.precip = getPrecip(key, mainLat, mainLon);
}
}
@@ -1,47 +0,0 @@
package WS3000.weatherstar3000;
public class DataRunner extends Thread {
public void run() {
//System.out.println("Data collection");
Main.currentConditions = new CurrentConditions();
Main.hourlyObservations = new HourlyObservations();
Main.regionalConditions = new RegionalConditions();
Main.localForecast = new LocalForecast();
Main.almanac = new Almanac();
Main.regionalForecast = new RegionalForecast();
Main.extendedForecast = new ExtendedForecast();
Main.outlook = new Outlook();
Main.travelForecast = new TravelForecast();
Main.bulletin = new Bulletin();
Main.currentConditions.start();
Main.hourlyObservations.start();
Main.regionalConditions.start();
Main.localForecast.start();
Main.almanac.start();
Main.regionalForecast.start();
Main.extendedForecast.start();
Main.outlook.start();
Main.travelForecast.start();
Main.bulletin.start();
try {
Main.currentConditions.join();
Main.hourlyObservations.join();
Main.regionalConditions.join();
Main.localForecast.join();
Main.almanac.join();
Main.regionalForecast.join();
Main.extendedForecast.join();
Main.outlook.join();
Main.travelForecast.join();
Main.bulletin.join();
LoadingScreen.dataFinish = true;
SlidesRunner.collectingData = false;
//ystem.out.println("data finished, destroying thread");
//wr.join();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
@@ -1,146 +0,0 @@
package WS3000.weatherstar3000;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import org.json.JSONObject;
import util.Utilities;
public class ExtendedForecast extends Thread {
String dayOne;
String dayTwo;
String dayThree;
ArrayList<String> conditionOne;
ArrayList<String> conditionTwo;
ArrayList<String> conditionThree;
String lowOne;
String lowTwo;
String lowThree;
String highOne;
String highTwo;
String highThree;
Utilities utl = new Utilities();
String getDayName(String icaoCode, String key, int day) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/forecast/daily/7day?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
//JSONObject JSONResponse = new JSONObject(ResponseBody);
//JSONObject dpData = JSONResponse.getJSONArray("daypart").getJSONObject(0);
//int bump = dpData.getJSONArray("dayOrNight").isNull(0) ? 1 : 0;
return utl.ljust(new JSONObject(ResponseBody).getJSONArray("dayOfWeek").getString(day + 2).toUpperCase(), 10, " ");
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
ArrayList<String> getCondition(String icaoCode, String key, int day) {
ArrayList<String> values = new ArrayList<>();
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/forecast/daily/7day?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
values.add(" ");
values.add(" ");
return values;
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
JSONObject dpData = JSONResponse.getJSONArray("daypart").getJSONObject(0);
int bump = dpData.getJSONArray("dayOrNight").isNull(0) ? 5 : 4;
int ex = day*2;
values.add(utl.getForecastEx(dpData.getJSONArray("iconCodeExtend").getInt(ex + bump), 0));
values.add(utl.getForecastEx(dpData.getJSONArray("iconCodeExtend").getInt(ex + bump), 1));
return values;
} catch (Exception e) {
e.printStackTrace();
values.add(" ");
values.add(" ");
return values;
}
}
String getLow(String icaoCode, String key, int day) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/forecast/daily/7day?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
JSONObject dpData = JSONResponse.getJSONArray("daypart").getJSONObject(0);
int bump = dpData.getJSONArray("dayOrNight").isNull(0) ? 5 : 4;
int ex = day*2;
return "LO:" + utl.rjust(Integer.toString(dpData.getJSONArray("temperature").getInt(ex + bump + 1)), 4, " ") + " ";
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
String getHigh(String icaoCode, String key, int day) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/forecast/daily/7day?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
JSONObject dpData = JSONResponse.getJSONArray("daypart").getJSONObject(0);
int bump = dpData.getJSONArray("dayOrNight").isNull(0) ? 5 : 4;
int ex = day*2;
return "HI:" + utl.rjust(Integer.toString(dpData.getJSONArray("temperature").getInt(ex + bump)), 4, " ") + " ";
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
public void run() {
String key = Main.key;
String mainIcao = Main.mainIcao;
Main.extendedForecast.dayOne = getDayName(mainIcao, key, 0);
Main.extendedForecast.dayTwo = getDayName(mainIcao, key, 1);
Main.extendedForecast.dayThree = getDayName(mainIcao, key, 2);
Main.extendedForecast.conditionOne = getCondition(mainIcao, key, 0);
Main.extendedForecast.conditionTwo = getCondition(mainIcao, key, 1);
Main.extendedForecast.conditionThree = getCondition(mainIcao, key, 2);
Main.extendedForecast.lowOne = getLow(mainIcao, key, 0);
Main.extendedForecast.lowTwo = getLow(mainIcao, key, 1);
Main.extendedForecast.lowThree = getLow(mainIcao, key, 2);
Main.extendedForecast.highOne = getHigh(mainIcao, key, 0);
Main.extendedForecast.highTwo = getHigh(mainIcao, key, 1);
Main.extendedForecast.highThree = getHigh(mainIcao, key, 2);
}
}
@@ -1,77 +0,0 @@
package WS3000.weatherstar3000;
import java.util.ArrayList;
import java.util.List;
public class GameObject {
private String name;
private List<Component> components;
public Transform transform;
private int zIndex;
private boolean visible = true;
public GameObject(String name) {
this.name = name;
this.components = new ArrayList<>();
this.transform = new Transform();
this.zIndex = 0;
this.visible = true;
}
public GameObject(String name, Transform transform, int zIndex) {
this.name = name;
this.zIndex = zIndex;
this.components = new ArrayList<>();
this.transform = transform;
this.visible = true;
}
public <T extends Component> T getComponent(Class<T> componentClass) {
for (Component c : components) {
if (componentClass.isAssignableFrom(c.getClass())) {
try {
return componentClass.cast(c);
} catch (ClassCastException e) {
e.printStackTrace();
assert false : "Error casting component";
}
}
}
return null;
}
public <T extends Component> void removeComponent(Class<T> componentClass) {
for (int i = 0; i < components.size(); i++) {
Component c = components.get(i);
if (componentClass.isAssignableFrom(c.getClass())) {
components.remove(i);
return;
}
}
}
public void addComponent(Component c) {
this.components.add(c);
c.gameObject = this;
}
public void update(float dt) {
for (int i = 0; i < components.size(); i++) {
components.get(i).update(dt);
}
}
public void start() {
for (int i = 0; i <components.size(); i++) {
components.get(i).start();
}
}
public boolean isVisible() {
return this.visible;
}
public int zIndex() {
return this.zIndex;
}
}
@@ -1,102 +0,0 @@
package WS3000.weatherstar3000;
import org.json.JSONObject;
import util.Utilities;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
public class HourlyObservations extends Thread {
ArrayList<String> locName = new ArrayList<>();
ArrayList<String> temperature = new ArrayList<>();
ArrayList<String> condition = new ArrayList<>();
ArrayList<String> wind = new ArrayList<>();
Utilities utl = new Utilities();
String getLocName(String displayName) {
return utl.ljust(displayName, 14, " ").substring(0, 14);
}
String getTemperature(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/observations/current?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
return utl.rjust(Integer.toString(JSONResponse.getInt("temperature")), 3, " ");
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
String getCondition(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/observations/current?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return "NO REPORT";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
return utl.getCondition(JSONResponse.getInt("iconCodeExtend"));
} catch (Exception e) {
e.printStackTrace();
return "NO REPORT";
}
}
String getWind(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/observations/current?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
int windDir = JSONResponse.getInt("windDirection");
int windSpeed = JSONResponse.getInt("windSpeed");
return utl.formatWind(windSpeed, windDir, false);
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
public void run() {
ArrayList<String> nearNames = new ArrayList<>();
nearNames.addAll(Main.nearNames);
ArrayList<String> nearIcaos = new ArrayList<>();;
nearIcaos.addAll(Main.nearIcaos);
String key = Main.key;
for (int i = 0; i < nearIcaos.size(); i++) {
Main.hourlyObservations.locName.add(getLocName(nearNames.get(i)));
Main.hourlyObservations.temperature.add(getTemperature(nearIcaos.get(i), key));
Main.hourlyObservations.condition.add(getCondition(nearIcaos.get(i), key));
Main.hourlyObservations.wind.add(getWind(nearIcaos.get(i), key));
}
}
}
@@ -1,39 +0,0 @@
package WS3000.weatherstar3000;
import static org.lwjgl.glfw.GLFW.*;
public class KeyListener {
private static KeyListener instance;
private boolean keyPressed[] = new boolean[350];
private KeyListener() {
}
public static KeyListener get() {
if (KeyListener.instance == null) {
KeyListener.instance = new KeyListener();
}
return KeyListener.instance;
}
public static void keyCallback(long window, int key, int scancode, int action, int mods) {
if (key >= 0 && key <= 350) {
if (action == GLFW_PRESS) {
get().keyPressed[key] = true;
} else if (action == GLFW_RELEASE) {
get().keyPressed[key] = false;
}
}
return;
}
public static boolean isKeyPressed(int keyCode) {
if (keyCode >= 0 && keyCode <= 350) {
return get().keyPressed[keyCode];
} else {
return false;
}
}
}
@@ -1,113 +0,0 @@
package WS3000.weatherstar3000;
import java.util.ArrayList;
import org.joml.Vector2f;
import org.joml.Vector4f;
import components.SpriteRenderer;
import components.Spritesheet;
import util.AssetPool;
import util.Utilities;
public class LoadingScreen extends Scene {
Vector4f color1 = new Vector4f(82.0f/255.0f, 80.0f/255.0f, 80.0f/255.0f, 1.0f); //gray
Vector4f color2 = new Vector4f(11.0f/255.0f, 104.0f/255.0f, 6.0f/255.0f, 1.0f); //green
Vector4f color3 = new Vector4f(61.0f/255.0f, 0.0f/255.0f, 109.0f/255.0f, 1.0f); //purple
Vector4f color4 = new Vector4f(104.0f/255.0f, 0.0f/255.0f, 8.0f/255.0f, 1.0f); //red
Vector4f color5 = new Vector4f(4.0f/255.0f, 92.0f/255.0f, 82.0f/255.0f, 1.0f); //cyan
Vector4f color6 = new Vector4f(46.0f/255.0f, 2.0f/255.0f, 120.0f/255.0f, 1.0f); //blue BG
Vector4f color7 = new Vector4f(124.0f/255.0f, 104.0f/255.0f, 6.0f/255.0f, 1.0f); //gold
Vector4f color8 = new Vector4f(3.0f/255.0f, 0.0f/255.0f, 0.0f/255.0f, 1.0f); //black
Vector4f color9 = new Vector4f(106.0f/255.0f, 80.0f/255.0f, 57.0f/255.0f, 1.0f); //brown
Vector4f color10 = new Vector4f(116.0f/255.0f, 133.0f/255.0f, 22.0f/255.0f, 1.0f); //yellow
Vector4f color11 = new Vector4f(60.0f/255.0f, 0.0f/255.0f, 109.0f/255.0f, 1.0f); //purple (again?)
Vector4f color12 = new Vector4f(132.0f/255.0f, 81.0f/255.0f, 74.0f/255.0f, 1.0f); //peach
Vector4f color13 = new Vector4f(83.0f/255.0f, 77.0f/255.0f, 1.0f/255.0f, 1.0f); //hazel
Vector4f color14 = new Vector4f(9.0f/255.0f, 121.0f/255.0f, 172.0f/255.0f, 1.0f); //light blue
Vector4f color15 = new Vector4f(160.0f/255.0f, 78.0f/255.0f, 14.0f/255.0f, 1.0f); //orange
Vector4f color16 = new Vector4f(188.0f/255.0f, 190.0f/255.0f, 189.0f/255.0f, 1.0f); //white
Vector4f greenScreen = new Vector4f(0.0f/255.0f, 255.0f/255.0f, 0.0f/255.0f, 1.0f);
Utilities utl = new Utilities();
Spritesheet sprites;
boolean dataInit = false;
static boolean dataFinish = false;
public LoadingScreen() {
}
@Override
public void init() {
loadResources();
this.camera = new Camera(new Vector2f(0, 0));
sprites = AssetPool.getSpritesheet("/resources/images/charMap.png");
ArrayList<String> lines = new ArrayList<>();
GameObject[] lsPool = new GameObject[256];
for (int i = 0; i < lsPool.length; i++) {
lsPool[i] = new GameObject("ccPool" + i, new Transform(new Vector2f()), 0);
lsPool[i].addComponent(new SpriteRenderer(new Vector4f(1,1,1,1)));
}
lines.add("LOADING DATA...");
lines.add(" ");
lines.add("MADE WITH JAVA, LWJGL, OPENGL,");
lines.add("AND JLAYER BY JAVAZOOM");
lines.add("BROUGHT TO YOU BY");
lines.add("JOE MOLINELLI");
lines.add("AND MIST WEATHER MEDIA");
int textX = 81;
int textY = 44;
int poolIdx = 0;
for (int row = 0; row < lines.size(); row++) {
int lineHeight = 40;
String line = lines.get(row);
for (int i = 0; i < line.length(); i ++) {
if (poolIdx >= lsPool.length) break;
char c = line.charAt(i);
GameObject go = lsPool[poolIdx++];
go.transform.position.set(textX, textY);
go.transform.scale.set(18, 32);
SpriteRenderer sr = go.getComponent(SpriteRenderer.class);
sr.setSprite(sprites.getSprite(utl.getMainChar(c)));
this.addGameObjectToScene(go);
if (i % 2 != 0) textX++;
textX += 17;
}
textX = 81;
textY += lineHeight;
}
}
private void loadResources() {
AssetPool.getShader("/resources/shaders/default.glsl");
AssetPool.addSpritesheet("/resources/images/charMap.png", new Spritesheet(AssetPool.getTexture("/resources/images/charMap.png"),32, 32, 128, 0));
}
@Override
public void update(float dt) {
if (!dataInit) {
dataInit = true;
DataRunner data = new DataRunner();
data.start();
}
for (GameObject go : this.gameObjects) {
go.update(dt);
}
this.renderer.render();
if (dataFinish) {
Window.finishInit();
}
}
}
@@ -1,105 +0,0 @@
package WS3000.weatherstar3000;
import org.json.JSONArray;
import org.json.JSONObject;
import util.Utilities;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.Arrays;
public class LocalForecast extends Thread {
ArrayList<String> bulletin = new ArrayList<>();
ArrayList<String> forecastOne = new ArrayList<>();
ArrayList<String> forecastTwo = new ArrayList<>();
ArrayList<String> forecastThree = new ArrayList<>();
Utilities utl = new Utilities();
ArrayList<String> getForecast(String icaoCode, String key, int forecastId) {
ArrayList<String> words = new ArrayList<>();
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/forecast/daily/7day?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
words.add("NO REPORT");
return words;
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
JSONObject dpData = JSONResponse.getJSONArray("daypart").getJSONObject(0);
int bump = dpData.getJSONArray("dayOrNight").isNull(0) ? 1 : 0;
String fullText = dpData.getJSONArray("daypartName").getString(forecastId + bump).replaceAll("Tomorrow", JSONResponse.getJSONArray("dayOfWeek").getString(bump)).toUpperCase() +
"..." +
dpData.getJSONArray("narrative").getString(forecastId + bump).toUpperCase();
String[] splitwords = fullText.split("\\s+");
words.addAll(Arrays.asList(splitwords));
return words;
} catch (Exception e) {
e.printStackTrace();
words.clear();
words.add("NO REPORT");
return words;
}
}
ArrayList<String> getBulletin(String key, String lat, String lon) {
ArrayList<String> words = new ArrayList<>();
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/alerts/headlines?geocode=" + lat + "," + lon + "&format=json&language=en-US&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
words.add("NOBULLETIN");
return words;
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
JSONArray alertData = JSONResponse.getJSONArray("alerts");
StringBuilder fullText = new StringBuilder();
for (int i = 0; i < alertData.length(); i++) {
if (utl.isHeadline(alertData.getJSONObject(i).getString("eventDescription"))) {
if (!fullText.isEmpty()) {fullText.append(" *NEWLINE* ");}
fullText.append(alertData.getJSONObject(i).getString("headlineText").toUpperCase());
}
}
String[] splitwords = fullText.toString().split("\\s+");
words.addAll(Arrays.asList(splitwords));
return words;
} catch (Exception e) {
e.printStackTrace();
words.clear();
words.add("NOBULLETIN");
return words;
}
}
public void run() {
String mainIcao = Main.mainIcao;
String key = Main.key;
String mainLat = Main.mainLat;
String mainLon = Main.mainLon;
Main.localForecast.bulletin = getBulletin(key, mainLat, mainLon);
Main.localForecast.forecastOne = getForecast(mainIcao, key, 0);
Main.localForecast.forecastTwo = getForecast(mainIcao, key, 1);
Main.localForecast.forecastThree = getForecast(mainIcao, key, 2);
}
}
@@ -1,938 +0,0 @@
package WS3000.weatherstar3000;
import org.json.JSONException;
import org.json.JSONObject;
import util.Utilities;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.net.URISyntaxException;
public class Main {
static String[] slidesList;
static ArrayList<String> ldlList = new ArrayList<>(Arrays.asList("cityname", "condition", "temperature", "humidity", "pressure", "wind", "visibility", "precip"));
static boolean settingsErrorThrown = false;
static ArrayList<String> settingsErrorReasons = new ArrayList<>();
static String popupErrors = "";
static boolean loopSlides = false;
static boolean greenScreen = false;
static String key;
static String mainIcao;
static String mainLon;
static String mainLat;
static String todayMonth;
static String todayDay;
static int simWidth;
static int simHeight;
static boolean fullscreen = false;
// static String mainName;
static DataRunner dr;
static CurrentConditions currentConditions;
static HourlyObservations hourlyObservations;
static RegionalConditions regionalConditions;
static LocalForecast localForecast;
static Almanac almanac;
static RegionalForecast regionalForecast;
static ExtendedForecast extendedForecast;
static Outlook outlook;
static TravelForecast travelForecast;
static Bulletin bulletin;
static ArrayList<String> nearNames = new ArrayList<>();
static ArrayList<String> nearIcaos = new ArrayList<>();
static ArrayList<String> regConNames = new ArrayList<>();
static ArrayList<String> regConIcaos = new ArrayList<>();
static ArrayList<String> regForNames = new ArrayList<>();
static ArrayList<String> regForIcaos = new ArrayList<>();
static JFrame settingsWindow;
static String adCrawl;
static String jarFolder = "";
static JTextField mainLocName;
public static void main(String[] args) throws InterruptedException {
try {
String jarPath = Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
File jarFile = new File(jarPath);
jarFolder = jarFile.getParent();
} catch (URISyntaxException e) {
e.printStackTrace();
jarFolder = "error";
}
settingsWindow = new JFrame("WeatherSTAR 3000 Settings");
settingsWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
settingsWindow.setSize(540, 350);
settingsWindow.setLocationRelativeTo(null);
settingsWindow.setResizable(false);
ImageIcon sfIcon = new ImageIcon(Main.class.getResource("/resources/images/icon.png"));
settingsWindow.setIconImage(sfIcon.getImage());
JPanel settingsFrame = new JPanel();
settingsFrame.setPreferredSize(new Dimension(540, 840));
settingsFrame.setLayout(new FlowLayout(FlowLayout.LEADING));
// read
File loadDataFile = new File(jarFolder + "/loadData.txt");
ArrayList<String> loadDataLines = new ArrayList<>();
// info
settingsFrame.add(new JLabel("***Maximum location name length: 14 characters, 19 for Regional Con***"));// 19
// if
// regional
// conditions
// api key
settingsFrame.add(new JLabel("api,weather.com IBM api key"));
JTextField apiKeyText = new JTextField(20);
settingsFrame.add(apiKeyText);
// main location
settingsFrame.add(new JLabel("Main Location ICAO Code and Name"));
JTextField mainLocIcaoCode = new JTextField(4);
settingsFrame.add(mainLocIcaoCode);
mainLocName = new JTextField(14);
settingsFrame.add(mainLocName);
// spacer
JPanel firstSpacer = new JPanel();
firstSpacer.setPreferredSize(new Dimension(480, 10));
settingsFrame.add(firstSpacer);
// nearby locations
settingsFrame.add(new JLabel("Nearby Location One ICAO Code and Name"));
JTextField nearLocOneIcaoCode = new JTextField(4);
settingsFrame.add(nearLocOneIcaoCode);
JTextField nearLocOneName = new JTextField(14);
settingsFrame.add(nearLocOneName);
settingsFrame.add(new JLabel("Nearby Location Two ICAO Code and Name"));
JTextField nearLocTwoIcaoCode = new JTextField(4);
settingsFrame.add(nearLocTwoIcaoCode);
JTextField nearLocTwoName = new JTextField(14);
settingsFrame.add(nearLocTwoName);
settingsFrame.add(new JLabel("Nearby Location Three ICAO Code and Name"));
JTextField nearLocThreeIcaoCode = new JTextField(4);
settingsFrame.add(nearLocThreeIcaoCode);
JTextField nearLocThreeName = new JTextField(14);
settingsFrame.add(nearLocThreeName);
settingsFrame.add(new JLabel("Nearby Location Four ICAO Code and Name"));
JTextField nearLocFourIcaoCode = new JTextField(4);
settingsFrame.add(nearLocFourIcaoCode);
JTextField nearLocFourName = new JTextField(14);
settingsFrame.add(nearLocFourName);
settingsFrame.add(new JLabel("Nearby Location Five ICAO Code and Name"));
JTextField nearLocFiveIcaoCode = new JTextField(4);
settingsFrame.add(nearLocFiveIcaoCode);
JTextField nearLocFiveName = new JTextField(14);
settingsFrame.add(nearLocFiveName);
settingsFrame.add(new JLabel("Nearby Location Six ICAO Code and Name"));
JTextField nearLocSixIcaoCode = new JTextField(4);
settingsFrame.add(nearLocSixIcaoCode);
JTextField nearLocSixName = new JTextField(14);
settingsFrame.add(nearLocSixName);
settingsFrame.add(new JLabel("Nearby Location Seven ICAO Code and Name"));
JTextField nearLocSevenIcaoCode = new JTextField(4);
settingsFrame.add(nearLocSevenIcaoCode);
JTextField nearLocSevenName = new JTextField(14);
settingsFrame.add(nearLocSevenName);
// spacer
JPanel secondSpacer = new JPanel();
secondSpacer.setPreferredSize(new Dimension(480, 10));
settingsFrame.add(secondSpacer);
// nearby locations
settingsFrame.add(new JLabel("Regional Conditions One ICAO Code and Name"));
JTextField regConOneIcaoCode = new JTextField(4);
settingsFrame.add(regConOneIcaoCode);
JTextField regConOneName = new JTextField(14);
settingsFrame.add(regConOneName);
settingsFrame.add(new JLabel("Regional Conditions Two ICAO Code and Name"));
JTextField regConTwoIcaoCode = new JTextField(4);
settingsFrame.add(regConTwoIcaoCode);
JTextField regConTwoName = new JTextField(14);
settingsFrame.add(regConTwoName);
settingsFrame.add(new JLabel("Regional Conditions Three ICAO Code and Name"));
JTextField regConThreeIcaoCode = new JTextField(4);
settingsFrame.add(regConThreeIcaoCode);
JTextField regConThreeName = new JTextField(14);
settingsFrame.add(regConThreeName);
settingsFrame.add(new JLabel("Regional Conditions Four ICAO Code and Name"));
JTextField regConFourIcaoCode = new JTextField(4);
settingsFrame.add(regConFourIcaoCode);
JTextField regConFourName = new JTextField(14);
settingsFrame.add(regConFourName);
settingsFrame.add(new JLabel("Regional Conditions Five ICAO Code and Name"));
JTextField regConFiveIcaoCode = new JTextField(4);
settingsFrame.add(regConFiveIcaoCode);
JTextField regConFiveName = new JTextField(14);
settingsFrame.add(regConFiveName);
settingsFrame.add(new JLabel("Regional Conditions Six ICAO Code and Name"));
JTextField regConSixIcaoCode = new JTextField(4);
settingsFrame.add(regConSixIcaoCode);
JTextField regConSixName = new JTextField(14);
settingsFrame.add(regConSixName);
settingsFrame.add(new JLabel("Regional Conditions Seven ICAO Code and Name"));
JTextField regConSevenIcaoCode = new JTextField(4);
settingsFrame.add(regConSevenIcaoCode);
JTextField regConSevenName = new JTextField(14);
settingsFrame.add(regConSevenName);
// spacer
JPanel thirdSpacer = new JPanel();
thirdSpacer.setPreferredSize(new Dimension(480, 10));
settingsFrame.add(thirdSpacer);
// nearby locations
settingsFrame.add(new JLabel("Regional Forecast One ICAO Code and Name"));
JTextField regForOneIcaoCode = new JTextField(4);
settingsFrame.add(regForOneIcaoCode);
JTextField regForOneName = new JTextField(14);
settingsFrame.add(regForOneName);
settingsFrame.add(new JLabel("Regional Forecast Two ICAO Code and Name"));
JTextField regForTwoIcaoCode = new JTextField(4);
settingsFrame.add(regForTwoIcaoCode);
JTextField regForTwoName = new JTextField(14);
settingsFrame.add(regForTwoName);
settingsFrame.add(new JLabel("Regional Forecast Three ICAO Code and Name"));
JTextField regForThreeIcaoCode = new JTextField(4);
settingsFrame.add(regForThreeIcaoCode);
JTextField regForThreeName = new JTextField(14);
settingsFrame.add(regForThreeName);
settingsFrame.add(new JLabel("Regional Forecast Four ICAO Code and Name"));
JTextField regForFourIcaoCode = new JTextField(4);
settingsFrame.add(regForFourIcaoCode);
JTextField regForFourName = new JTextField(14);
settingsFrame.add(regForFourName);
settingsFrame.add(new JLabel("Regional Forecast Five ICAO Code and Name"));
JTextField regForFiveIcaoCode = new JTextField(4);
settingsFrame.add(regForFiveIcaoCode);
JTextField regForFiveName = new JTextField(14);
settingsFrame.add(regForFiveName);
settingsFrame.add(new JLabel("Regional Forecast Six ICAO Code and Name"));
JTextField regForSixIcaoCode = new JTextField(4);
settingsFrame.add(regForSixIcaoCode);
JTextField regForSixName = new JTextField(14);
settingsFrame.add(regForSixName);
settingsFrame.add(new JLabel("Regional Forecast Seven ICAO Code and Name"));
JTextField regForSevenIcaoCode = new JTextField(4);
settingsFrame.add(regForSevenIcaoCode);
JTextField regForSevenName = new JTextField(14);
settingsFrame.add(regForSevenName);
JPanel aSpacer = new JPanel();
aSpacer.setPreferredSize(new Dimension(500, 10));
settingsFrame.add(aSpacer);
settingsFrame.add(new JLabel("Ad crawl message"));
JTextField adCrawlInput = new JTextField(32);
settingsFrame.add(adCrawlInput);
// spacer
JPanel fourthSpacer = new JPanel();
fourthSpacer.setPreferredSize(new Dimension(500, 10));
settingsFrame.add(fourthSpacer);
settingsFrame.add(new JLabel("Width"));
JTextField widthField = new JTextField(3);
settingsFrame.add(widthField);
widthField.setText("720");
settingsFrame.add(new JLabel("Height"));
JTextField heightField = new JTextField(3);
heightField.setText("480");
settingsFrame.add(heightField);
settingsFrame.add(new JLabel("Flavor"));
String[] flavorOptions = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q"};
JComboBox flavorDropdown = new JComboBox(flavorOptions);
flavorDropdown.setSelectedIndex(0);
settingsFrame.add(flavorDropdown);
settingsFrame.add(new JLabel("LDL Options"));
String[] ldlOptions = {"Observations", "Ad Crawl", "Both"};
JComboBox ldlDropdown = new JComboBox(ldlOptions);
ldlDropdown.setSelectedIndex(0);
settingsFrame.add(ldlDropdown);
JPanel fifthSpacer = new JPanel();
fifthSpacer.setPreferredSize(new Dimension(500, 10));
settingsFrame.add(fifthSpacer);
JCheckBox loopCheck = new JCheckBox("Loop");
settingsFrame.add(loopCheck);
JCheckBox gsCheck = new JCheckBox("Green Screen");
settingsFrame.add(gsCheck);
JCheckBox fsCheck = new JCheckBox("Fullscreen");
settingsFrame.add(fsCheck);
JPanel sixthSpacer = new JPanel();
sixthSpacer.setPreferredSize(new Dimension(500, 10));
settingsFrame.add(sixthSpacer);
JButton doneButton = new JButton("Run");
settingsFrame.add(doneButton);
JButton saveButton = new JButton("Save Config");
settingsFrame.add(saveButton);
JButton loadButton = new JButton("Load Config");
settingsFrame.add(loadButton);
try (Scanner myReader = new Scanner(loadDataFile)) {
while (myReader.hasNextLine()) {
loadDataLines.add(myReader.nextLine());
}
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(settingsFrame, "Unable to read previous data.");
}
apiKeyText.setText(loadDataLines.get(0));
mainLocIcaoCode.setText(loadDataLines.get(1));
mainLocName.setText(loadDataLines.get(2));
nearLocOneIcaoCode.setText(loadDataLines.get(3));
nearLocOneName.setText(loadDataLines.get(4));
nearLocTwoIcaoCode.setText(loadDataLines.get(5));
nearLocTwoName.setText(loadDataLines.get(6));
nearLocThreeIcaoCode.setText(loadDataLines.get(7));
nearLocThreeName.setText(loadDataLines.get(8));
nearLocFourIcaoCode.setText(loadDataLines.get(9));
nearLocFourName.setText(loadDataLines.get(10));
nearLocFiveIcaoCode.setText(loadDataLines.get(11));
nearLocFiveName.setText(loadDataLines.get(12));
nearLocSixIcaoCode.setText(loadDataLines.get(13));
nearLocSixName.setText(loadDataLines.get(14));
nearLocSevenIcaoCode.setText(loadDataLines.get(15));
nearLocSevenName.setText(loadDataLines.get(16));
regConOneIcaoCode.setText(loadDataLines.get(17));
regConOneName.setText(loadDataLines.get(18));
regConTwoIcaoCode.setText(loadDataLines.get(19));
regConTwoName.setText(loadDataLines.get(20));
regConThreeIcaoCode.setText(loadDataLines.get(21));
regConThreeName.setText(loadDataLines.get(22));
regConFourIcaoCode.setText(loadDataLines.get(23));
regConFourName.setText(loadDataLines.get(24));
regConFiveIcaoCode.setText(loadDataLines.get(25));
regConFiveName.setText(loadDataLines.get(26));
regConSixIcaoCode.setText(loadDataLines.get(27));
regConSixName.setText(loadDataLines.get(28));
regConSevenIcaoCode.setText(loadDataLines.get(29));
regConSevenName.setText(loadDataLines.get(30));
regForOneIcaoCode.setText(loadDataLines.get(31));
regForOneName.setText(loadDataLines.get(32));
regForTwoIcaoCode.setText(loadDataLines.get(33));
regForTwoName.setText(loadDataLines.get(34));
regForThreeIcaoCode.setText(loadDataLines.get(35));
regForThreeName.setText(loadDataLines.get(36));
regForFourIcaoCode.setText(loadDataLines.get(37));
regForFourName.setText(loadDataLines.get(38));
regForFiveIcaoCode.setText(loadDataLines.get(39));
regForFiveName.setText(loadDataLines.get(40));
regForSixIcaoCode.setText(loadDataLines.get(41));
regForSixName.setText(loadDataLines.get(42));
regForSevenIcaoCode.setText(loadDataLines.get(43));
regForSevenName.setText(loadDataLines.get(44));
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Select a directory to save you config");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = chooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFolder = chooser.getSelectedFile();
String fileName = JOptionPane.showInputDialog(null, "Name the config file?");
// 3. Create the JSON content
String jsonContent = String.format(
"{\"starSettings\": {"
+ "\"api_key\": \"" + apiKeyText.getText() + "\","
+ "\"mainLocation\": {"
+ "\"icaoCode\": \"" + mainLocIcaoCode.getText() + "\","
+ "\"locName\": \"" + mainLocName.getText() + "\","
+ "},"
+ "\"nearbyLocations\": ["
+ "{\"icaoCode\": \"" + nearLocOneIcaoCode.getText() + "\", \"locName\": \"" + nearLocOneName.getText() + "\"},"
+ "{\"icaoCode\": \"" + nearLocTwoIcaoCode.getText() + "\", \"locName\": \"" + nearLocTwoName.getText() + "\"},"
+ "{\"icaoCode\": \"" + nearLocThreeIcaoCode.getText() + "\", \"locName\": \"" + nearLocThreeName.getText() + "\"},"
+ "{\"icaoCode\": \"" + nearLocFourIcaoCode.getText() + "\", \"locName\": \"" + nearLocFourName.getText() + "\"},"
+ "{\"icaoCode\": \"" + nearLocFiveIcaoCode.getText() + "\", \"locName\": \"" + nearLocFiveName.getText() + "\"},"
+ "{\"icaoCode\": \"" + nearLocSixIcaoCode.getText() + "\", \"locName\": \"" + nearLocSixName.getText() + "\"},"
+ "{\"icaoCode\": \"" + nearLocSevenIcaoCode.getText() + "\", \"locName\": \"" + nearLocSevenName.getText() + "\"},"
+ "],"
+ "\"regionalForecastLocations\": ["
+ "{\"icaoCode\": \"" + regForOneIcaoCode.getText() + "\", \"locName\": \"" + regForOneName.getText() + "\"},"
+ "{\"icaoCode\": \"" + regForTwoIcaoCode.getText() + "\", \"locName\": \"" + regForTwoName.getText() + "\"},"
+ "{\"icaoCode\": \"" + regForThreeIcaoCode.getText() + "\", \"locName\": \"" + regForThreeName.getText() + "\"},"
+ "{\"icaoCode\": \"" + regForFourIcaoCode.getText() + "\", \"locName\": \"" + regForFourName.getText() + "\"},"
+ "{\"icaoCode\": \"" + regForFiveIcaoCode.getText() + "\", \"locName\": \"" + regForFiveName.getText() + "\"},"
+ "{\"icaoCode\": \"" + regForSixIcaoCode.getText() + "\", \"locName\": \"" + regForSixName.getText() + "\"},"
+ "{\"icaoCode\": \"" + regForSevenIcaoCode.getText() + "\", \"locName\": \"" + regForSevenName.getText() + "\"},"
+ "],"
+ "\"regionalConditionsLocations\": ["
+ "{\"icaoCode\": \"" + regConOneIcaoCode.getText() + "\", \"locName\": \"" + regConOneName.getText() + "\"},"
+ "{\"icaoCode\": \"" + regConTwoIcaoCode.getText() + "\", \"locName\": \"" + regConTwoName.getText() + "\"},"
+ "{\"icaoCode\": \"" + regConThreeIcaoCode.getText() + "\", \"locName\": \"" + regConThreeName.getText() + "\"},"
+ "{\"icaoCode\": \"" + regConFourIcaoCode.getText() + "\", \"locName\": \"" + regConFourName.getText() + "\"},"
+ "{\"icaoCode\": \"" + regConFiveIcaoCode.getText() + "\", \"locName\": \"" + regConFiveName.getText() + "\"},"
+ "{\"icaoCode\": \"" + regConSixIcaoCode.getText() + "\", \"locName\": \"" + regConSixName.getText() + "\"},"
+ "{\"icaoCode\": \"" + regConSevenIcaoCode.getText() + "\", \"locName\": \"" + regConSevenName.getText() + "\"},"
+ "],"
+ "}}"
);
// 4. Save to the folder
if (fileName != null && !fileName.trim().isEmpty()) {
if (!fileName.endsWith(".json")) fileName += ".json";
} else {
fileName = "myConfig.json";
}
File fileToSave = new File(selectedFolder, fileName);
try (FileWriter writer = new FileWriter(fileToSave)) {
writer.write(jsonContent);
JOptionPane.showMessageDialog(null, "Saved to: " + fileToSave.getAbsolutePath());
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(settingsFrame, "Error saving config file.");
}
}
}
});
loadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser openFile = new JFileChooser();
int returnval = openFile.showOpenDialog(null);
File loadedFile = openFile.getSelectedFile();
Path filePath;
String absFilePath;
String loadedExtension;
if (returnval == JFileChooser.APPROVE_OPTION) {
filePath = Paths.get(loadedFile.getAbsolutePath());
absFilePath = loadedFile.getAbsolutePath();
try {
loadedExtension = Files.probeContentType(filePath);
} catch (IOException ex) {
loadedExtension = "error";
}
if (!loadedExtension.equals("application/json")) {
JOptionPane.showMessageDialog(settingsFrame, "Please choose a json file.");
} else {
StringBuilder jsonText = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(absFilePath));
String line;
while ((line = br.readLine()) != null) {
jsonText.append(line).append("\n");
}
br.close();
JSONObject settingsObj = new JSONObject(jsonText.toString()).getJSONObject("starSettings");
// api key
apiKeyText.setText(settingsObj.getString("api_key"));
// main location
mainLocIcaoCode.setText(settingsObj.getJSONObject("mainLocation").getString("icaoCode"));
mainLocName.setText(settingsObj.getJSONObject("mainLocation").getString("locName"));
// nearby cities
nearLocOneIcaoCode.setText(
settingsObj.getJSONArray("nearbyLocations").getJSONObject(0).getString("icaoCode"));
nearLocOneName.setText(
settingsObj.getJSONArray("nearbyLocations").getJSONObject(0).getString("locName"));
nearLocTwoIcaoCode.setText(
settingsObj.getJSONArray("nearbyLocations").getJSONObject(1).getString("icaoCode"));
nearLocTwoName.setText(
settingsObj.getJSONArray("nearbyLocations").getJSONObject(1).getString("locName"));
nearLocThreeIcaoCode.setText(
settingsObj.getJSONArray("nearbyLocations").getJSONObject(2).getString("icaoCode"));
nearLocThreeName.setText(
settingsObj.getJSONArray("nearbyLocations").getJSONObject(2).getString("locName"));
nearLocFourIcaoCode.setText(
settingsObj.getJSONArray("nearbyLocations").getJSONObject(3).getString("icaoCode"));
nearLocFourName.setText(
settingsObj.getJSONArray("nearbyLocations").getJSONObject(3).getString("locName"));
nearLocFiveIcaoCode.setText(
settingsObj.getJSONArray("nearbyLocations").getJSONObject(4).getString("icaoCode"));
nearLocFiveName.setText(
settingsObj.getJSONArray("nearbyLocations").getJSONObject(4).getString("locName"));
nearLocSixIcaoCode.setText(
settingsObj.getJSONArray("nearbyLocations").getJSONObject(5).getString("icaoCode"));
nearLocSixName.setText(
settingsObj.getJSONArray("nearbyLocations").getJSONObject(5).getString("locName"));
nearLocSevenIcaoCode.setText(
settingsObj.getJSONArray("nearbyLocations").getJSONObject(6).getString("icaoCode"));
nearLocSevenName.setText(
settingsObj.getJSONArray("nearbyLocations").getJSONObject(6).getString("locName"));
// regional conditions
regConOneIcaoCode.setText(settingsObj.getJSONArray("regionalConditionsLocations")
.getJSONObject(0).getString("icaoCode"));
regConOneName.setText(settingsObj.getJSONArray("regionalConditionsLocations")
.getJSONObject(0).getString("locName"));
regConTwoIcaoCode.setText(settingsObj.getJSONArray("regionalConditionsLocations")
.getJSONObject(1).getString("icaoCode"));
regConTwoName.setText(settingsObj.getJSONArray("regionalConditionsLocations")
.getJSONObject(1).getString("locName"));
regConThreeIcaoCode.setText(settingsObj.getJSONArray("regionalConditionsLocations")
.getJSONObject(2).getString("icaoCode"));
regConThreeName.setText(settingsObj.getJSONArray("regionalConditionsLocations")
.getJSONObject(2).getString("locName"));
regConFourIcaoCode.setText(settingsObj.getJSONArray("regionalConditionsLocations")
.getJSONObject(3).getString("icaoCode"));
regConFourName.setText(settingsObj.getJSONArray("regionalConditionsLocations")
.getJSONObject(3).getString("locName"));
regConFiveIcaoCode.setText(settingsObj.getJSONArray("regionalConditionsLocations")
.getJSONObject(4).getString("icaoCode"));
regConFiveName.setText(settingsObj.getJSONArray("regionalConditionsLocations")
.getJSONObject(4).getString("locName"));
regConSixIcaoCode.setText(settingsObj.getJSONArray("regionalConditionsLocations")
.getJSONObject(5).getString("icaoCode"));
regConSixName.setText(settingsObj.getJSONArray("regionalConditionsLocations")
.getJSONObject(5).getString("locName"));
regConSevenIcaoCode.setText(settingsObj.getJSONArray("regionalConditionsLocations")
.getJSONObject(6).getString("icaoCode"));
regConSevenName.setText(settingsObj.getJSONArray("regionalConditionsLocations")
.getJSONObject(6).getString("locName"));
// regional forecast
regForOneIcaoCode.setText(settingsObj.getJSONArray("regionalForecastLocations")
.getJSONObject(0).getString("icaoCode"));
regForOneName.setText(settingsObj.getJSONArray("regionalForecastLocations").getJSONObject(0)
.getString("locName"));
regForTwoIcaoCode.setText(settingsObj.getJSONArray("regionalForecastLocations")
.getJSONObject(1).getString("icaoCode"));
regForTwoName.setText(settingsObj.getJSONArray("regionalForecastLocations").getJSONObject(1)
.getString("locName"));
regForThreeIcaoCode.setText(settingsObj.getJSONArray("regionalForecastLocations")
.getJSONObject(2).getString("icaoCode"));
regForThreeName.setText(settingsObj.getJSONArray("regionalForecastLocations")
.getJSONObject(2).getString("locName"));
regForFourIcaoCode.setText(settingsObj.getJSONArray("regionalForecastLocations")
.getJSONObject(3).getString("icaoCode"));
regForFourName.setText(settingsObj.getJSONArray("regionalForecastLocations")
.getJSONObject(3).getString("locName"));
regForFiveIcaoCode.setText(settingsObj.getJSONArray("regionalForecastLocations")
.getJSONObject(4).getString("icaoCode"));
regForFiveName.setText(settingsObj.getJSONArray("regionalForecastLocations")
.getJSONObject(4).getString("locName"));
regForSixIcaoCode.setText(settingsObj.getJSONArray("regionalForecastLocations")
.getJSONObject(5).getString("icaoCode"));
regForSixName.setText(settingsObj.getJSONArray("regionalForecastLocations").getJSONObject(5)
.getString("locName"));
regForSevenIcaoCode.setText(settingsObj.getJSONArray("regionalForecastLocations")
.getJSONObject(6).getString("icaoCode"));
regForSevenName.setText(settingsObj.getJSONArray("regionalForecastLocations")
.getJSONObject(6).getString("locName"));
// after all of that, change the base config json that loads on start
String dataFilePath = jarFolder + "/loadData.txt";
String content = apiKeyText.getText() + "\n" + mainLocIcaoCode.getText() + "\n"
+ mainLocName.getText() + "\n" + nearLocOneIcaoCode.getText() + "\n"
+ nearLocOneName.getText() + "\n" + nearLocTwoIcaoCode.getText() + "\n"
+ nearLocTwoName.getText() + "\n" + nearLocThreeIcaoCode.getText() + "\n"
+ nearLocThreeName.getText() + "\n" + nearLocFourIcaoCode.getText() + "\n"
+ nearLocFourName.getText() + "\n" + nearLocFiveIcaoCode.getText() + "\n"
+ nearLocFiveName.getText() + "\n" + nearLocSixIcaoCode.getText() + "\n"
+ nearLocSixName.getText() + "\n" + nearLocSevenIcaoCode.getText() + "\n"
+ nearLocSevenName.getText() + "\n" + regConOneIcaoCode.getText() + "\n"
+ regConOneName.getText() + "\n" + regConTwoIcaoCode.getText() + "\n"
+ regConTwoName.getText() + "\n" + regConThreeIcaoCode.getText() + "\n"
+ regConThreeName.getText() + "\n" + regConFourIcaoCode.getText() + "\n"
+ regConFourName.getText() + "\n" + regConFiveIcaoCode.getText() + "\n"
+ regConFiveName.getText() + "\n" + regConSixIcaoCode.getText() + "\n"
+ regConSixName.getText() + "\n" + regConSevenIcaoCode.getText() + "\n"
+ regConSevenName.getText() + "\n" + regForOneIcaoCode.getText() + "\n"
+ regForOneName.getText() + "\n" + regForTwoIcaoCode.getText() + "\n"
+ regForTwoName.getText() + "\n" + regForThreeIcaoCode.getText() + "\n"
+ regForThreeName.getText() + "\n" + regForFourIcaoCode.getText() + "\n"
+ regForFourName.getText() + "\n" + regForFiveIcaoCode.getText() + "\n"
+ regForFiveName.getText() + "\n" + regForSixIcaoCode.getText() + "\n"
+ regForSixName.getText() + "\n" + regForSevenIcaoCode.getText() + "\n"
+ regForSevenName.getText() + "\n";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(dataFilePath))) {
writer.write(content);
writer.close();
} catch (IOException y) {
y.printStackTrace();
JOptionPane.showMessageDialog(settingsFrame,
"Error saving loaded config data to program. Config will not load on next startup.");
}
} catch (JSONException ex) {
JOptionPane.showMessageDialog(settingsFrame,
"Unable to read loaded configuration file, please choose a valid file.");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
}
});
doneButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loopSlides = loopCheck.isSelected();
greenScreen = gsCheck.isSelected();
fullscreen = fsCheck.isSelected();
key = apiKeyText.getText();
mainIcao = mainLocIcaoCode.getText();
/*
if (!checkIcaoCode(mainIcao, key).equals("noerror")) {
settingsErrorThrown = true;
settingsErrorReasons.add("\nMain Location Error: " + checkIcaoCode(mainIcao, key));
}
*/
nearIcaos.add(nearLocOneIcaoCode.getText());
nearIcaos.add(nearLocTwoIcaoCode.getText());
nearIcaos.add(nearLocThreeIcaoCode.getText());
nearIcaos.add(nearLocFourIcaoCode.getText());
nearIcaos.add(nearLocFiveIcaoCode.getText());
nearIcaos.add(nearLocSixIcaoCode.getText());
nearIcaos.add(nearLocSevenIcaoCode.getText());
nearNames.add(nearLocOneName.getText());
nearNames.add(nearLocTwoName.getText());
nearNames.add(nearLocThreeName.getText());
nearNames.add(nearLocFourName.getText());
nearNames.add(nearLocFiveName.getText());
nearNames.add(nearLocSixName.getText());
nearNames.add(nearLocSevenName.getText());
/*
for (int i = 0; i < nearIcaos.size(); i++) {
if (!checkIcaoCode(nearIcaos.get(i), key).equals("noerror")) {
settingsErrorThrown = true;
settingsErrorReasons
.add("\nNear Location " + i + " Error: " + checkIcaoCode(nearIcaos.get(i), key));
}
}
*/
regConIcaos.add(regConOneIcaoCode.getText());
regConIcaos.add(regConTwoIcaoCode.getText());
regConIcaos.add(regConThreeIcaoCode.getText());
regConIcaos.add(regConFourIcaoCode.getText());
regConIcaos.add(regConFiveIcaoCode.getText());
regConIcaos.add(regConSixIcaoCode.getText());
regConIcaos.add(regConSevenIcaoCode.getText());
regConNames.add(regConOneName.getText());
regConNames.add(regConTwoName.getText());
regConNames.add(regConThreeName.getText());
regConNames.add(regConFourName.getText());
regConNames.add(regConFiveName.getText());
regConNames.add(regConSixName.getText());
regConNames.add(regConSevenName.getText());
/*
for (int i = 0; i < regConIcaos.size(); i++) {
if (!checkIcaoCode(regConIcaos.get(i), key).equals("noerror")) {
settingsErrorThrown = true;
settingsErrorReasons.add(
"\nRegional Conditions Loc " + i + " Error: " + checkIcaoCode(regConIcaos.get(i), key));
}
}*/
regForIcaos.add(regForOneIcaoCode.getText());
regForIcaos.add(regForTwoIcaoCode.getText());
regForIcaos.add(regForThreeIcaoCode.getText());
regForIcaos.add(regForFourIcaoCode.getText());
regForIcaos.add(regForFiveIcaoCode.getText());
regForIcaos.add(regForSixIcaoCode.getText());
regForIcaos.add(regForSevenIcaoCode.getText());
regForNames.add(regForOneName.getText());
regForNames.add(regForTwoName.getText());
regForNames.add(regForThreeName.getText());
regForNames.add(regForFourName.getText());
regForNames.add(regForFiveName.getText());
regForNames.add(regForSixName.getText());
regForNames.add(regForSevenName.getText());
adCrawl = adCrawlInput.getText();
/*
for (int i = 0; i < regForIcaos.size(); i++) {
if (!checkIcaoCode(regForIcaos.get(i), key).equals("noerror")) {
settingsErrorThrown = true;
settingsErrorReasons
.add("\nRegional Forecast Loc " + i + " Error: " + checkIcaoCode(regForIcaos.get(i), key));
}
}
*/
WindowRunner wr = new WindowRunner();
//dr = new DataRunner();
/*currentConditions = new CurrentConditions();
hourlyObservations = new HourlyObservations();
regionalConditions = new RegionalConditions();
localForecast = new LocalForecast();
almanac = new Almanac();
regionalForecast = new RegionalForecast();
extendedForecast = new ExtendedForecast();*/
/*if (settingsErrorThrown) {
for (int i = 0; i < settingsErrorReasons.size(); i++) {
popupErrors = popupErrors + settingsErrorReasons.get(i);
}
JOptionPane.showMessageDialog(settingsFrame, "The following errors have occured: " + popupErrors);
mainLat = "error";
mainLon = "error";
todayMonth = "error";
todayDay = "error";
*///} else {
// after checking for icao code and key errors, get data
//}
// get cc data
String ldltype = (String) ldlDropdown.getSelectedItem();
switch (ldltype) {
case "Observations":
SlidesRunner.ccType = "obs";
break;
case "Ad Crawl":
SlidesRunner.ccType = "crawl";
break;
case "Both":
SlidesRunner.ccType = "both";
break;
default:
System.out.println("Invalid LDL Option");
break;
}
String selectedFlavor = (String) flavorDropdown.getSelectedItem();
switch (selectedFlavor) {
case "A":
slidesList = Utilities.flavorA;
break;
case "B":
slidesList = Utilities.flavorB;
break;
case "C":
slidesList = Utilities.flavorC;
break;
case "D":
slidesList = Utilities.flavorD;
break;
case "E":
slidesList = Utilities.flavorE;
break;
case "F":
slidesList = Utilities.flavorF;
break;
case "G":
slidesList = Utilities.flavorG;
break;
case "H":
slidesList = Utilities.flavorH;
break;
case "I":
slidesList = Utilities.flavorI;
break;
case "J":
slidesList = Utilities.flavorJ;
break;
case "K":
slidesList = Utilities.flavorK;
break;
case "L":
slidesList = Utilities.flavorL;
break;
case "M":
slidesList = Utilities.flavorM;
break;
case "N":
slidesList = Utilities.flavorN;
break;
case "O":
slidesList = Utilities.flavorO;
break;
case "P":
slidesList = Utilities.flavorP;
break;
case "Q":
slidesList = Utilities.flavorQ;
break;
default:
System.out.println("Invalid flavor");
break;
}
//slidesList = Utilities.testFlavor;
simWidth = Integer.parseInt(widthField.getText());
simHeight = Integer.parseInt(heightField.getText());
mainLat = icaoToLat(mainIcao, key);
mainLon = icaoToLon(mainIcao, key);
almanac = new Almanac();
todayMonth = almanac.getMonth(mainIcao, key);
todayDay = almanac.getDayDate(mainIcao, key);
/*currentConditions.start();
hourlyObservations.start();
regionalConditions.start();
localForecast.start();
almanac.start();
regionalForecast.start();
extendedForecast.start();
try {
currentConditions.join();
hourlyObservations.join();
regionalConditions.join();
localForecast.join();
almanac.join();
regionalForecast.join();
extendedForecast.join();
//wr.join();
} catch (InterruptedException e1) {
e1.printStackTrace();
}*/
//dr.run();
wr.start();
// flavor manager
// after all data, checks, and flavor management
/*
settingsWindow.setVisible(false);
//BlueWindow blueWindow = new BlueWindow();
//LDLRunner lr = new LDLRunner();
//lr.start();
//BlueRunner br = new BlueRunner();
//br.start();
*/
//settingsWindow.setVisible(false);
//Window window = Window.get();
//window.runWindow();
settingsErrorThrown = false;
settingsErrorReasons.clear();
popupErrors = "";
}
});
JScrollPane settingsScrollFrame = new JScrollPane(settingsFrame);
settingsScrollFrame.getVerticalScrollBar().setUnitIncrement(16);
settingsScrollFrame.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
settingsScrollFrame.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
settingsWindow.add(settingsScrollFrame);
settingsWindow.setVisible(true);
}
static String checkIcaoCode(String code, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/location/point?icaoCode=" + code
+ "&language=en-US&format=json&apiKey=" + key))
.GET() // Or .POST(HttpRequest.BodyPublishers.ofString("your_json_body"))
.header("Accept", "application/json").build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
if (Response.statusCode() == 401) {
return "API Key error";
} else {
return "Invalid ICAO Code";
}
}
return "noerror";
} catch (Exception e) {
e.printStackTrace();
return "Server Error";
}
}
static String icaoToLat(String code, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/location/point?icaoCode=" + code
+ "&language=en-US&format=json&apiKey=" + key))
.GET() // Or .POST(HttpRequest.BodyPublishers.ofString("your_json_body"))
.header("Accept", "application/json").build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
JSONObject locationObject = JSONResponse.getJSONObject("location");
return Float.toString(locationObject.getFloat("latitude"));
} catch (Exception e) {
e.printStackTrace();
return "Server Error";
}
}
static String icaoToLon(String code, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/location/point?icaoCode=" + code
+ "&language=en-US&format=json&apiKey=" + key))
.GET() // Or .POST(HttpRequest.BodyPublishers.ofString("your_json_body"))
.header("Accept", "application/json").build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
JSONObject locationObject = JSONResponse.getJSONObject("location");
return Float.toString(locationObject.getFloat("longitude"));
} catch (Exception e) {
e.printStackTrace();
return "Server Error";
}
}
}
@@ -1,98 +0,0 @@
package WS3000.weatherstar3000;
import static org.lwjgl.glfw.GLFW.*;
public class MouseListener {
private static MouseListener instance;
private double scrollX, scrollY;
private double xPos, yPos, lastX, lastY;
private boolean mouseButtonPressed[] = new boolean[3];
private boolean isDragging;
private MouseListener() {
this.scrollX = 0.0;
this.scrollY = 0.0;
this.xPos = 0.0;
this.yPos = 9.0;
this.lastX = 0.0;
this.lastY = 0.0;
}
public static MouseListener get() {
if (MouseListener.instance == null) {
MouseListener.instance = new MouseListener();
}
return MouseListener.instance;
}
public static void mousePosCallback(long window, double xpos, double ypos) {
get().lastX = get().xPos;
get().lastY = get().yPos;
get().xPos = xpos;
get().yPos = ypos;
get().isDragging = get().mouseButtonPressed[0] || get().mouseButtonPressed[1] || get().mouseButtonPressed[2];
}
public static void mouseButtonCallback(long window, int button, int action, int mods) {
if (action == GLFW_PRESS) {
if (button < get().mouseButtonPressed.length) {
get().mouseButtonPressed[button] = true;
}
} else if (action == GLFW_RELEASE) {
if (button < get().mouseButtonPressed.length) {
get().mouseButtonPressed[button] = false;
get().isDragging = false;
}
}
}
public static void mouseScrollCallback(long window, double xOffset, double yOffset) {
get().scrollX = xOffset;
get().scrollY = yOffset;
}
public static void endFrame() {
get().scrollX = 0;
get().scrollY = 0;
get().lastX = get().xPos;
get().lastY = get().yPos;
}
public static float getX() {
return (float)get().xPos;
}
public static float getY() {
return (float)get().yPos;
}
public static float getDx() {
return (float)(get().lastX - get().xPos);
}
public static float getDy() {
return (float)(get().lastY - get().yPos);
}
public static float getScrollX() {
return (float)get().scrollX;
}
public static float getScrollY() {
return (float)get().scrollY;
}
public static boolean isDragging() {
return get().isDragging;
}
public static boolean mouseButtonDown(int button) {
if (button < get().mouseButtonPressed.length) {
return get().mouseButtonPressed[button];
} else {
return false;
}
}
}
@@ -1,35 +0,0 @@
package WS3000.weatherstar3000;
//import java.net.URI;
//import java.net.http.HttpClient;
//import java.net.http.HttpRequest;
//import java.net.http.HttpResponse;
import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList;
import util.Utilities;
//import org.json.JSONObject;
public class Outlook extends Thread {
static Utilities utl = new Utilities();
String month;
ArrayList<String> outlook = new ArrayList<>();
String getMonth() {
LocalDate cdate = LocalDate.now();
Month cmonth = cdate.getMonth();
return cmonth.name().toUpperCase();
}
ArrayList<String> getOutlook() {
ArrayList<String> outlook = new ArrayList<>();
outlook.add("NO");
outlook.add("REPORT");
return outlook;
}
public void run() {
Main.outlook.month = getMonth();
Main.outlook.outlook = getOutlook();
}
}
@@ -1,76 +0,0 @@
package WS3000.weatherstar3000;
import org.json.JSONObject;
import util.Utilities;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
public class RegionalConditions extends Thread {
ArrayList<String> locName = new ArrayList<>();
ArrayList<String> temperature = new ArrayList<>();
ArrayList<String> condition = new ArrayList<>();
Utilities utl = new Utilities();
String getLocName(String displayName){
return utl.ljust(displayName, 19, " ").substring(0, 19);
}
String getCondition(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/observations/current?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return "NO REPORT";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
return utl.getCondition(JSONResponse.getInt("iconCodeExtend"));
} catch (Exception e) {
e.printStackTrace();
return "NO REPORT";
}
}
String getTemperature(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/observations/current?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
return utl.rjust(Integer.toString(JSONResponse.getInt("temperature")), 3, " ");
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
public void run() {
ArrayList<String> regConNames = new ArrayList<>();
regConNames.addAll(Main.regConNames);
ArrayList<String> regConIcaos = new ArrayList<>();
regConIcaos.addAll(Main.regConIcaos);
String key = Main.key;
for (int i = 0; i < regConIcaos.size(); i++) {
Main.regionalConditions.locName.add(getLocName(regConNames.get(i)));
Main.regionalConditions.temperature.add(getTemperature(regConIcaos.get(i), key));
Main.regionalConditions.condition.add(getCondition(regConIcaos.get(i), key));
}
}
}
@@ -1,104 +0,0 @@
package WS3000.weatherstar3000;
import org.json.JSONObject;
import util.Utilities;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
public class RegionalForecast extends Thread {
ArrayList<String> locName = new ArrayList<>();
ArrayList<String> condition = new ArrayList<>();
ArrayList<String> low = new ArrayList<>();
ArrayList<String> high = new ArrayList<>();
Utilities utl = new Utilities();
String getLocName(String displayName){
return utl.ljust(displayName, 14, " ").substring(0, 14);
}
String getCondition(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/forecast/daily/7day?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return "NO REPORT";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
JSONObject dpData = JSONResponse.getJSONArray("daypart").getJSONObject(0);
int bump = dpData.getJSONArray("dayOrNight").isNull(0) ? 2 : 0;
return utl.getForecast(dpData.getJSONArray("iconCodeExtend").getInt(bump));
} catch (Exception e) {
e.printStackTrace();
return "NO REPORT";
}
}
String getLow(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/forecast/daily/7day?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
JSONObject dpData = JSONResponse.getJSONArray("daypart").getJSONObject(0);
return utl.rjust(Integer.toString(dpData.getJSONArray("temperature").getInt(1)), 3, " ");
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
String getHigh(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/forecast/daily/7day?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
JSONObject dpData = JSONResponse.getJSONArray("daypart").getJSONObject(0);
int bump = dpData.getJSONArray("dayOrNight").isNull(0) ? 2 : 0;
return utl.rjust(Integer.toString(dpData.getJSONArray("temperature").getInt(bump)), 3, " ");
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
public void run() {
ArrayList<String> regForNames = new ArrayList<>();
regForNames.addAll(Main.regForNames);
ArrayList<String> regForIcaos = new ArrayList<>();
regForIcaos.addAll(Main.regForIcaos);
String key = Main.key;
for (int i = 0; i < regForIcaos.size(); i++) {
Main.regionalForecast.locName.add(getLocName(regForNames.get(i)));
Main.regionalForecast.condition.add(getCondition(regForIcaos.get(i), key));
Main.regionalForecast.low.add(getLow(regForIcaos.get(i), key));
Main.regionalForecast.high.add(getHigh(regForIcaos.get(i), key));
}
}
}
@@ -1,45 +0,0 @@
package WS3000.weatherstar3000;
import java.util.ArrayList;
import java.util.List;
import renderer.Renderer;
public abstract class Scene {
protected Renderer renderer = new Renderer();
protected Camera camera;
private boolean isRunning = false;
protected List<GameObject> gameObjects = new ArrayList<>();
public Scene() {
}
public void init() {
}
public void start() {
for (GameObject go : gameObjects) {
go.start();
this.renderer.add(go);
}
isRunning = true;
}
public void addGameObjectToScene(GameObject go) {
if (!isRunning) {
gameObjects.add(go);
} else {
gameObjects.add(go);
go.start();
this.renderer.add(go);
}
}
public abstract void update(float dt);
public Camera camera() {
return this.camera;
}
}
File diff suppressed because it is too large. Load diff
@@ -1,44 +0,0 @@
package WS3000.weatherstar3000;
import org.joml.Vector2f;
public class Transform {
public Vector2f position;
public Vector2f scale;
public Transform() {
init(new Vector2f(), new Vector2f());
}
public Transform(Vector2f position) {
init(position, new Vector2f());
}
public Transform(Vector2f position, Vector2f scale) {
init(position, scale);
}
public void init(Vector2f position, Vector2f scale) {
this.position = position;
this.scale = scale;
}
public Transform copy() {
return new Transform(new Vector2f(this.position), new Vector2f(this.scale));
}
public void copy(Transform to) {
to.position.set(this.position);
to.scale.set(this.scale);
}
@Override
public boolean equals(Object o) {
if (o == null) return false;
if (!(o instanceof Transform)) return false;
Transform t = (Transform)o;
return t.position.equals(this.position) && t.scale.equals(this.scale);
}
}
@@ -1,104 +0,0 @@
package WS3000.weatherstar3000;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.Arrays;
import org.json.JSONObject;
import util.Utilities;
public class TravelForecast extends Thread {
ArrayList<String> locName = new ArrayList<>();
ArrayList<String> condition = new ArrayList<>();
ArrayList<String> low = new ArrayList<>();
ArrayList<String> high = new ArrayList<>();
Utilities utl = new Utilities();
ArrayList<String> tForNames = new ArrayList<>(Arrays.asList("ATLANTA", "BISMARCK", "BOISE", "BOSTON", "BUFFALO", "CHICAGO", "CINCINNATI", "DALLAS", "DENVER", "DETROIT", "KANSAS CITY", "LOS ANGELES", "MINNEAPOLIS", "NASHVILLE", "NEW ORLEANS", "NEW YORK CITY", "PHOENIX", "PORTLAND", "RALEIGH", "RAPID CITY", "SACRAMENTO", "SALT LAKE CITY", "TAMPA", "WASHINGTON, DC"));
ArrayList<String> tForIcaos = new ArrayList<>(Arrays.asList("KATL", "KBIS", "KBOI", "KBOS", "KBUF", "KORD", "KCVG", "KDAL", "KDEN", "KDTW", "KMCI", "KLAX", "KMSP", "KDNA", "KMSY", "KLGA", "KPHX", "KPDX", "KRDU", "KRAP", "KSMF", "KSLC", "KTPA", "KDCA"));
String getLocName(String displayName){
return utl.ljust(displayName, 14, " ").substring(0, 14);
}
String getCondition(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/forecast/daily/7day?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return "NO REPORT";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
JSONObject dpData = JSONResponse.getJSONArray("daypart").getJSONObject(0);
int bump = dpData.getJSONArray("dayOrNight").isNull(0) ? 2 : 0;
return utl.getForecast(dpData.getJSONArray("iconCodeExtend").getInt(bump));
} catch (Exception e) {
e.printStackTrace();
return "NO REPORT";
}
}
String getLow(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/forecast/daily/7day?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
JSONObject dpData = JSONResponse.getJSONArray("daypart").getJSONObject(0);
return utl.rjust(Integer.toString(dpData.getJSONArray("temperature").getInt(1)), 3, " ");
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
String getHigh(String icaoCode, String key) {
HttpClient Client = HttpClient.newBuilder().build();
HttpRequest Request = HttpRequest.newBuilder()
.uri(URI.create("https://api.weather.com/v3/wx/forecast/daily/7day?icaoCode=" + icaoCode + "&units=e&language=en-US&format=json&apiKey=" + key))
.GET()
.header("Accept", "application/json")
.build();
try {
HttpResponse<String> Response = Client.send(Request, HttpResponse.BodyHandlers.ofString());
if (Response.statusCode() != 200) {
return " ";
}
String ResponseBody = Response.body();
JSONObject JSONResponse = new JSONObject(ResponseBody);
JSONObject dpData = JSONResponse.getJSONArray("daypart").getJSONObject(0);
int bump = dpData.getJSONArray("dayOrNight").isNull(0) ? 2 : 0;
return utl.rjust(Integer.toString(dpData.getJSONArray("temperature").getInt(bump)), 3, " ");
} catch (Exception e) {
e.printStackTrace();
return " ";
}
}
public void run() {
String key = Main.key;
for (int i = 0; i < tForIcaos.size(); i++) {
Main.travelForecast.locName.add(getLocName(tForNames.get(i)));
Main.travelForecast.condition.add(getCondition(tForIcaos.get(i), key));
Main.travelForecast.low.add(getLow(tForIcaos.get(i), key));
Main.travelForecast.high.add(getHigh(tForIcaos.get(i), key));
}
}
}
@@ -1,200 +0,0 @@
package WS3000.weatherstar3000;
import org.lwjgl.*;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import org.lwjgl.system.*;
import java.nio.*;
import static org.lwjgl.glfw.Callbacks.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.opengl.GL30.glGenFramebuffers;
import static org.lwjgl.opengl.GL30.GL_FRAMEBUFFER;
import static org.lwjgl.opengl.GL30.glBindFramebuffer;
import static org.lwjgl.opengl.GL30.*;
import renderer.FrameBuffer;
public class Window {
static int secFrameCount;
static int fourSecFrameCount;
static int slidesSecFrameCount;
static int crawlSecFrameCount;
static int bTimerSecFrameCount;
static int bSlideSecFrameCount;
int width, height;
String title;
private FrameBuffer framebuffer;
private static long glfwWindow;
public float r, g, b, a;
private static boolean fullscreen;
private static Window window;
private static Scene currentScene;
private Window(int width, int height, boolean fullscreen) {
this.width = width;
this.height = height;
this.title = "WeatherSTAR 3000";
this.fullscreen = fullscreen;
r = 0.0f;
g = 0.0f;
b = 0.0f;
a = 1.0f;
}
public static Window get() {
if (Window.window == null) {
Window.window = new Window(Main.simWidth, Main.simHeight, Main.fullscreen);
}
return Window.window;
}
public static long getGLFWWindow() {
return glfwWindow;
}
public static Scene getScene() {
return get().currentScene;
}
public void runWindow() {
System.out.println("LWJGL" + Version.getVersion());
init();
loop();
glfwFreeCallbacks(glfwWindow);
glfwDestroyWindow(glfwWindow);
glfwTerminate();
glfwSetErrorCallback(null).free();
}
public void init() {
GLFWErrorCallback.createPrint(System.err).set();
if (!glfwInit()) {
throw new IllegalStateException("Unable to initialize GLFW");
}
glfwDefaultWindowHints();
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
GLFWVidMode vidMode = GLFW.glfwGetVideoMode(GLFW.glfwGetPrimaryMonitor());
PointerBuffer monitors = glfwGetMonitors();
if (!monitors.equals(NULL)) {
for (int i = 0; i < monitors.limit(); i++) {
long monitorHandle = monitors.get(i);
// Get the human-readable name of the monitor
String monitorName = glfwGetMonitorName(monitorHandle);
System.out.println("Monitor " + i + ": " + monitorName);
}
} else {
System.err.println("No monitors found!");
}
if (this.fullscreen) {
glfwWindow = glfwCreateWindow(vidMode.width(), vidMode.height(), "WeatherSTAR 3000", GLFW.glfwGetPrimaryMonitor(), NULL);
} else {
glfwWindow = glfwCreateWindow(this.width, this.height, "WeatherSTAR 3000", NULL, NULL);
}
if (glfwWindow == NULL) {
throw new IllegalStateException("Failed to create GLFW window");
}
glfwSetFramebufferSizeCallback(glfwWindow, (windowHandle, newWidth, newHeight) -> {
this.width = newWidth;
this.height = newHeight;
glViewport(0, 0, newWidth, newHeight);
});
glfwSetKeyCallback(glfwWindow, KeyListener::keyCallback);
glfwMakeContextCurrent(glfwWindow);
glfwSwapInterval(1);
glfwShowWindow(glfwWindow);
GL.createCapabilities();
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
//this.framebuffer = new FrameBuffer(this.width, this.height);
currentScene = new LoadingScreen();
currentScene.init();
currentScene.start();
}
public void loop() {
float beginTime = (float)glfwGetTime();
float endTime;
float dt = 0.0f;
secFrameCount = 0;
System.out.println("start loop");
while(!glfwWindowShouldClose(glfwWindow)) {
glfwPollEvents();
glClearColor(r, g, b, a);
glClear(GL_COLOR_BUFFER_BIT);
if (KeyListener.isKeyPressed(GLFW_KEY_ESCAPE)) {
System.exit(0);
}
if (dt >= 0) {
currentScene.update(dt);
}
glfwSwapBuffers(glfwWindow);
endTime = (float)glfwGetTime();
if (SlidesRunner.slidesStarted) {
secFrameCount++;
fourSecFrameCount++;
slidesSecFrameCount++;
if (!SlidesRunner.bulletinActive) {
bTimerSecFrameCount++;
}
if (SlidesRunner.adCrawlActive) {
crawlSecFrameCount++;
}
}
dt = endTime - beginTime;
//System.out.println(1.0f/dt + " fps");
beginTime = endTime;
}
if (SlidesRunner.audioManager != null) {
SlidesRunner.audioManager.close();
}
System.exit(0);
}
static void finishInit() {
currentScene = new SlidesRunner();
currentScene.init();
currentScene.start();
}
}
@@ -1,9 +0,0 @@
package WS3000.weatherstar3000;
public class WindowRunner extends Thread {
public void run() {
Main.settingsWindow.setVisible(false);
Window window = Window.get();
window.runWindow();
}
}
@@ -1,20 +0,0 @@
package components;
import WS3000.weatherstar3000.Component;
public class FontRenderer extends Component {
@Override
public void start() {
if (gameObject.getComponent(SpriteRenderer.class) != null) {
System.out.println("Found font renderer");
}
}
@Override
public void update(float dt) {
}
}
-34
View File
@@ -1,34 +0,0 @@
package components;
import org.joml.Vector2f;
import renderer.Texture;
public class Sprite {
private Texture texture;
private Vector2f[] texCoords;
public Sprite(Texture texture) {
this.texture = texture;
Vector2f[] texCoords = {
new Vector2f(1,0),
new Vector2f(1,1),
new Vector2f(0,1),
new Vector2f(0,0)
};
this.texCoords = texCoords;
}
public Sprite(Texture texture, Vector2f[] texCoords) {
this.texture = texture;
this.texCoords = texCoords;
}
public Texture getTexture() {
return this.texture;
}
public Vector2f[] getTexCoords() {
return this.texCoords;
}
}
@@ -1,73 +0,0 @@
package components;
import WS3000.weatherstar3000.Component;
import WS3000.weatherstar3000.Transform;
import renderer.Texture;
import org.joml.Vector2f;
import org.joml.Vector4f;
public class SpriteRenderer extends Component {
private Vector4f color;
private Sprite sprite;
private Transform lastTransform;
private boolean isDirty;
public SpriteRenderer(Vector4f color) {
this.color = color;
this.sprite = new Sprite(null);
this.isDirty = true;
}
public SpriteRenderer(Sprite sprite) {
this.sprite = sprite;
this.color = new Vector4f(1,1,1,1);
this.isDirty = true;
}
@Override
public void start() {
this.lastTransform = gameObject.transform.copy();
}
@Override
public void update(float dt) {
if (!this.lastTransform.equals(this.gameObject.transform)) {
this.gameObject.transform.copy(lastTransform);
isDirty = true;
}
}
public Vector4f getColor() {
return this.color;
}
public Texture getTexture() {
return sprite.getTexture();
}
public Vector2f[] getTexCoords() {
return sprite.getTexCoords();
}
public void setSprite(Sprite sprite) {
this.sprite = sprite;
this.isDirty = true;
}
public void setColor(Vector4f color) {
if (!this.color.equals(color)) {
this.isDirty = true;
this.color = color;
}
}
public boolean isDirty() {
return this.isDirty;
}
public void setClean() {
this.isDirty = false;
}
}
-46
View File
@@ -1,46 +0,0 @@
package components;
import java.util.ArrayList;
import java.util.List;
import org.joml.Vector2f;
import renderer.Texture;
public class Spritesheet {
private Texture texture;
private List<Sprite> sprites;
public Spritesheet(Texture texture, int spriteWidth, int spriteHeight, int numSprites, int spacing) {
this.sprites = new ArrayList<>();
this.texture = texture;
int currentX = 0;
int currentY = texture.getHeight() - spriteHeight;
for (int i = 0; i < numSprites; i++) {
float topY = (currentY + spriteHeight) / (float)texture.getHeight();;
float rightX = (currentX + spriteWidth) / (float)texture.getWidth();
float leftX = currentX / (float)texture.getWidth();
float bottomY = currentY / (float)texture.getHeight();;
Vector2f[] texCoords = {
new Vector2f(rightX, bottomY),
new Vector2f(rightX, topY),
new Vector2f(leftX, topY),
new Vector2f(leftX, bottomY)
};
Sprite sprite = new Sprite(this.texture, texCoords);
this.sprites.add(sprite);
currentX += spriteWidth + spacing;
if (currentX >= texture.getWidth()) {
currentX = 0;
currentY -= spriteHeight + spacing;
}
}
}
public Sprite getSprite(int index) {
return this.sprites.get(index);
}
}
-46
View File
@@ -1,46 +0,0 @@
package renderer;
import static org.lwjgl.opengl.GL30.glGenFramebuffers;
import static org.lwjgl.opengl.GL30.GL_FRAMEBUFFER;
import static org.lwjgl.opengl.GL30.glBindFramebuffer;
import static org.lwjgl.opengl.GL30.*;
public class FrameBuffer {
private int fboID = 0;
private Texture texture = null;
public FrameBuffer(int width, int height) {
fboID = glGenFramebuffers();
glBindFramebuffer(GL_FRAMEBUFFER, fboID);
this.texture = new Texture(width, height);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this.texture.getId(), 0);
int rboID = glGenRenderbuffers();
glBindRenderbuffer(GL_RENDERBUFFER, rboID);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT32, width, height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rboID);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
assert false : "Error: Framebuffer is not complete";
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
public void bind() {
glBindFramebuffer(GL_FRAMEBUFFER, fboID);
}
public void unbind() {
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
public int getFboID() {
return fboID;
}
public int getTextureId() {
return texture.getId();
}
}
-242
View File
@@ -1,242 +0,0 @@
package renderer;
import components.SpriteRenderer;
import util.AssetPool;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL30.*;
import java.util.ArrayList;
import java.util.List;
import org.joml.Vector2f;
import org.joml.Vector4f;
import WS3000.weatherstar3000.Window;
public class RenderBatch implements Comparable<RenderBatch> {
private final int POS_SIZE = 2;
private final int COLOR_SIZE = 4;
private final int TEX_COORDS_SIZE = 2;
private final int TEX_ID_SIZE = 1;
private final int POS_OFFSET = 0;
private final int COLOR_OFFSET = POS_OFFSET + (POS_SIZE * Float.BYTES);
private final int TEX_COORDS_OFFSET = COLOR_OFFSET + (COLOR_SIZE * Float.BYTES);
private final int TEX_ID_OFFSET = TEX_COORDS_OFFSET + (TEX_COORDS_SIZE * Float.BYTES);
private final int VERTEX_SIZE = 9;
private final int VERTEX_SIZE_BYTES = VERTEX_SIZE * Float.BYTES;
private SpriteRenderer[] sprites;
private int numSprites;
private boolean hasRoom;
private float[] vertices;
private int[] texSlots = {0,1,2,3,4,5,6,7};
private List<Texture> textures;
private int vaoID, vboID;
private int maxBatchSize;
private Shader shader;
private int zIndex;
public RenderBatch(int maxBatchSize, int zIndex) {
this.zIndex = zIndex;
shader = AssetPool.getShader("/resources/shaders/default.glsl");
shader.compile();
this.sprites = new SpriteRenderer[maxBatchSize];
this.maxBatchSize = maxBatchSize;
vertices = new float[maxBatchSize * 4 * VERTEX_SIZE];
this.numSprites = 0;
this.hasRoom = true;
this.textures = new ArrayList<>();
}
public void start() {
vaoID = glGenVertexArrays();
glBindVertexArray(vaoID);
vboID = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, vboID);
glBufferData(GL_ARRAY_BUFFER, vertices.length * Float.BYTES, GL_DYNAMIC_DRAW);
int eboID = glGenBuffers();
int[] indices = generateIndices();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, eboID);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices, GL_STATIC_DRAW);
glVertexAttribPointer(0, POS_SIZE, GL_FLOAT, false, VERTEX_SIZE_BYTES, POS_OFFSET);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, COLOR_SIZE, GL_FLOAT, false, VERTEX_SIZE_BYTES, COLOR_OFFSET);
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, TEX_COORDS_SIZE, GL_FLOAT, false, VERTEX_SIZE_BYTES, TEX_COORDS_OFFSET);
glEnableVertexAttribArray(2);
glVertexAttribPointer(3, TEX_ID_SIZE, GL_FLOAT, false, VERTEX_SIZE_BYTES, TEX_ID_OFFSET);
glEnableVertexAttribArray(3);
}
public void addSprite(SpriteRenderer spr) {
int index = this.numSprites;
this.sprites[index] = spr;
this.numSprites++;
if (spr.getTexture() != null) {
if (!textures.contains(spr.getTexture())) {
textures.add(spr.getTexture());
}
}
loadVertexProperties(index);
if (numSprites >= this.maxBatchSize) {
this.hasRoom = false;
}
}
public void render() {
boolean rebufferData = false;
for (int i = 0; i < numSprites; i++) {
SpriteRenderer spr = sprites[i];
if (spr.isDirty()) {
loadVertexProperties(i);
spr.setClean();
rebufferData = true;
}
}
if (rebufferData) {
glBindBuffer(GL_ARRAY_BUFFER, vboID);
glBufferSubData(GL_ARRAY_BUFFER, 0, vertices);
}
shader.use();
shader.uploadMat4f("uProjection", Window.getScene().camera().getProjectionMatrix());
shader.uploadMat4f("uView", Window.getScene().camera().getViewMatrix());
for (int i = 0; i < textures.size(); i++) {
glActiveTexture(GL_TEXTURE0 + i + 1);
textures.get(i).bind();
}
shader.uploadIntArray("uTextures", texSlots);
glBindVertexArray(vaoID);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glDrawElements(GL_TRIANGLES, this.numSprites * 6, GL_UNSIGNED_INT, 0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
glDisableVertexAttribArray(3);
glBindVertexArray(0);
for (int i = 0; i < textures.size(); i++) {
textures.get(i).unBind();
}
shader.detach();
}
private void loadVertexProperties(int index) {
SpriteRenderer sprite = this.sprites[index];
int offset = index * 4 * VERTEX_SIZE;
Vector4f color = sprite.getColor();
Vector2f[] texCoords = sprite.getTexCoords();
int texId = 0;
if (sprite.getTexture() != null) {
for (int i = 0; i < textures.size(); i++) {
if (textures.get(i).equals(sprite.getTexture())) {
texId = i + 1;
break;
}
}
}
float xAdd = 1.0f;
float yAdd = 1.0f;
for (int i = 0; i < 4; i++) {
if (i == 1) {
yAdd = 0.0f;
} else if (i == 2) {
xAdd = 0.0f;
} else if (i == 3) {
yAdd = 1.0f;
}
vertices[offset] = sprite.gameObject.transform.position.x + (xAdd * sprite.gameObject.transform.scale.x);
vertices[offset + 1] = sprite.gameObject.transform.position.y + (yAdd * sprite.gameObject.transform.scale.y);
vertices[offset + 2] = color.x;
vertices[offset + 3] = color.y;
vertices[offset + 4] = color.z;
vertices[offset + 5] = color.w;
vertices[offset + 6] = texCoords[i].x;
vertices[offset + 7] = texCoords[i].y;
vertices[offset + 8] = texId;;
offset += VERTEX_SIZE;
}
}
private int[] generateIndices() {
int[] elements = new int [6 * maxBatchSize];
for (int i = 0; i < maxBatchSize; i++) {
loadElementIndices(elements, i);
}
return elements;
}
private void loadElementIndices(int[] elements, int index) {
int offsetArrayIndex = 6 * index;
int offset = 4 * index;
elements[offsetArrayIndex] = offset + 3;
elements[offsetArrayIndex + 1] = offset + 2;
elements[offsetArrayIndex + 2] = offset + 0;
elements[offsetArrayIndex + 3] = offset + 0;
elements[offsetArrayIndex + 4] = offset + 2;
elements[offsetArrayIndex + 5] = offset + 1;
}
public boolean hasRoom() {
return this.hasRoom;
}
public boolean hasTextureRoom() {
return this.textures.size() < 8;
}
public boolean hasTexture(Texture tex) {
return this.textures.contains(tex);
}
public int zIndex() {
return this.zIndex;
}
public void clear() {
this.numSprites = 0;
}
@Override
public int compareTo(RenderBatch o) {
return Integer.compare(this.zIndex, o.zIndex());
}
}
-60
View File
@@ -1,60 +0,0 @@
package renderer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import WS3000.weatherstar3000.GameObject;
import components.SpriteRenderer;
public class Renderer {
private final int MAX_BATCH_SIZE = 2500;
private List<RenderBatch> batches;
public Renderer() {
this.batches = new ArrayList<>();
}
public void add(GameObject go) {
SpriteRenderer spr = go.getComponent(SpriteRenderer.class);
if (spr != null) {
add(spr);
}
}
private void add(SpriteRenderer sprite) {
boolean added = false;
for (RenderBatch batch : batches) {
if (batch.hasRoom() && batch.zIndex() == sprite.gameObject.zIndex()) {
Texture tex = sprite.getTexture();
if (tex == null || (batch.hasTexture(tex) || batch.hasTextureRoom())) {
batch.addSprite(sprite);
added = true;
break;
}
}
}
if (!added) {
RenderBatch newBatch = new RenderBatch(MAX_BATCH_SIZE, sprite.gameObject.zIndex());
newBatch.start();
batches.add(newBatch);
newBatch.addSprite(sprite);
Collections.sort(batches);
}
}
public void render() {
for (RenderBatch batch : batches) {
batch.render();
}
}
public void clear() {
for (RenderBatch batch : batches) {
batch.clear(); // Resets numSprites to 0
}
//this.batches.clear();
}
}
-183
View File
@@ -1,183 +0,0 @@
package renderer;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL20.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.FloatBuffer;
import java.nio.file.*;
import java.util.stream.Collectors;
import org.joml.*;
import org.lwjgl.BufferUtils;
public class Shader {
private int shaderProgramID;
private boolean beingUsed = false;
private String vertexSource;
private String fragmentSource;
private String filepath;
public Shader(String filepath) {
this.filepath = filepath;
try {
// Make sure the path starts with a leading slash for root JAR loading
String resourcePath = filepath.startsWith("/") ? filepath : "/" + filepath;
String source;
try (InputStream is = Shader.class.getResourceAsStream(resourcePath)) {
if (is == null) {
throw new IOException("Shader file not found inside JAR: " + resourcePath);
}
// Safely read all text lines into a single String
source = new BufferedReader(new InputStreamReader(is))
.lines().collect(Collectors.joining("\n"));
}
String[] splitString = source.split("(#type)( )+([a-zA-Z]+)");
int index = source.indexOf("#type") + 6;
int eol = source.indexOf("\n", index);
String firstPattern = source.substring(index, eol).trim();
index = source.indexOf("#type", eol) + 6;
eol = source.indexOf("\n", index);
String secondPattern = source.substring(index, eol).trim();
if (firstPattern.equals("vertex")) {
vertexSource = splitString[1];
} else if (firstPattern.equals("fragment")) {
fragmentSource = splitString[1];
} else {
throw new IOException("Unexpected token '" + firstPattern + "'");
}
if (secondPattern.equals("vertex")) {
vertexSource = splitString[2];
} else if (secondPattern.equals("fragment")) {
fragmentSource = splitString[2];
} else {
throw new IOException("Unexpected token '" + secondPattern + "'");
}
} catch (IOException e) {
e.printStackTrace();
assert false : "ERROR: Could not open file for shader: " + filepath;
}
}
public void compile() {
int vertexID, fragmentID;
vertexID = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexID, vertexSource);
glCompileShader(vertexID);
int success = glGetShaderi(vertexID, GL_COMPILE_STATUS);
if (success == GL_FALSE) {
int len = glGetShaderi(vertexID, GL_INFO_LOG_LENGTH);
System.out.println("ERROR: " + filepath + "\n\tVertex shader compilation failed.");
System.out.println(glGetShaderInfoLog(vertexID, len));
assert false : "";
}
fragmentID = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentID, fragmentSource);
glCompileShader(fragmentID);
success = glGetShaderi(fragmentID, GL_COMPILE_STATUS);
if (success == GL_FALSE) {
int len = glGetShaderi(fragmentID, GL_INFO_LOG_LENGTH);
System.out.println("ERROR: " + filepath + "\n\tVertex shader compilation failed.");
System.out.println(glGetShaderInfoLog(fragmentID, len));
assert false : "";
}
shaderProgramID = glCreateProgram();
glAttachShader(shaderProgramID, vertexID);
glAttachShader(shaderProgramID, fragmentID);
glLinkProgram(shaderProgramID);
success = glGetProgrami(shaderProgramID, GL_LINK_STATUS);
if (success == GL_FALSE) {
int len = glGetProgrami(shaderProgramID, GL_LINK_STATUS);
System.out.println("ERROR: " + filepath + "\n\tFailed to link shaders.");
System.out.println(glGetProgramInfoLog(shaderProgramID, len));
assert false : "";
}
}
public void use() {
if (!beingUsed) {
glUseProgram(shaderProgramID);
beingUsed = true;
}
}
public void detach() {
glUseProgram(0);
beingUsed = false;
}
public void uploadMat4f(String varName, Matrix4f mat4) {
int varLocation = glGetUniformLocation(shaderProgramID, varName);
use();
FloatBuffer matBuffer = BufferUtils.createFloatBuffer(16);
mat4.get(matBuffer);
glUniformMatrix4fv(varLocation, false, matBuffer);
}
public void uploadMat3f(String varName, Matrix3f mat3) {
int varLocation = glGetUniformLocation(shaderProgramID, varName);
use();
FloatBuffer matBuffer = BufferUtils.createFloatBuffer(9);
mat3.get(matBuffer);
glUniformMatrix3fv(varLocation, false, matBuffer);
}
public void uploadVec4f(String varName, Vector4f vec) {
int varLocation = glGetUniformLocation(shaderProgramID, varName);
use();
glUniform4f(varLocation, vec.x, vec.y, vec.z, vec.w);
}
public void uploadVec3f(String varName, Vector3f vec) {
int varLocation = glGetUniformLocation(shaderProgramID, varName);
use();
glUniform3f(varLocation, vec.x, vec.y, vec.z);
}
public void uploadVec2f(String varName, Vector2f vec) {
int varLocation = glGetUniformLocation(shaderProgramID, varName);
use();
glUniform2f(varLocation, vec.x, vec.y);
}
public void uploadFloat(String varName, float val) {
int varLocation = glGetUniformLocation(shaderProgramID, varName);
use();
glUniform1f(varLocation, val);
}
public void uploadInt(String varName, int val) {
int varLocation = glGetUniformLocation(shaderProgramID, varName);
use();
glUniform1i(varLocation, val);
}
public void uploadTexture(String varName, int slot) {
int varLocation = glGetUniformLocation(shaderProgramID, varName);
use();
glUniform1i(varLocation, slot);
}
public void uploadIntArray(String varName, int[] array) {
int varLocation = glGetUniformLocation(shaderProgramID, varName);
use();
glUniform1iv(varLocation, array);
}
}
-126
View File
@@ -1,126 +0,0 @@
package renderer;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.ARBTextureRectangle.*;
import static org.lwjgl.stb.STBImage.*;
import java.io.IOException;
import java.io.InputStream;
import java.nio.*;
import org.lwjgl.BufferUtils;
public class Texture {
private String filepath;
private int texID;
private int width, height;
public Texture() {
texID = -1;
width = -1;
height = -1;
}
public Texture(int width, int height) {
this.filepath = "Generated";
texID = glGenTextures();
glBindTexture(GL_TEXTURE_2D, texID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
}
public Texture(String filepath) {
this.filepath = filepath;
texID = glGenTextures();
glBindTexture(GL_TEXTURE_2D, texID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
IntBuffer widthBuffer = BufferUtils.createIntBuffer(1);
IntBuffer heightBuffer = BufferUtils.createIntBuffer(1);
IntBuffer channelsBuffer = BufferUtils.createIntBuffer(1);
stbi_set_flip_vertically_on_load(true);
// Ensure the path starts with a leading slash for classpath lookup
String resourcePath = filepath.startsWith("/") ? filepath : "/" + filepath;
ByteBuffer image = null;
try (InputStream is = Texture.class.getResourceAsStream(resourcePath)) {
if (is == null) {
throw new IOException("Texture file not found inside JAR: " + resourcePath);
}
// Read bytes from the JAR stream into a native ByteBuffer
byte[] bytes = is.readAllBytes();
ByteBuffer nativeBuffer = BufferUtils.createByteBuffer(bytes.length);
nativeBuffer.put(bytes);
nativeBuffer.flip();
// Tell STB to decode the image from raw memory instead of a disk path
image = stbi_load_from_memory(nativeBuffer, widthBuffer, heightBuffer, channelsBuffer, 0);
} catch (IOException e) {
e.printStackTrace();
assert false : "ERROR: Could not read stream for texture: " + filepath;
}
if (image != null) {
this.width = widthBuffer.get(0);
this.height = heightBuffer.get(0);
int channels = channelsBuffer.get(0);
if (channels == 3) {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, this.width, this.height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
} else if (channels == 4) {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, this.width, this.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
} else {
stbi_image_free(image);
assert false : "ERROR: (Texture) Unknown number of channels " + channels + ", " + filepath;
}
stbi_image_free(image);
} else {
assert false : "ERROR: STB failed to decode image " + filepath + " Reason: " + stbi_failure_reason();
}
}
public void bind() {
glBindTexture(GL_TEXTURE_2D, texID);
}
public void unBind() {
glBindTexture(GL_TEXTURE_2D, 0);
}
public int getWidth() {
return this.width;
}
public String getFilePath() {
return this.filepath;
}
public int getHeight() {
return this.height;
}
public int getId() {
return this.texID;
}
@Override
public boolean equals(Object o) {
if (o == null) return false;
if (!(o instanceof Texture)) return false;
Texture oTex = (Texture) o;
return oTex.getWidth() == this.width && oTex.getHeight() == this.height && oTex.getId() == this.texID && oTex.getFilePath().equals(this.filepath);
}
}
-49
View File
@@ -1,49 +0,0 @@
package util;
import renderer.Shader;
import renderer.Texture;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import components.Spritesheet;
public class AssetPool {
private static Map<String, Shader> shaders = new HashMap<>();
private static Map<String, Texture> textures = new HashMap<>();
private static Map<String, Spritesheet> spritesheets = new HashMap<>();
public static Shader getShader(String resourceName) {
if (AssetPool.shaders.containsKey(resourceName)) {
return AssetPool.shaders.get(resourceName);
} else {
Shader shader = new Shader(resourceName);
shader.compile();
AssetPool.shaders.put(resourceName, shader);
return shader;
}
}
public static Texture getTexture(String resourceName) {
if (AssetPool.textures.containsKey(resourceName)) {
return AssetPool.textures.get(resourceName);
} else {
Texture texture = new Texture(resourceName);
AssetPool.textures.put(resourceName, texture);
return texture;
}
}
public static void addSpritesheet(String resourceName, Spritesheet spritesheet) {
if (!AssetPool.spritesheets.containsKey(resourceName)) {
AssetPool.spritesheets.put(resourceName, spritesheet);
}
}
public static Spritesheet getSpritesheet(String resourceName) {
if (!AssetPool.spritesheets.containsKey(resourceName)) {
assert false : "Error: Tried to access spritesheet '" + resourceName + "' and it has not been added to the asset pool.";
}
return AssetPool.spritesheets.getOrDefault(resourceName, null);
}
}
-403
View File
@@ -1,403 +0,0 @@
package util;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import org.json.*;
import org.joml.Vector4f;
public class Utilities {
public static Map<Character, Integer> mainFontMap = new HashMap<>();
public static Map<Character, Integer> smallFontMap = new HashMap<>();
public static String[] testFlavor = {"outlook","travelForecast", "localForecast", "outlook"};
public static String[] flavorA = {"currentConditions","localForecast","hourlyObservations"};
public static String[] flavorB = {"hourlyObservations", "almanac", "extendedForecast", "regionalConditions"};
public static String[] flavorC = {"regionalConditions", "localForecast", "currentConditions"};
public static String[] flavorD = {"hourlyObservations", "almanac", "localForecast", "regionalConditions"};
public static String[] flavorE = {"localForecast", "extendedForecast","hourlyObservations"};
public static String[] flavorF = {"currentConditions", "regionalConditions", "localForecast", "almanac"};
public static String[] flavorG = {"localForecast"};
public static String[] flavorH = {"localForecast", "regionalforecast", "almanac", "hourlyObservations"};
public static String[] flavorI = {"currentConditions", "hourlyObservations", "regionalConditions"};
public static String[] flavorJ = {"currentConditions", "hourlyObservations", "regionalConditions", "localForecast", "almanac", "regionalForecast", "travelForecast", "extendedForecast", "outlook"};
public static String[] flavorK = {"currentConditions", "almanac", "regionalForecast", "localForecast", "extendedForecast", "hourlyObservations"};
public static String[] flavorL = {"currentConditions", "hourlyObservations", "regionalConditions", "regionalForecast", "almanac", "localForecast", "extendedForecast"};
public static String[] flavorM = {"currentConditions", "localForecast", "extendedForecast", "travelForecast"};
public static String[] flavorN = {"currentConditions", "hourlyObservations", "regionalConditions", "localForecast", "almanac", "regionalForecast", "travelForecast", "extendedForecast", "outlook", "currentConditions", "localForecast", "extendedForecast", "travelForecast"};
public static String[] flavorO = {"currentConditions", "hourlyObservations", "regionalConditions", "localForecast", "almanac", "regionalForecast", "travelForecast", "extendedForecast", "outlook", "currentConditions", "hourlyObservations", "regionalConditions", "localForecast", "almanac", "regionalForecast", "travelForecast", "extendedForecast", "outlook"};
public static String[] flavorP = {"localForecast", "extendedForecast", "currentConditions"};
public static String[] flavorQ = {"currentConditions", "almanac", "localForecast", "regionalConditions"};
static {
mainFontMap.put(' ', 0);
mainFontMap.put('!', 1);
mainFontMap.put('"', 2);
mainFontMap.put('#', 3);
mainFontMap.put('$', 4);
mainFontMap.put('%', 5);
mainFontMap.put('&', 6);
mainFontMap.put('\'', 7);
mainFontMap.put('(', 8);
mainFontMap.put(')', 9);
mainFontMap.put('*', 10);
mainFontMap.put('+', 11);
mainFontMap.put(',', 12);
mainFontMap.put('-', 13);
mainFontMap.put('.', 14);
mainFontMap.put('/', 15);
mainFontMap.put('0', 16);
mainFontMap.put('1', 17);
mainFontMap.put('2', 18);
mainFontMap.put('3', 19);
mainFontMap.put('4', 20);
mainFontMap.put('5', 21);
mainFontMap.put('6', 22);
mainFontMap.put('7', 23);
mainFontMap.put('8', 24);
mainFontMap.put('9', 25);
mainFontMap.put(':', 26);
mainFontMap.put(';', 27);
mainFontMap.put('<', 28);
mainFontMap.put('=', 29);
mainFontMap.put('>', 30);
mainFontMap.put('?', 31);
mainFontMap.put('@', 64);
mainFontMap.put('A', 65);
mainFontMap.put('B', 66);
mainFontMap.put('C', 67);
mainFontMap.put('D', 68);
mainFontMap.put('E', 69);
mainFontMap.put('F', 70);
mainFontMap.put('G', 71);
mainFontMap.put('H', 72);
mainFontMap.put('I', 73);
mainFontMap.put('J', 74);
mainFontMap.put('K', 75);
mainFontMap.put('L', 76);
mainFontMap.put('M', 77);
mainFontMap.put('N', 78);
mainFontMap.put('O', 79);
mainFontMap.put('P', 80);
mainFontMap.put('Q', 81);
mainFontMap.put('R', 82);
mainFontMap.put('S', 83);
mainFontMap.put('T', 84);
mainFontMap.put('U', 85);
mainFontMap.put('V', 86);
mainFontMap.put('W', 87);
mainFontMap.put('X', 88);
mainFontMap.put('Y', 89);
mainFontMap.put('Z', 90);
mainFontMap.put('[', 91);
mainFontMap.put('\\', 92);
mainFontMap.put(']', 93);
mainFontMap.put('^', 94);
mainFontMap.put('_', 95);
mainFontMap.put('`', 96);
smallFontMap.put(' ', 32);
smallFontMap.put('!', 33);
smallFontMap.put('"', 34);
smallFontMap.put('#', 35);
smallFontMap.put('$', 36);
smallFontMap.put('%', 37);
smallFontMap.put('&', 38);
smallFontMap.put('\'', 39);
smallFontMap.put('(', 40);
smallFontMap.put(')', 41);
smallFontMap.put('*', 42);
smallFontMap.put('+', 43);
smallFontMap.put(',', 44);
smallFontMap.put('-', 45);
smallFontMap.put('.', 46);
smallFontMap.put('/', 47);
smallFontMap.put('0', 48);
smallFontMap.put('1', 49);
smallFontMap.put('2', 50);
smallFontMap.put('3', 51);
smallFontMap.put('4', 52);
smallFontMap.put('5', 53);
smallFontMap.put('6', 54);
smallFontMap.put('7', 55);
smallFontMap.put('8', 56);
smallFontMap.put('9', 57);
smallFontMap.put(':', 58);
smallFontMap.put(';', 59);
smallFontMap.put('<', 60);
smallFontMap.put('=', 61);
smallFontMap.put('>', 62);
smallFontMap.put('?', 63);
smallFontMap.put('A', 97);
smallFontMap.put('B', 98);
smallFontMap.put('C', 99);
smallFontMap.put('D', 100);
smallFontMap.put('E', 101);
smallFontMap.put('F', 102);
smallFontMap.put('G', 103);
smallFontMap.put('H', 104);
smallFontMap.put('I', 105);
smallFontMap.put('J', 106);
smallFontMap.put('K', 107);
smallFontMap.put('L', 108);
smallFontMap.put('M', 109);
smallFontMap.put('N', 110);
smallFontMap.put('O', 111);
smallFontMap.put('P', 112);
smallFontMap.put('Q', 113);
smallFontMap.put('R', 114);
smallFontMap.put('S', 115);
smallFontMap.put('T', 116);
smallFontMap.put('U', 117);
smallFontMap.put('V', 118);
smallFontMap.put('W', 119);
smallFontMap.put('X', 120);
smallFontMap.put('Y', 121);
smallFontMap.put('Z', 122);
smallFontMap.put('[', 123);
smallFontMap.put('\\', 124);
smallFontMap.put(']', 125);
smallFontMap.put('^', 126);
smallFontMap.put('`', 127);
smallFontMap.put('_', 128);
}
public int getMainChar(char character) {
return mainFontMap.get(character);
}
public int getSmallChar(char character) {
return smallFontMap.get(character);
}
public String ljust(String s, int width, String fillChar) {
if (s.length() >= width) {
return s;
}
StringBuilder sb = new StringBuilder(s);
while (sb.length() < width) {
sb.append(fillChar);
}
return sb.toString();
}
public String rjust(String s, int width, String fillChar) {
if (s.length() >= width) {
return s;
}
StringBuilder sb = new StringBuilder();
while (sb.length() < width - s.length()) {
sb.append(fillChar);
}
sb.append(s);
return sb.toString();
}
public String cjust(String s, int width, String fillChar) {
if (s.length() >= width) {
return s; // No centering needed if text is already too long
}
int padding = width - s.length();
int leftPadding = padding / 2;
int rightPadding = padding - leftPadding;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < leftPadding; i++) {
sb.append(fillChar);
}
sb.append(s);
for(int i = 0; i < rightPadding; i++) {
sb.append(fillChar);
}
return sb.toString();
}
public String degToThreeLetter(int windDir) {
if (windDir >= 0 && windDir <= 11.25) {
return "N ";
} else if (windDir > 11.25 && windDir <= 33.75) {
return "NNE";
} else if (windDir > 33.75 && windDir <= 56.25) {
return "NE ";
} else if (windDir > 56.25 && windDir <= 78.75) {
return "ENE";
} else if (windDir > 78.75 && windDir <= 101.25) {
return "E ";
} else if (windDir > 101.25 && windDir <= 123.75) {
return "ESE";
} else if (windDir > 123.75 && windDir <= 146.25) {
return "SE ";
} else if (windDir > 146.25 && windDir <= 168.75) {
return "SSE";
} else if (windDir > 168.75 && windDir <= 191.25) {
return "S ";
} else if (windDir > 191.25 && windDir <= 213.75) {
return "SSW";
} else if (windDir > 213.75 && windDir <= 236.25) {
return "SW ";
} else if (windDir > 236.25 && windDir <= 258.75) {
return "WSW";
} else if (windDir > 258.75 && windDir <= 281.25) {
return "W ";
} else if (windDir > 281.25 && windDir <= 303.75) {
return "WNW";
} else if (windDir > 303.75 && windDir <= 326.25) {
return "NW ";
} else if (windDir > 326.25 && windDir <= 348.75) {
return "NNW";
} else if (windDir > 348.75 && windDir <= 360) {
return "N ";
} else {
return " ";
}
}
public String degToTwoLetter(int windDir) {
if (windDir >= 0 && windDir <= 22.5) {
return "N ";
} else if (windDir > 22.5 && windDir <= 67.5) {
return "NE";
} else if (windDir > 67.5 && windDir <= 112.5) {
return "E ";
} else if (windDir > 112.5 && windDir <= 157.5) {
return "SE";
} else if (windDir > 157.5 && windDir <= 202.5) {
return "S ";
} else if (windDir > 202.5 && windDir <= 247.5) {
return "SW";
} else if (windDir > 247.5 && windDir <= 292.5) {
return "W ";
} else if (windDir > 292.5 && windDir <= 337.5) {
return "NW";
} else if (windDir > 337.5 && windDir <= 360) {
return "N ";
} else {
return " ";
}
}
public String degToOneLetter(int windDir) {
if (windDir >= 0 && windDir <= 45) {
return "N";
} else if (windDir > 45 && windDir <= 135) {
return "E";
} else if (windDir > 135 && windDir <= 225) {
return "S";
} else if (windDir > 225 && windDir <= 315) {
return "W";
} else if (windDir > 315 && windDir <= 360) {
return "N";
} else {
return " ";
}
}
public String formatWind(int windSpeed, int windDir, boolean spaced) {
String spacer = "";
String ending = "";
int speedLength = Integer.toString(windSpeed).length();
if (spaced) {spacer = " "; ending = " MPH";}
if (windSpeed == 0) {return "CALM";}
if (speedLength == 1) {
return degToThreeLetter(windDir) + spacer + windSpeed + ending;
} else if (speedLength == 2) {
return degToTwoLetter(windDir) + spacer + windSpeed + ending;
} else if (speedLength == 3) {
return degToOneLetter(windDir) + spacer + windSpeed + ending;
} else {
return " " + spacer + ending;
}
}
public String formatShortCond(String condition) {
String conditionFinal = condition;
if (conditionFinal.contains("EARLY")) {
conditionFinal = "AM " + conditionFinal.replaceAll("EARLY", "");
}
if (conditionFinal.contains("LATE")) {
conditionFinal = "PM " + conditionFinal.replaceAll("LATE", "");
}
return conditionFinal.replaceAll(" SHOWER", " SHWR").replaceAll("NEAR", "").replaceAll("LIGHT", "LGT").replaceAll("HEAVY", "HVY").replaceAll("PARTIAL", "PART").replaceAll("CLDY", "CLOUDY").replaceAll(" T-STORM", " T-STM").replaceAll("SHOWERS/", "SHWRS/");
}
private String readJsonFromResource(String path) throws IOException {
StringBuilder jsonText = new StringBuilder();
try (InputStream is = getClass().getResourceAsStream(path)) {
if (is == null) {
throw new IOException("Resource not found inside JAR: " + path);
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
String line;
while ((line = br.readLine()) != null) {
jsonText.append(line).append("\n");
}
}
}
return jsonText.toString();
}
public String getCondition(int iconCode) throws IOException {
String json = readJsonFromResource("/resources/json/ObsMapping.json");
return new JSONObject(json).getString(Integer.toString(iconCode)).toUpperCase();
}
public String getForecast(int iconCode) throws IOException {
String json = readJsonFromResource("/resources/json/FcstMapping.json");
return new JSONObject(json).getString(Integer.toString(iconCode)).toUpperCase();
}
public String getForecastEx(int iconCode, int lineNum) throws IOException {
String json = readJsonFromResource("/resources/json/FcstTwoLineMapping.json");
return ljust(new JSONObject(json).getJSONArray(Integer.toString(iconCode)).getString(lineNum).toUpperCase(), 10, " ");
}
public boolean isHeadline(String headline) throws IOException {
String json = readJsonFromResource("/resources/json/AlertMapping.json");
JSONObject jsonObject = new JSONObject(json);
if (jsonObject.has(headline)) {
return jsonObject.getJSONObject(headline).getBoolean("headline");
} else {
return false;
}
}
public boolean isScroll(String headline) throws IOException {
String json = readJsonFromResource("/resources/json/AlertMapping.json");
JSONObject jsonObject = new JSONObject(json);
if (jsonObject.has(headline)) {
return jsonObject.getJSONObject(headline).getBoolean("scroll");
} else {
return false;
}
}
public String getSeverity(String headline) throws IOException {
String json = readJsonFromResource("/resources/json/AlertMapping.json");
JSONObject jsonObject = new JSONObject(json);
if (jsonObject.has(headline)) {
return jsonObject.getJSONObject(headline).getString("severity");
} else {
return "None";
}
}
public Vector4f getBulletinColor(String headline) throws IOException {
if (getSeverity(headline).equals("Warning")) {
return new Vector4f(104.0f/255.0f, 0.0f/255.0f, 8.0f/255.0f, 1.0f);
} else if (getSeverity(headline).equals("Advisory")) {
return new Vector4f(160.0f/255.0f, 78.0f/255.0f, 14.0f/255.0f, 1.0f);
} else {
return new Vector4f(0.0f/255.0f, 0.0f/255.0f, 0.0f/255.0f, 1.0f);
}
}
public void printThirtyTwoLine() {
System.out.println("--------------------------------");
}
}