mirror of
https://github.com/michaelrausch/Party-Parrots-At-Sea.git
synced 2026-05-09 06:18:44 +00:00
Action packets now sent at regular 20ms intervals
#issue[38] #implement
This commit is contained in:
@@ -9,12 +9,15 @@ import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Queue;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.zip.CRC32;
|
||||
import java.util.zip.Checksum;
|
||||
import javafx.application.Platform;
|
||||
import javafx.scene.control.Alert;
|
||||
import javafx.scene.control.Alert.AlertType;
|
||||
import seng302.gameServer.server.messages.BoatActionType;
|
||||
import seng302.model.stream.packets.StreamPacket;
|
||||
import seng302.gameServer.server.messages.BoatActionMessage;
|
||||
import seng302.gameServer.server.messages.Message;
|
||||
@@ -47,11 +50,15 @@ public class ClientToServerThread implements Runnable {
|
||||
|
||||
private Socket socket;
|
||||
private InputStream is;
|
||||
|
||||
//Output stream
|
||||
private OutputStream os;
|
||||
private Timer osTimer = new Timer();
|
||||
private Queue<BoatActionType> eventQueue = new ConcurrentLinkedQueue<>();
|
||||
private boolean upwindFlag = false, downwindFlag = false;
|
||||
static public final int PACKET_SENDING_INTERVAL_MS = 20;
|
||||
|
||||
private int clientId;
|
||||
|
||||
// private Boolean updateClient = true;
|
||||
private ByteArrayOutputStream crcBuffer;
|
||||
private boolean socketOpen = true;
|
||||
|
||||
@@ -83,6 +90,15 @@ public class ClientToServerThread implements Runnable {
|
||||
|
||||
thread = new Thread(this);
|
||||
thread.start();
|
||||
|
||||
osTimer.scheduleAtFixedRate(
|
||||
new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
processBoatActionQueue();
|
||||
}
|
||||
}, 0, PACKET_SENDING_INTERVAL_MS
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -181,18 +197,42 @@ public class ClientToServerThread implements Runnable {
|
||||
|
||||
|
||||
/**
|
||||
* Send the post-start race course information
|
||||
* @param boatActionMessage The message to send
|
||||
* Processes next element in the queue of events to send.
|
||||
*/
|
||||
public void sendBoatActionMessage(BoatActionMessage boatActionMessage) {
|
||||
private void processBoatActionQueue() {
|
||||
BoatActionType action = eventQueue.poll();
|
||||
if (action != null) {
|
||||
switch (action) {
|
||||
case MAINTAIN_HEADING:
|
||||
downwindFlag = upwindFlag = false; break;
|
||||
case DOWNWIND:
|
||||
downwindFlag = true; break;
|
||||
case UPWIND:
|
||||
upwindFlag = true; break;
|
||||
default:
|
||||
sendBoatAction(new BoatActionMessage(action)); break;
|
||||
}
|
||||
}
|
||||
if (downwindFlag) {
|
||||
sendBoatAction(new BoatActionMessage(BoatActionType.DOWNWIND));
|
||||
}
|
||||
if (upwindFlag) {
|
||||
sendBoatAction(new BoatActionMessage(BoatActionType.UPWIND));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a boat action of the given message type.
|
||||
* @param message The given message type.
|
||||
*/
|
||||
private void sendBoatAction(BoatActionMessage message) {
|
||||
try {
|
||||
os.write(boatActionMessage.getBuffer());
|
||||
os.write(message.getBuffer());
|
||||
} catch (IOException e) {
|
||||
clientLog("Could not write to server", 1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void closeSocket() {
|
||||
try {
|
||||
socket.close();
|
||||
@@ -245,11 +285,11 @@ public class ClientToServerThread implements Runnable {
|
||||
}
|
||||
}
|
||||
|
||||
public Thread getThread() {
|
||||
return thread;
|
||||
}
|
||||
|
||||
public int getClientId () {
|
||||
return clientId;
|
||||
}
|
||||
|
||||
public void sendBoatEvent(BoatActionType actionType) {
|
||||
eventQueue.add(actionType);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import javafx.scene.Node;
|
||||
import javafx.scene.input.KeyEvent;
|
||||
import javafx.scene.layout.Pane;
|
||||
import seng302.gameServer.MainServerThread;
|
||||
import seng302.gameServer.server.messages.BoatActionType;
|
||||
import seng302.model.RaceState;
|
||||
import seng302.model.Yacht;
|
||||
import seng302.model.stream.packets.StreamPacket;
|
||||
@@ -22,8 +23,6 @@ import seng302.model.stream.parser.PositionUpdateData.DeviceType;
|
||||
import seng302.model.stream.parser.RaceStatusData;
|
||||
import seng302.model.stream.xml.parser.RaceXMLData;
|
||||
import seng302.model.stream.xml.parser.RegattaXMLData;
|
||||
import seng302.gameServer.server.messages.BoatActionMessage;
|
||||
import seng302.gameServer.server.messages.BoatActionType;
|
||||
import seng302.utilities.StreamParser;
|
||||
import seng302.utilities.XMLParser;
|
||||
import seng302.visualiser.controllers.LobbyController;
|
||||
@@ -48,9 +47,6 @@ public class GameClient {
|
||||
|
||||
private ObservableList<String> clientLobbyList = FXCollections.observableArrayList();
|
||||
|
||||
private long lastSendingTime;
|
||||
private int KEY_STROKE_SENDING_FREQUENCY = 50;
|
||||
|
||||
public GameClient(Pane holder) {
|
||||
this.holderPane = holder;
|
||||
}
|
||||
@@ -174,17 +170,13 @@ public class GameClient {
|
||||
break;
|
||||
|
||||
case BOAT_XML:
|
||||
System.out.println("GOT SUM BOATS YAY :)");
|
||||
allBoatsMap = XMLParser.parseBoats(
|
||||
StreamParser.extractXmlMessage(packet)
|
||||
);
|
||||
clientLobbyList.clear();
|
||||
allBoatsMap.forEach((id, boat) -> {
|
||||
clientLobbyList.add(id + " " + boat.getBoatName());
|
||||
// System.out.println(id + " " + boat.getBoatName());
|
||||
|
||||
});
|
||||
// startRaceIfAllDataReceived();
|
||||
break;
|
||||
|
||||
case RACE_START_STATUS:
|
||||
@@ -279,47 +271,34 @@ public class GameClient {
|
||||
* Handle the key-pressed event from the text field.
|
||||
* @param e The key event triggering this call
|
||||
*/
|
||||
public void keyPressed(KeyEvent e) {
|
||||
BoatActionMessage boatActionMessage;
|
||||
long currentTime = System.currentTimeMillis();
|
||||
if (currentTime - lastSendingTime > KEY_STROKE_SENDING_FREQUENCY) {
|
||||
lastSendingTime = currentTime;
|
||||
switch (e.getCode()) {
|
||||
case SPACE: // align with vmg
|
||||
boatActionMessage = new BoatActionMessage(BoatActionType.VMG);
|
||||
socketThread.sendBoatActionMessage(boatActionMessage);
|
||||
break;
|
||||
case PAGE_UP: // upwind
|
||||
boatActionMessage = new BoatActionMessage(BoatActionType.UPWIND);
|
||||
socketThread.sendBoatActionMessage(boatActionMessage);
|
||||
break;
|
||||
case PAGE_DOWN: // downwind
|
||||
boatActionMessage = new BoatActionMessage(BoatActionType.DOWNWIND);
|
||||
socketThread.sendBoatActionMessage(boatActionMessage);
|
||||
break;
|
||||
case ENTER: // tack/gybe
|
||||
boatActionMessage = new BoatActionMessage(BoatActionType.TACK_GYBE);
|
||||
socketThread.sendBoatActionMessage(boatActionMessage);
|
||||
break;
|
||||
//TODO Allow a zoom in and zoom out methods
|
||||
case Z: // zoom in
|
||||
System.out.println("Zoom in");
|
||||
break;
|
||||
case X: // zoom out
|
||||
System.out.println("Zoom out");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void keyReleased(KeyEvent e) {
|
||||
private void keyPressed(KeyEvent e) {
|
||||
switch (e.getCode()) {
|
||||
//TODO 12/07/17 Determine the sail state and send the appropriate packet (eg. if sails are in, send a sail out packet)
|
||||
case SHIFT: // sails in/sails out
|
||||
BoatActionMessage boatActionMessage = new BoatActionMessage(
|
||||
BoatActionType.SAILS_IN);
|
||||
socketThread.sendBoatActionMessage(boatActionMessage);
|
||||
case SPACE: // align with vmg
|
||||
socketThread.sendBoatEvent(BoatActionType.VMG); break;
|
||||
case PAGE_UP: // upwind
|
||||
socketThread.sendBoatEvent(BoatActionType.UPWIND); break;
|
||||
case PAGE_DOWN: // downwind
|
||||
socketThread.sendBoatEvent(BoatActionType.DOWNWIND); break;
|
||||
case ENTER: // tack/gybe
|
||||
socketThread.sendBoatEvent(BoatActionType.TACK_GYBE); break;
|
||||
//TODO Allow a zoom in and zoom out methods
|
||||
case Z: // zoom in
|
||||
System.out.println("Zoom in");
|
||||
break;
|
||||
case X: // zoom out
|
||||
System.out.println("Zoom out");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void keyReleased(KeyEvent e) {
|
||||
switch (e.getCode()) {
|
||||
//TODO 12/07/17 Determine the sail state and send the appropriate packet (eg. if sails are in, send a sail out packet)
|
||||
case SHIFT: // sails in/sails out
|
||||
socketThread.sendBoatEvent(BoatActionType.SAILS_IN); break;
|
||||
case PAGE_UP:
|
||||
case PAGE_DOWN:
|
||||
socketThread.sendBoatEvent(BoatActionType.MAINTAIN_HEADING); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,8 +32,8 @@ import seng302.visualiser.fxObjects.BoatObject;
|
||||
import seng302.visualiser.fxObjects.CourseBoundary;
|
||||
import seng302.visualiser.fxObjects.Gate;
|
||||
import seng302.visualiser.fxObjects.Marker;
|
||||
import seng302.visualiser.map.Boundary;
|
||||
import seng302.visualiser.map.CanvasMap;
|
||||
import seng302.v.map.Boundary;
|
||||
import seng302.v.map.CanvasMap;
|
||||
|
||||
/**
|
||||
* Created by cir27 on 20/07/17.
|
||||
|
||||
@@ -4,15 +4,13 @@ import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import javafx.application.Platform;
|
||||
import javafx.collections.FXCollections;
|
||||
import javafx.collections.ListChangeListener;
|
||||
import javafx.collections.ObservableList;
|
||||
import javafx.fxml.FXML;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.ListView;
|
||||
import javafx.scene.control.TextArea;
|
||||
import javafx.scene.image.Image;
|
||||
import javafx.scene.image.ImageView;
|
||||
import javafx.scene.layout.GridPane;
|
||||
import javafx.scene.text.Text;
|
||||
import seng302.gameServer.GameStages;
|
||||
import seng302.gameServer.GameState;
|
||||
@@ -33,28 +31,26 @@ public class LobbyController {
|
||||
void notify(CloseStatus exitCause);
|
||||
}
|
||||
|
||||
@FXML
|
||||
private GridPane lobbyScreen;
|
||||
@FXML
|
||||
private Text lobbyIpText;
|
||||
@FXML
|
||||
private Button readyButton;
|
||||
@FXML
|
||||
private ListView<String> firstListView;
|
||||
private TextArea playerOneTxt;
|
||||
@FXML
|
||||
private ListView secondListView;
|
||||
private TextArea playerTwoTxt;
|
||||
@FXML
|
||||
private ListView thirdListView;
|
||||
private TextArea playerThreeTxt;
|
||||
@FXML
|
||||
private ListView fourthListView;
|
||||
private TextArea playerFourTxt;
|
||||
@FXML
|
||||
private ListView fifthListView;
|
||||
private TextArea playerFiveTxt;
|
||||
@FXML
|
||||
private ListView sixthListView;
|
||||
private TextArea playerSixTxt;
|
||||
@FXML
|
||||
private ListView seventhListView;
|
||||
private TextArea playerSevenTxt;
|
||||
@FXML
|
||||
private ListView eighthListView;
|
||||
private TextArea playerEightTxt;
|
||||
@FXML
|
||||
private ImageView firstImageView;
|
||||
@FXML
|
||||
@@ -72,79 +68,67 @@ public class LobbyController {
|
||||
@FXML
|
||||
private ImageView eighthImageView;
|
||||
|
||||
private List<ObservableList<String>> competitors = new ArrayList<>();
|
||||
private ObservableList<String> firstCompetitor = FXCollections.observableArrayList();
|
||||
private ObservableList<String> secondCompetitor = FXCollections.observableArrayList();
|
||||
private ObservableList<String> thirdCompetitor = FXCollections.observableArrayList();
|
||||
private ObservableList<String> fourthCompetitor = FXCollections.observableArrayList();
|
||||
private ObservableList<String> fifthCompetitor = FXCollections.observableArrayList();
|
||||
private ObservableList<String> sixthCompetitor = FXCollections.observableArrayList();
|
||||
private ObservableList<String> seventhCompetitor = FXCollections.observableArrayList();
|
||||
private ObservableList<String> eighthCompetitor = FXCollections.observableArrayList();
|
||||
|
||||
private List<ImageView> imageViews = new ArrayList<>();
|
||||
private List<ListView> listViews;
|
||||
private List<TextArea> listViews = new ArrayList<>();
|
||||
|
||||
private int MAX_NUM_PLAYERS = 8;
|
||||
|
||||
private List<LobbyCloseListener> lobbyListeners = new ArrayList<>();
|
||||
private ObservableList<String> players = FXCollections.observableArrayList();
|
||||
private ObservableList<String> players;
|
||||
|
||||
/**
|
||||
* Add all FXObjects to lists and initialize images.
|
||||
*/
|
||||
public void initialize() {
|
||||
imageViews = new ArrayList<>();
|
||||
Collections
|
||||
.addAll(imageViews, firstImageView, secondImageView, thirdImageView, fourthImageView,
|
||||
fifthImageView, sixthImageView, seventhImageView, eighthImageView);
|
||||
listViews = new ArrayList<>();
|
||||
Collections.addAll(listViews, firstListView, secondListView, thirdListView, fourthListView, fifthListView,
|
||||
sixthListView, seventhListView, eighthListView);
|
||||
competitors = new ArrayList<>();
|
||||
Collections.addAll(competitors, firstCompetitor, secondCompetitor, thirdCompetitor,
|
||||
fourthCompetitor, fifthCompetitor, sixthCompetitor, seventhCompetitor, eighthCompetitor);
|
||||
|
||||
Collections.addAll(listViews,
|
||||
playerOneTxt, playerTwoTxt, playerThreeTxt, playerFourTxt, playerFiveTxt, playerSixTxt,
|
||||
playerSevenTxt, playerEightTxt
|
||||
);
|
||||
Collections.addAll(imageViews,
|
||||
firstImageView, secondImageView, thirdImageView, fourthImageView,
|
||||
fifthImageView, sixthImageView, seventhImageView, eighthImageView
|
||||
);
|
||||
initialiseImageView();
|
||||
}
|
||||
|
||||
private void initialiseListView() {
|
||||
listViews.forEach(listView -> listView.getItems().clear());
|
||||
imageViews.forEach(gif -> gif.setVisible(false));
|
||||
competitors.forEach(ol -> ol.removeAll());
|
||||
/**
|
||||
* Updates player names.
|
||||
*/
|
||||
private void updatePlayers() {
|
||||
//Update players if one added.
|
||||
for (int i = 0; i < players.size(); i++) {
|
||||
competitors.get(i).add(players.get(i));
|
||||
listViews.get(i).setItems(competitors.get(i));
|
||||
listViews.get(i).setText(players.get(i));
|
||||
imageViews.get(i).setVisible(true);
|
||||
}
|
||||
//Update empty text fields if player left.
|
||||
for (int i = MAX_NUM_PLAYERS-1; i >= players.size(); i--) {
|
||||
listViews.get(i).setText("");
|
||||
imageViews.get(i).setVisible(false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets all images and hides them till players join.
|
||||
*/
|
||||
private void initialiseImageView() {
|
||||
imageViews.add(firstImageView);
|
||||
imageViews.add(secondImageView);
|
||||
imageViews.add(thirdImageView);
|
||||
imageViews.add(fourthImageView);
|
||||
imageViews.add(fifthImageView);
|
||||
imageViews.add(sixthImageView);
|
||||
imageViews.add(seventhImageView);
|
||||
imageViews.add(eighthImageView);
|
||||
for (int i = 0; i < MAX_NUM_PLAYERS; i++) {
|
||||
imageViews.get(i).setImage(
|
||||
for (ImageView viewer : imageViews) {
|
||||
viewer.setImage(
|
||||
new Image(
|
||||
RaceViewController.class.getResourceAsStream(
|
||||
"/pics/sail.png")
|
||||
)
|
||||
);
|
||||
viewer.setVisible(false);
|
||||
}
|
||||
}
|
||||
|
||||
@FXML
|
||||
public void leaveLobbyButtonPressed() {
|
||||
// TODO: 10/07/17 wmu16 - Finish function!
|
||||
// setContentPane("/views/StartScreenView.fxml");
|
||||
GameState.setCurrentStage(GameStages.CANCELLED);
|
||||
// TODO: 20/07/17 wmu16 - Implement some way of terminating the game
|
||||
// ClientState.setConnectedToHost(false);
|
||||
for (LobbyCloseListener readyListener : lobbyListeners)
|
||||
readyListener.notify(CloseStatus.LEAVE);
|
||||
|
||||
}
|
||||
|
||||
@FXML
|
||||
@@ -154,32 +138,6 @@ public class LobbyController {
|
||||
readyListener.notify(CloseStatus.READY);
|
||||
}
|
||||
|
||||
|
||||
// private static MediaPlayer mediaPlayer;
|
||||
//
|
||||
// private void playTheme() {
|
||||
// Random random = new Random(System.currentTimeMillis());
|
||||
// Integer rand = random.nextInt();
|
||||
// if(rand == 10) {
|
||||
// URL file = getClass().getResource("/music/Disturbed - down with the sickness.mp3");
|
||||
// Media hit = new Media(file.toString());
|
||||
// mediaPlayer = new MediaPlayer(hit);
|
||||
// mediaPlayer.play();
|
||||
// } else if(rand == 9) {
|
||||
// URL file = getClass().getResource("/music/Owl City - Fireflies.mp3");
|
||||
// Media hit = new Media(file.toString());
|
||||
// mediaPlayer = new MediaPlayer(hit);
|
||||
// mediaPlayer.play();
|
||||
// }
|
||||
// }
|
||||
|
||||
// private void switchToRaceView() {
|
||||
// if (!switchedPane) {
|
||||
// switchedPane = true;
|
||||
// setContentPane("/views/RaceView.fxml");
|
||||
// }
|
||||
// }
|
||||
// TODO: 26/07/17 cir27 - Could probably be done in a cleaner way.
|
||||
public void setTitle (String title) {
|
||||
lobbyIpText.setText(title);
|
||||
}
|
||||
@@ -191,12 +149,13 @@ public class LobbyController {
|
||||
public void setPlayerListSource (ObservableList<String> players) {
|
||||
this.players = players;
|
||||
players.addListener((ListChangeListener<? super String>) (lcl) ->
|
||||
Platform.runLater(this::initialiseListView)
|
||||
Platform.runLater(this::updatePlayers)
|
||||
);
|
||||
Platform.runLater(this::initialiseListView);
|
||||
Platform.runLater(this::updatePlayers);
|
||||
}
|
||||
|
||||
public void disableReadyButton () {
|
||||
readyButton.setDisable(true);
|
||||
readyButton.setVisible(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
package seng302.visualiser.map;
|
||||
|
||||
/**
|
||||
* The Boundary class represents a rectangle territorial boundary on a map. It
|
||||
* contains four extremity double values(N, E, S, W). N and S are represented as
|
||||
* latitudes in radians. E and W are represented as longitudes in radians.
|
||||
*
|
||||
* Created by Haoming on 10/5/17
|
||||
*/
|
||||
public class Boundary {
|
||||
|
||||
private double northLat, eastLng, southLat, westLng;
|
||||
|
||||
public Boundary(double northLat, double eastLng, double southLat, double westLng) {
|
||||
this.northLat = northLat;
|
||||
this.eastLng = eastLng;
|
||||
this.southLat = southLat;
|
||||
this.westLng = westLng;
|
||||
}
|
||||
|
||||
double getCentreLat() {
|
||||
return (northLat + southLat) / 2;
|
||||
}
|
||||
|
||||
double getCentreLng() {
|
||||
return (eastLng + westLng) / 2;
|
||||
}
|
||||
|
||||
double getNorthLat() {
|
||||
return northLat;
|
||||
}
|
||||
|
||||
double getEastLng() {
|
||||
return eastLng;
|
||||
}
|
||||
|
||||
double getSouthLat() {
|
||||
return southLat;
|
||||
}
|
||||
|
||||
double getWestLng() {
|
||||
return westLng;
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
package seng302.visualiser.map;
|
||||
|
||||
import java.net.URL;
|
||||
import javafx.geometry.Point2D;
|
||||
import javafx.scene.image.Image;
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import seng302.model.GeoPoint;
|
||||
|
||||
/**
|
||||
* CanvasMap retrieves a map image with given geo boundary from Google Map server.
|
||||
* By passing a rectangle like geo boundary, it returns a map image with the
|
||||
* highest resolution. However, due to free quote account usage limit, the maximum
|
||||
* resolution is only 1280 * 1280.
|
||||
*
|
||||
* Created by Haoming on 15/5/2017
|
||||
*/
|
||||
public class CanvasMap {
|
||||
|
||||
private Boundary boundary;
|
||||
private long width, height; // desired image size
|
||||
private int zoom;
|
||||
|
||||
private String KEY = "AIzaSyC-5oOShMCY5Oy_9L7guYMPUPFHDMr37wE";
|
||||
|
||||
public CanvasMap(Boundary boundary) {
|
||||
this.boundary = boundary;
|
||||
calculateOptimalMapSize();
|
||||
}
|
||||
|
||||
public Image getMapImage() {
|
||||
try {
|
||||
URL url = new URL(getRequest());
|
||||
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
|
||||
|
||||
return new Image(connection.getInputStream());
|
||||
} catch (Exception e) {
|
||||
System.out.println("[CanvasMap] Exception");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private String getRequest() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("https://maps.googleapis.com/maps/api/staticmap?");
|
||||
sb.append(String.format("center=%f,%f", boundary.getCentreLat(), boundary.getCentreLng()));
|
||||
sb.append(String.format("&zoom=%d", zoom));
|
||||
sb.append(String.format("&size=%dx%d&scale=2", width, height));
|
||||
sb.append("&style=feature:all|element:labels|visibility:off"); // hide all labels on map
|
||||
// sb.append(String.format("&markers=%f,%f", boundary.getSouthLat(), boundary.getWestLng()));
|
||||
// sb.append(String.format("&key=%s", KEY));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void calculateOptimalMapSize() {
|
||||
for (int z = 20; z > 0; z--) {
|
||||
MapSize mapSize = getMapSize(z, boundary);
|
||||
zoom = z;
|
||||
width = mapSize.width;
|
||||
height = mapSize.height;
|
||||
// if map size is valid, exit the loop as we have the highest resolution
|
||||
if (mapSize.isValid()) break;
|
||||
}
|
||||
}
|
||||
|
||||
private MapSize getMapSize(int zoom, Boundary boundary) {
|
||||
double scale = Math.pow(2, zoom);
|
||||
GeoPoint geoSW = new GeoPoint(boundary.getSouthLat(), boundary.getWestLng());
|
||||
GeoPoint geoNE = new GeoPoint(boundary.getNorthLat(), boundary.getEastLng());
|
||||
Point2D pointSW = MercatorProjection.toMapPoint(geoSW);
|
||||
Point2D pointNE = MercatorProjection.toMapPoint(geoNE);
|
||||
return new MapSize(Math.abs(pointNE.getX() - pointSW.getX()) * scale,
|
||||
Math.abs(pointNE.getY() - pointSW.getY()) * scale);
|
||||
}
|
||||
|
||||
class MapSize {
|
||||
long width, height;
|
||||
|
||||
MapSize(double width, double height) {
|
||||
this.width = Math.round(width);
|
||||
this.height = Math.round(height);
|
||||
}
|
||||
|
||||
/**
|
||||
* Map size is valid when width and height are both less than 640 pixels
|
||||
* @return true if both dimensions are less than 640px
|
||||
*/
|
||||
boolean isValid() {
|
||||
return Math.max(width, height) <= 640;
|
||||
}
|
||||
}
|
||||
|
||||
public long getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
public long getHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
public int getZoom() {
|
||||
return zoom;
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
package seng302.visualiser.map;
|
||||
|
||||
import javafx.geometry.Point2D;
|
||||
import seng302.model.GeoPoint;
|
||||
|
||||
/**
|
||||
* An utility class useful to convert between Geo locations and Mercator projection
|
||||
* planar coordinates.
|
||||
* Created by Haoming on 15/5/2017
|
||||
*/
|
||||
public class MercatorProjection {
|
||||
|
||||
private static final double MERCATOR_RANGE = 256;
|
||||
private static final double pixelsPerLngDegree = MERCATOR_RANGE / 360.0;
|
||||
private static final double pixelsPerLngRadian = MERCATOR_RANGE / (2 * Math.PI);
|
||||
|
||||
/**
|
||||
* A help function keeps the value in bound between -0.9999 and 0.9999.
|
||||
* @param value in bound value
|
||||
* @return the value in bound
|
||||
*/
|
||||
private static double bound(double value) {
|
||||
return Math.min(Math.max(value, -0.9999), 0.9999);
|
||||
}
|
||||
|
||||
/**
|
||||
* Projects a Geo Location (lat, lng) on a planar
|
||||
* @param geo GeoPoint (lat, lng) location to be projected
|
||||
* @return the projection Point2D (x, y) on planar
|
||||
*/
|
||||
static Point2D toMapPoint(GeoPoint geo) {
|
||||
double x, y;
|
||||
Point2D origin = new Point2D(MERCATOR_RANGE / 2.0, MERCATOR_RANGE / 2.0);
|
||||
x = (origin.getX() + geo.getLng() * pixelsPerLngDegree);
|
||||
|
||||
// NOTE(appleton): Truncating to 0.9999 effectively limits latitude to
|
||||
// 89.189. This is about a third of a tile past the edge of the world tile.
|
||||
double sinY = bound(Math.sin(Math.toRadians(geo.getLat())));
|
||||
y = origin.getY() + 0.5 * Math.log((1 + sinY) / (1 - sinY)) * (-pixelsPerLngRadian);
|
||||
return new Point2D(x, y);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the planar projection (x, y) back to Geo Location (lat, lng)
|
||||
* @param point Point2D (x, y) to be converted back
|
||||
* @return the original Geo location converted from the given projection point
|
||||
*/
|
||||
public static GeoPoint toMapGeo(Point2D point) {
|
||||
Point2D origin = new Point2D(MERCATOR_RANGE / 2.0, MERCATOR_RANGE / 2.0);
|
||||
double lng = (point.getX() - origin.getX()) / pixelsPerLngDegree;
|
||||
double latRadians = (point.getY() - origin.getY()) / (-pixelsPerLngRadian);
|
||||
double lat = Math.toDegrees(2 * Math.atan(Math.exp(latRadians)) - Math.PI / 2.0);
|
||||
return new GeoPoint(lat, lng);
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package seng302.visualiser.map;
|
||||
|
||||
import java.net.URL;
|
||||
import java.util.ResourceBundle;
|
||||
import javafx.fxml.FXML;
|
||||
import javafx.fxml.Initializable;
|
||||
import javafx.scene.canvas.Canvas;
|
||||
import javafx.scene.canvas.GraphicsContext;
|
||||
|
||||
public class TestMapController implements Initializable{
|
||||
|
||||
@FXML
|
||||
private Canvas mapCanvas;
|
||||
|
||||
@Override
|
||||
public void initialize(URL location, ResourceBundle resources) {
|
||||
GraphicsContext gc = mapCanvas.getGraphicsContext2D();
|
||||
Boundary bound = new Boundary(57.662943, 11.848501, 57.673945, 11.824966);
|
||||
CanvasMap canvasMap = new CanvasMap(bound);
|
||||
gc.drawImage(canvasMap.getMapImage(), 0, 0, canvasMap.getWidth(), canvasMap.getHeight());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user