Merge remote-tracking branch 'remotes/origin/master' into story66-collision

# Conflicts:
#	racevisionGame/src/main/java/mock/model/MockBoat.java
#	racevisionGame/src/main/java/mock/model/RaceLogic.java
#	racevisionGame/src/main/java/shared/model/CompoundMark.java
#	racevisionGame/src/main/java/shared/model/Race.java
#	racevisionGame/src/test/java/mock/model/MockBoatTest.java
This commit is contained in:
cbt24
2017-08-16 15:09:18 +12:00
185 changed files with 13956 additions and 3906 deletions
@@ -0,0 +1,288 @@
package mock.model;
import mock.app.MockOutput;
import mock.enums.ConnectionStateEnum;
import shared.exceptions.HandshakeException;
import mock.exceptions.SourceIDAllocationException;
import mock.model.commandFactory.CompositeCommand;
import network.Messages.*;
import network.Messages.Enums.JoinAcceptanceEnum;
import network.Messages.Enums.MessageType;
import network.Messages.Enums.RequestToJoinEnum;
import network.StreamRelated.MessageDeserialiser;
import network.StreamRelated.MessageSerialiser;
import visualiser.gameController.ControllerServer;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This class handles the client connection handshake, and creation of MockOutput and ControllerServer.
*/
public class ClientConnection implements Runnable {
/**
* The socket for the client's connection.
*/
private Socket socket;
/**
* Periodically sends HeartBeat messages to client.
*/
private HeartBeatService heartBeatService;
/**
* The thread the {@link HeartBeatService} runs on.
*/
private Thread heartBeatThread;
/**
* Used to allocate source ID to client, if they request to participate.
*/
private SourceIdAllocator sourceIdAllocator;
/**
* Latest snapshot of the race, to send to client. Currently only used for XML messages.
*/
private LatestMessages latestMessages;
/**
* Collection of commands from client for race to execute.
*/
private CompositeCommand compositeCommand;
/**
* The race the client is connected to.
*/
private RaceLogic raceLogic;
/**
* Used to send the race snapshot to client.
*/
private MockOutput mockOutput;
/**
* The thread the {@link MockOutput} runs on.
*/
private Thread mockOutputThread;
/**
* Used to receive client input, and turn it into commands.
*/
private ControllerServer controllerServer;
/**
* The thread the {@link ControllerServer} runs on.
*/
private Thread controllerServerThread;
/**
* Used to write messages to socket.
*/
private MessageSerialiser messageSerialiser;
/**
* Stores messages to write to socket.
*/
private BlockingQueue<AC35Data> outputQueue;
/**
* Used to read messages from socket.
*/
private MessageDeserialiser messageDeserialiser;
/**
* Stores messages read from socket.
*/
private BlockingQueue<AC35Data> inputQueue;
/**
* The state of the connection to the client.
*/
private ConnectionStateEnum connectionState = ConnectionStateEnum.UNKNOWN;
/**
* Creates a client connection, using a given socket.
* @param socket The socket which connects to the client.
* @param sourceIdAllocator Used to allocate a source ID for the client.
* @param latestMessages Latest race snapshot to send to client.
* @param compositeCommand Collection of commands for race to execute.
* @param raceLogic The race the client is connected to.
* @throws IOException Thrown if there is a problem with the client socket.
*/
public ClientConnection(Socket socket, SourceIdAllocator sourceIdAllocator, LatestMessages latestMessages, CompositeCommand compositeCommand, RaceLogic raceLogic) throws IOException {
this.socket = socket;
this.sourceIdAllocator = sourceIdAllocator;
this.latestMessages = latestMessages;
this.compositeCommand = compositeCommand;
this.raceLogic = raceLogic;
this.outputQueue = new LinkedBlockingQueue<>();
this.inputQueue = new LinkedBlockingQueue<>();
this.messageSerialiser = new MessageSerialiser(socket.getOutputStream(), outputQueue);
this.messageDeserialiser = new MessageDeserialiser(socket.getInputStream(), inputQueue);
new Thread(messageSerialiser, "ClientConnection()->MessageSerialiser thread " + messageSerialiser).start();
new Thread(messageDeserialiser, "ClientConnection()->MessageDeserialiser thread " + messageDeserialiser).start();
this.heartBeatService = new HeartBeatService(outputQueue);
this.heartBeatThread = new Thread(heartBeatService, "ClientConnection()->HeartBeatService thread " + heartBeatService);
this.heartBeatThread.start();
}
@Override
public void run() {
try {
handshake();
} catch (HandshakeException | SourceIDAllocationException e) {
Logger.getGlobal().log(Level.WARNING, "Client handshake failed.", e);
Thread.currentThread().interrupt();
return;
}
}
/**
* Initiates the handshake with the client.
* @throws HandshakeException Thrown if something goes wrong with the handshake.
* @throws SourceIDAllocationException Thrown if we cannot allocate a sourceID.
*/
private void handshake() throws SourceIDAllocationException, HandshakeException {
//This function is a bit messy, and could probably be refactored a bit.
connectionState = ConnectionStateEnum.WAITING_FOR_HANDSHAKE;
RequestToJoin requestToJoin = waitForRequestToJoin();
int allocatedSourceID = 0;
//If they want to participate, give them a source ID number.
if (requestToJoin.getRequestType() == RequestToJoinEnum.PARTICIPANT) {
allocatedSourceID = sourceIdAllocator.allocateSourceID();
this.controllerServer = new ControllerServer(compositeCommand, inputQueue, allocatedSourceID, raceLogic.getRace());
this.controllerServerThread = new Thread(controllerServer, "ClientConnection.run()->ControllerServer thread" + controllerServer);
this.controllerServerThread.start();
}
sendJoinAcceptanceMessage(allocatedSourceID);
this.mockOutput = new MockOutput(latestMessages, outputQueue);
this.mockOutputThread = new Thread(mockOutput, "ClientConnection.run()->MockOutput thread" + mockOutput);
this.mockOutputThread.start();
connectionState = ConnectionStateEnum.CONNECTED;
}
/**
* Waits until the client sends a {@link RequestToJoin} message, and returns it.
* @return The {@link RequestToJoin} message.
* @throws HandshakeException Thrown if we get interrupted while waiting.
*/
private RequestToJoin waitForRequestToJoin() throws HandshakeException {
try {
while (connectionState == ConnectionStateEnum.WAITING_FOR_HANDSHAKE) {
AC35Data message = inputQueue.take();
//We need to wait until they actually send a join request.
if (message.getType() == MessageType.REQUEST_TO_JOIN) {
return (RequestToJoin) message;
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new HandshakeException("Handshake failed. Thread: " + Thread.currentThread() + " was interrupted while waiting on the incoming message queue.", e);
}
throw new HandshakeException("Handshake was cancelled. Connection state is now: " + connectionState);
}
/**
* Sends the client a {@link JoinAcceptance} message, containing their assigned sourceID.
* @param sourceID The sourceID to assign to client.
* @throws HandshakeException Thrown if the thread is interrupted while placing message on the outgoing message queue.
*/
private void sendJoinAcceptanceMessage(int sourceID) throws HandshakeException {
//Send them the source ID.
JoinAcceptance joinAcceptance = new JoinAcceptance(JoinAcceptanceEnum.JOIN_SUCCESSFUL_PARTICIPANT, sourceID);
try {
outputQueue.put(joinAcceptance);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new HandshakeException("Handshake failed. Thread: " + Thread.currentThread() + " interrupted while placing JoinAcceptance message on outgoing message queue.", e);
}
}
/**
* Determines whether or not this connection is still alive.
* This is based off whether the {@link MessageSerialiser} is still alive.
* @return True if it is alive, false otherwise.
*/
public boolean isAlive() {
return messageSerialiser.isRunning();
}
/**
* Terminates this connection.
*/
public void terminate() {
if (this.heartBeatThread != null) {
this.heartBeatThread.interrupt();
}
if (this.mockOutputThread != null) {
this.mockOutputThread.interrupt();
}
if (this.controllerServerThread != null) {
this.controllerServerThread.interrupt();
}
}
}
@@ -0,0 +1,54 @@
package mock.model;
import shared.model.Bearing;
import shared.model.Wind;
import java.util.Random;
/**
* This class generates Wind objects for use in a MockRace.
* Initialised with a baseline wind speed and direction, and keeps it constant.
*/
public class ConstantWindGenerator implements WindGenerator {
/**
* The bearing the wind direction starts at.
*/
private Bearing windBaselineBearing;
/**
* The speed the wind starts at, in knots.
*/
private double windBaselineSpeed;
/**
* Creates a constant wind generator, with a baseline wind speed and direction.
* @param windBaselineBearing Baseline wind direction.
* @param windBaselineSpeed Baseline wind speed, in knots.
*/
public ConstantWindGenerator(Bearing windBaselineBearing, double windBaselineSpeed) {
this.windBaselineBearing = windBaselineBearing;
this.windBaselineSpeed = windBaselineSpeed;
}
@Override
public Wind generateBaselineWind() {
return new Wind(windBaselineBearing, windBaselineSpeed);
}
@Override
public Wind generateNextWind(Wind currentWind) {
return generateBaselineWind();
}
}
@@ -0,0 +1,110 @@
package mock.model;
import network.Messages.AC35Data;
import network.Messages.HeartBeat;
import shared.model.RunnableWithFramePeriod;
import java.util.concurrent.BlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This class is responsible for sending {@link HeartBeat} messages to queue.
*/
public class HeartBeatService implements RunnableWithFramePeriod {
/**
* Timestamp of the last sent heartbeat message.
*/
private long lastHeartbeatTime;
/**
* Period for the heartbeat - that is, how often we send it. Milliseconds.
*/
private long heartbeatPeriod = 2500;
/**
* The messages we're writing to the stream.
*/
private BlockingQueue<AC35Data> messagesToSend;
/**
* Sequence number for heartbeat messages.
*/
private int heartbeatSequenceNum = 1;
/**
* Constructs a new HeartBeatService to send heartBeat messages to a given outputStream.
* @param messagesToSend The queue to send heartBeat messages to.
*/
public HeartBeatService(BlockingQueue<AC35Data> messagesToSend) {
this.messagesToSend = messagesToSend;
this.lastHeartbeatTime = System.currentTimeMillis();
}
/**
* Increments the {@link #heartbeatSequenceNum} value, and returns it.
* @return Incremented heat beat number.
*/
private int getNextHeartBeatNumber(){
this.heartbeatSequenceNum++;
return this.heartbeatSequenceNum;
}
/**
* Generates the next heartbeat message and returns it. Increments the heartbeat sequence number.
* @return The next heartbeat message.
*/
private HeartBeat createHeartbeatMessage() {
HeartBeat heartBeat = new HeartBeat(getNextHeartBeatNumber());
return heartBeat;
}
/**
* Puts a HeartBeat message on the message queue.
* @throws InterruptedException Thrown if the thread is interrupted.
*/
private void sendHeartBeat() throws InterruptedException {
HeartBeat heartBeat = createHeartbeatMessage();
messagesToSend.put(heartBeat);
}
@Override
public void run() {
while (!Thread.interrupted()) {
long currentFrameTime = System.currentTimeMillis();
waitForFramePeriod(lastHeartbeatTime, currentFrameTime, heartbeatPeriod);
lastHeartbeatTime = currentFrameTime;
try {
sendHeartBeat();
} catch (InterruptedException e) {
Logger.getGlobal().log(Level.WARNING, "HeartBeatService: " + this + " sendHeartBeat() was interrupted on thread: " + Thread.currentThread(), e);
Thread.currentThread().interrupt();
return;
}
}
}
}
@@ -6,6 +6,8 @@ import network.Messages.LatestMessages;
import shared.dataInput.BoatDataSource;
import shared.dataInput.RaceDataSource;
import shared.dataInput.RegattaDataSource;
import shared.exceptions.BoatNotFoundException;
import shared.enums.RoundingType;
import shared.model.*;
import java.time.ZonedDateTime;
@@ -313,6 +315,8 @@ public class MockRace extends Race {
if (!finish && totalElapsedMilliseconds >= updatePeriodMilliseconds) {
checkPosition(boat, totalElapsedMilliseconds);
if (boat.getCurrentSpeed() == 0) {
newOptimalVMG(boat);
boat.setBearing(boat.calculateBearingToNextMarker());
@@ -372,6 +376,251 @@ public class MockRace extends Race {
}
}
/**
* Calculates the upper and lower bounds that the boat may have in order to not go outside of the course.
* @param boat The boat to check.
* @return An array of bearings. The first is the lower bound, the second is the upper bound.
*/
private Bearing[] calculateBearingBounds(MockBoat boat) {
Bearing[] bearings = new Bearing[2];
Bearing lowerBearing = Bearing.fromDegrees(0.001);
Bearing upperBearing = Bearing.fromDegrees(359.999);
double lastAngle = -1;
boolean lastAngleWasGood = false;
//Check all bearings between [0, 360).
for (double angle = 0; angle < 360; angle += 1) {
//Create bearing from angle.
Bearing bearing = Bearing.fromDegrees(angle);
//Check that if it is acceptable.
boolean bearingIsGood = this.checkBearingInsideCourse(bearing, boat.getCurrentPosition());
if (lastAngle != -1) {
if (lastAngleWasGood && !bearingIsGood) {
//We have flipped over from good bearings to bad bearings. So the last good bearing is the upper bearing.
upperBearing = Bearing.fromDegrees(lastAngle);
}
if (!lastAngleWasGood && bearingIsGood) {
//We have flipped over from bad bearings to good bearings. So the current bearing is the lower bearing.
lowerBearing = Bearing.fromDegrees(angle);
}
}
lastAngle = angle;
lastAngleWasGood = bearingIsGood;
}
//TODO BUG if it can't find either upper or lower, it returns (0, 359.999). Should return (boatbearing, boatbearing+0.0001)
bearings[0] = lowerBearing;
bearings[1] = upperBearing;
return bearings;
}
/**
* Checks if a given bearing, starting at a given position, would put a boat out of the course boundaries.
* @param bearing The bearing to check.
* @param position The position to start from.
* @return True if the bearing would keep the boat in the course, false if it would take it out of the course.
*/
private boolean checkBearingInsideCourse(Bearing bearing, GPSCoordinate position) {
//Get azimuth from bearing.
Azimuth azimuth = Azimuth.fromBearing(bearing);
//Tests to see if a point in front of the boat is out of bounds.
double epsilonMeters = 50d;
GPSCoordinate testCoord = GPSCoordinate.calculateNewPosition(position, epsilonMeters, azimuth);
//If it isn't inside the boundary, calculate new bearing.
if (GPSCoordinate.isInsideBoundary(testCoord, this.shrinkBoundary)) {
return true;
} else {
return false;
}
}
/**
* Checks to be run on boats rounding marks on the port side
* @param boat the boat that is rounding a mark
* @param roundingChecks the checks to run
* @param legBearing the direction of the leg
*/
private void boatRoundingCheckPort(MockBoat boat, List<GPSCoordinate> roundingChecks, Bearing legBearing) {
//boats must pass all checks in order to round a mark
//boolean for if boat has to/needs to pass through a gate
boolean gateCheck = boat.getCurrentLeg().getEndCompoundMark().getMark2() == null || boat.isBetweenGate(boat.getCurrentLeg().getEndCompoundMark());
Mark roundingMark = boat.getCurrentLeg().getEndCompoundMark().getMarkForRounding(legBearing);
switch (boat.getRoundingStatus()) {
case 0://hasn't started rounding
if (boat.isPortSide(roundingMark) &&
GPSCoordinate.passesLine(roundingMark.getPosition(),
roundingChecks.get(0), boat.getCurrentPosition(), legBearing) &&
gateCheck && boat.isBetweenGate(roundingMark, Mark.tempMark(roundingChecks.get(0)))) {
boat.increaseRoundingStatus();
if (boat.getCurrentLeg().getLegNumber() + 2 >= legs.size()){
//boat has finished race
boat.increaseRoundingStatus();
}
}
break;
case 1://has been parallel to the mark;
if (boat.isPortSide(roundingMark) &&
GPSCoordinate.passesLine(roundingMark.getPosition(),
roundingChecks.get(1), boat.getCurrentPosition(),
Bearing.fromDegrees(legBearing.degrees() - 90)) &&//negative 90 from bearing because of port rounding
boat.isBetweenGate(roundingMark, Mark.tempMark(roundingChecks.get(1)))) {
boat.increaseRoundingStatus();
}
break;
case 2://has traveled 180 degrees around the mark
//Move boat on to next leg.
boat.resetRoundingStatus();
Leg nextLeg = this.legs.get(boat.getCurrentLeg().getLegNumber() + 1);
boat.setCurrentLeg(nextLeg);
break;
}
}
/**
* Checks to be run on boats rounding marks on the starboard side
* @param boat the boat that is rounding a mark
* @param roundingChecks the checks to run
* @param legBearing the direction of the leg
*/
private void boatRoundingCheckStarboard(MockBoat boat, List<GPSCoordinate> roundingChecks, Bearing legBearing){
//boats must pass all checks in order to round a mark
//boolean for if boat has to/needs to pass through a gate
boolean gateCheck = boat.getCurrentLeg().getEndCompoundMark().getMark2() == null || boat.isBetweenGate(boat.getCurrentLeg().getEndCompoundMark());
Mark roundingMark = boat.getCurrentLeg().getEndCompoundMark().getMarkForRounding(legBearing);
switch (boat.getRoundingStatus()) {
case 0://hasn't started rounding
if (boat.isStarboardSide(roundingMark) &&
GPSCoordinate.passesLine(roundingMark.getPosition(),
roundingChecks.get(0), boat.getCurrentPosition(), legBearing) &&
gateCheck &&
boat.isBetweenGate(roundingMark, Mark.tempMark(roundingChecks.get(0)))) {
boat.increaseRoundingStatus();
if (boat.getCurrentLeg().getLegNumber() + 2 >= legs.size()){
//boat has finished race
boat.increaseRoundingStatus();
}
}
break;
case 1://has been parallel to the mark
if (boat.isStarboardSide(roundingMark) &&
GPSCoordinate.passesLine(roundingMark.getPosition(),
roundingChecks.get(1), boat.getCurrentPosition(), Bearing.fromDegrees(legBearing.degrees() + 90)) && //positive 90 from bearing because of starboard rounding
boat.isBetweenGate(roundingMark, Mark.tempMark(roundingChecks.get(1)))) {
boat.increaseRoundingStatus();
}
break;
case 2://has traveled 180 degrees around the mark
//Move boat on to next leg.
boat.resetRoundingStatus();
Leg nextLeg = this.legs.get(boat.getCurrentLeg().getLegNumber() + 1);
boat.setCurrentLeg(nextLeg);
break;
}
}
/**
* Checks if a boat has finished any legs, or has pulled out of race (DNF).
* @param boat The boat to check.
* @param timeElapsed The total time, in milliseconds, that has elapsed since the race started.
*/
protected void checkPosition(MockBoat boat, long timeElapsed) {
//The distance, in nautical miles, within which the boat needs to get in order to consider that it has reached the marker.
double epsilonNauticalMiles = boat.getCurrentLeg().getEndCompoundMark().getRoundingDistance(); //250 meters.
if (boat.calculateDistanceToNextMarker() < epsilonNauticalMiles) {
//Boat is within an acceptable distance from the mark.
GPSCoordinate startDirectionLinePoint = boat.getCurrentLeg().getStartCompoundMark().getMark1Position();
GPSCoordinate endDirectionLinePoint = boat.getCurrentLeg().getEndCompoundMark().getMark1Position();
Bearing bearingOfDirectionLine = GPSCoordinate.calculateBearing(startDirectionLinePoint, endDirectionLinePoint);
//use the direction line to create three invisible points that act as crossover lines a boat must cross
//to round a mark
double bearingToAdd;
if (boat.getCurrentLeg().getEndCompoundMark().getRoundingType() == RoundingType.Port ||
boat.getCurrentLeg().getEndCompoundMark().getRoundingType() == RoundingType.SP){
bearingToAdd = 90;
}else{
bearingToAdd = -90;
}
GPSCoordinate roundCheck1 = GPSCoordinate.calculateNewPosition(endDirectionLinePoint,
epsilonNauticalMiles, Azimuth.fromDegrees(bearingOfDirectionLine.degrees() + bearingToAdd));
GPSCoordinate roundCheck2;
try{
Leg nextLeg = legs.get(legs.indexOf(boat.getCurrentLeg()) + 1);
GPSCoordinate startNextDirectionLinePoint = nextLeg.getStartCompoundMark().getMark1Position();
GPSCoordinate endNextDirectionLinePoint = nextLeg.getEndCompoundMark().getMark1Position();
Bearing bearingOfNextDirectionLine = GPSCoordinate.calculateBearing(startNextDirectionLinePoint, endNextDirectionLinePoint);
roundCheck2 = GPSCoordinate.calculateNewPosition(endDirectionLinePoint,
epsilonNauticalMiles, Azimuth.fromDegrees(bearingOfNextDirectionLine.degrees() + bearingToAdd));
}catch(NullPointerException e){
//this is caused by the last leg not being having a leg after it
roundCheck2 = roundCheck1;
}
List<GPSCoordinate> roundingChecks = new ArrayList<GPSCoordinate>(Arrays.asList(roundCheck1, roundCheck2));
switch (boat.getCurrentLeg().getEndCompoundMark().getRoundingType()) {
case SP://Not yet implemented so these gates will be rounded port side
case Port:
boatRoundingCheckPort(boat, roundingChecks, bearingOfDirectionLine);
break;
case PS://not yet implemented so these gates will be rounded starboard side
case Starboard:
boatRoundingCheckStarboard(boat, roundingChecks, bearingOfDirectionLine);
break;
}
//Check if the boat has finished or stopped racing.
if (this.isLastLeg(boat.getCurrentLeg())) {
//Boat has finished.
boat.setTimeFinished(timeElapsed);
boat.setCurrentSpeed(0);
boat.setStatus(BoatStatusEnum.FINISHED);
}
}
}
/**
* Returns the number of boats that are still active in the race.
* They become inactive by either finishing or withdrawing.
@@ -402,6 +651,25 @@ public class MockRace extends Race {
return boats;
}
/**
* Returns a boat by sourceID.
* @param sourceID The source ID the boat.
* @return The boat.
* @throws BoatNotFoundException Thrown if there is not boat with the specified sourceID.
*/
public MockBoat getBoat(int sourceID) throws BoatNotFoundException {
for (MockBoat boat : boats) {
if (boat.getSourceID() == sourceID) {
return boat;
}
}
throw new BoatNotFoundException("Boat with sourceID: " + sourceID + " was not found.");
}
/**
* Changes the wind direction randomly, while keeping it within [windLowerBound, windUpperBound].
*/
@@ -434,7 +702,6 @@ public class MockRace extends Race {
}
public List<CompoundMark> getCompoundMarks() {
return compoundMarks;
}
}
}
@@ -1,18 +1,16 @@
package mock.model;
import javafx.animation.AnimationTimer;
import mock.model.commandFactory.CommandFactory;
import mock.model.commandFactory.CompositeCommand;
import mock.model.commandFactory.CommandFactory;
import network.Messages.Enums.BoatActionEnum;
import network.Messages.Enums.BoatStatusEnum;
import network.Messages.Enums.RaceStatusEnum;
import network.Messages.LatestMessages;
import visualiser.gameController.ControllerServer;
import shared.model.RunnableWithFramePeriod;
import java.util.Observable;
import java.util.Observer;
public class RaceLogic implements Observer, Runnable {
public class RaceLogic implements RunnableWithFramePeriod {
/**
* State of current race modified by this object
*/
@@ -28,11 +26,12 @@ public class RaceLogic implements Observer, Runnable {
* Initialises race loop with state and server message queue
* @param race state of race to modify
* @param messages to send to server
* @param compositeCommand Commands from clients to execute.
*/
public RaceLogic(MockRace race, LatestMessages messages) {
public RaceLogic(MockRace race, LatestMessages messages, CompositeCommand compositeCommand) {
this.race = race;
this.server = new RaceServer(race, messages);
this.commands = new CompositeCommand();
this.commands = compositeCommand;
}
/**
@@ -41,20 +40,23 @@ public class RaceLogic implements Observer, Runnable {
@Override
public void run() {
race.initialiseBoats();
this.countdownTimer.start();
countdown();
raceLoop();
}
/**
* Countdown timer until race starts.
*/
protected AnimationTimer countdownTimer = new AnimationTimer() {
private void countdown() {
long previousFrameTime = System.currentTimeMillis();
long currentTime = System.currentTimeMillis();
while (race.getRaceStatusEnum() != RaceStatusEnum.STARTED) {
@Override
public void handle(long arg0) {
long currentTime = System.currentTimeMillis();
//Update race time.
race.updateRaceTime(currentTime);
@@ -65,58 +67,39 @@ public class RaceLogic implements Observer, Runnable {
//Provide boat's with an estimated time at next mark until the race starts.
race.setBoatsTimeNextMark(race.getRaceClock().getCurrentTime());
//Parse the boat locations.
server.parseBoatLocations();
//Parse the race snapshot.
server.parseSnapshot();
//Parse the marks.
server.parseMarks();
// Change wind direction
race.changeWindDirection();
//Parse the race status.
server.parseRaceStatus();
if (race.getRaceStatusEnum() == RaceStatusEnum.STARTED) {
race.setBoatsStatusToRacing();
raceTimer.start();
this.stop();
}
//Update the animations timer's time.
currentTime = System.currentTimeMillis();
waitForFramePeriod(previousFrameTime, currentTime, 50);
previousFrameTime = currentTime;
}
};
}
/**
* Timer that runs for the duration of the race, until all boats finish.
*/
private AnimationTimer raceTimer = new AnimationTimer() {
private void raceLoop() {
/**
* Start time of loop, in milliseconds.
*/
long timeRaceStarted = System.currentTimeMillis();
long previousFrameTime = System.currentTimeMillis();
/**
* Current time during a loop iteration.
*/
long currentTime = System.currentTimeMillis();
/**
* The time of the previous frame, in milliseconds.
*/
long lastFrameTime = timeRaceStarted;
long framePeriod = currentTime - lastFrameTime;
@Override
public void handle(long arg0) {
while (race.getRaceStatusEnum() != RaceStatusEnum.FINISHED) {
//Get the current time.
currentTime = System.currentTimeMillis();
long currentTime = System.currentTimeMillis();
//Execute commands from clients.
commands.execute();
//Update race time.
race.updateRaceTime(currentTime);
@@ -125,16 +108,15 @@ public class RaceLogic implements Observer, Runnable {
if (race.getNumberOfActiveBoats() != 0) {
//Get the time period of this frame.
framePeriod = currentTime - lastFrameTime;
long framePeriod = currentTime - previousFrameTime;
//For each boat, we update its position, and generate a BoatLocationMessage.
for (MockBoat boat : race.getBoats()) {
//If it is still racing, update its position.
if (boat.getStatus() == BoatStatusEnum.RACING) {
commands.execute();
race.updatePosition(boat, framePeriod, race.getRaceClock().getDurationMilli());
race.getColliderRegistry().rayCast(boat);
}
}
@@ -143,28 +125,23 @@ public class RaceLogic implements Observer, Runnable {
//Otherwise, the race is over!
raceFinished.start();
race.setRaceStatusEnum(RaceStatusEnum.FINISHED);
this.stop();
}
if (race.getNumberOfActiveBoats() != 0) {
// Change wind direction
race.changeWindDirection();
//Parse the boat locations.
server.parseBoatLocations();
//Parse the marks.
server.parseMarks();
//Parse the race status.
server.parseRaceStatus();
//Parse the race snapshot.
server.parseSnapshot();
//Update the last frame time.
this.lastFrameTime = currentTime;
previousFrameTime = currentTime;
}
waitForFramePeriod(previousFrameTime, currentTime, 50);
previousFrameTime = currentTime;
}
};
}
/**
* Broadcast that the race has finished.
@@ -174,7 +151,7 @@ public class RaceLogic implements Observer, Runnable {
@Override
public void handle(long now) {
server.parseRaceStatus();
server.parseSnapshot();
if (iters > 500) {
stop();
@@ -183,12 +160,12 @@ public class RaceLogic implements Observer, Runnable {
}
};
@Override
public void update(Observable o, Object arg) {
ControllerServer server = (ControllerServer)o;
BoatActionEnum action = server.getAction();
MockBoat boat = race.getBoats().get(0);
commands.addCommand(CommandFactory.createCommand(race, boat, action));
/**
* Returns the race state that this RaceLogic is simulating.
* @return Race state this RaceLogic is simulating.
*/
public MockRace getRace() {
return race;
}
}
@@ -1,10 +1,9 @@
package mock.model;
import network.Messages.BoatLocation;
import network.Messages.BoatStatus;
import network.Messages.LatestMessages;
import network.Messages.RaceStatus;
import network.Messages.*;
import network.Messages.Enums.BoatLocationDeviceEnum;
import network.Utils.AC35UnitConverter;
import shared.model.Bearing;
import shared.model.CompoundMark;
import shared.model.Constants;
import shared.model.Mark;
@@ -19,10 +18,6 @@ public class RaceServer {
private MockRace race;
private LatestMessages latestMessages;
/**
* The sequence number of the latest RaceStatus message sent or received.
*/
private int raceStatusSequenceNumber = 1;
/**
* The sequence number of the latest BoatLocation message sent or received.
@@ -37,29 +32,56 @@ public class RaceServer {
/**
* Parses an individual marker boat, and sends it to mockOutput.
* @param mark The marker boat to parse.
* Parses the race to create a snapshot, and places it in latestMessages.
*/
private void parseIndividualMark(Mark mark) {
public void parseSnapshot() {
List<AC35Data> snapshotMessages = new ArrayList<>();
//Parse the boat locations.
snapshotMessages.addAll(parseBoatLocations());
//Parse the marks.
snapshotMessages.addAll(parseMarks());
//Parse the race status.
snapshotMessages.add(parseRaceStatus());
latestMessages.setSnapshot(snapshotMessages);
}
/**
* Parses an individual marker boat, and returns it.
* @param mark The marker boat to parse.
* @return The BoatLocation message.
*/
private BoatLocation parseIndividualMark(Mark mark) {
//Create message.
BoatLocation boatLocation = new BoatLocation(
mark.getSourceID(),
mark.getPosition().getLatitude(),
mark.getPosition().getLongitude(),
this.boatLocationSequenceNumber,
0, 0,
BoatLocationDeviceEnum.Mark,
Bearing.fromDegrees(0),
0,
race.getRaceClock().getCurrentTimeMilli());
//Iterates the sequence number.
this.boatLocationSequenceNumber++;
this.latestMessages.setBoatLocation(boatLocation);
return boatLocation;
}
/**
* Parse the compound marker boats through mock output.
* Parse the compound marker boats, and returns a list of BoatLocation messages.
* @return BoatLocation messages for each mark.
*/
public void parseMarks() {
private List<BoatLocation> parseMarks() {
List<BoatLocation> markLocations = new ArrayList<>(race.getCompoundMarks().size());
for (CompoundMark compoundMark : race.getCompoundMarks()) {
//Get the individual marks from the compound mark.
@@ -68,54 +90,65 @@ public class RaceServer {
//If they aren't null, parse them (some compound marks only have one mark).
if (mark1 != null) {
this.parseIndividualMark(mark1);
markLocations.add(this.parseIndividualMark(mark1));
}
if (mark2 != null) {
this.parseIndividualMark(mark2);
markLocations.add(this.parseIndividualMark(mark2));
}
}
return markLocations;
}
/**
* Parse the boats in the race, and send it to mockOutput.
* Parse the boats in the race, and returns all of their BoatLocation messages.
* @return List of BoatLocation messages, for each boat.
*/
public void parseBoatLocations() {
private List<BoatLocation> parseBoatLocations() {
List<BoatLocation> boatLocations = new ArrayList<>(race.getBoats().size());
//Parse each boat.
for (MockBoat boat : race.getBoats()) {
this.parseIndividualBoatLocation(boat);
boatLocations.add(this.parseIndividualBoatLocation(boat));
}
return boatLocations;
}
/**
* Parses an individual boat, and sends it to mockOutput.
* Parses an individual boat, and returns it.
* @param boat The boat to parse.
* @return The BoatLocation message.
*/
private void parseIndividualBoatLocation(MockBoat boat) {
private BoatLocation parseIndividualBoatLocation(MockBoat boat) {
BoatLocation boatLocation = new BoatLocation(
boat.getSourceID(),
boat.getCurrentPosition().getLatitude(),
boat.getCurrentPosition().getLongitude(),
this.boatLocationSequenceNumber,
boat.getBearing().degrees(),
BoatLocationDeviceEnum.RacingYacht,
boat.getBearing(),
boat.getCurrentSpeed(),
race.getRaceClock().getCurrentTimeMilli());
//Iterates the sequence number.
this.boatLocationSequenceNumber++;
this.latestMessages.setBoatLocation(boatLocation);
return boatLocation;
}
/**
* Parses the race status, and sends it to mockOutput.
* Parses the race status, and returns it.
* @return The race status message.
*/
public void parseRaceStatus() {
private RaceStatus parseRaceStatus() {
//A race status message contains a list of boat statuses.
List<BoatStatus> boatStatuses = new ArrayList<>();
@@ -133,21 +166,19 @@ public class RaceServer {
}
//Convert wind direction and speed to ints. //TODO this conversion should be done inside the racestatus class.
int windDirectionInt = AC35UnitConverter.encodeHeading(race.getWindDirection().degrees());
int windSpeedInt = (int) (race.getWindSpeed() * Constants.KnotsToMMPerSecond);
//Create race status object, and send it.
RaceStatus raceStatus = new RaceStatus(
RaceStatus.currentMessageVersionNumber,
System.currentTimeMillis(),
race.getRaceId(),
race.getRaceStatusEnum().getValue(),
race.getRaceStatusEnum(),
race.getRaceClock().getStartingTimeMilli(),
windDirectionInt,
windSpeedInt,
race.getRaceType().getValue(),
race.getWindDirection(),
race.getWindSpeed(),
race.getRaceType(),
boatStatuses);
this.latestMessages.setRaceStatus(raceStatus);
return raceStatus;
}
}
@@ -0,0 +1,242 @@
package mock.model;
import shared.model.Bearing;
import shared.model.Wind;
import java.util.Random;
/**
* This class generates Wind objects for use in a MockRace.
* Bounds on bearing and speed can be specified.
* Wind can be completely random, or random incremental change.
*/
public class RandomWindGenerator implements WindGenerator {
/**
* The bearing the wind direction starts at.
*/
private Bearing windBaselineBearing;
/**
* The lower bearing angle that the wind may have.
*/
private Bearing windBearingLowerBound;
/**
* The upper bearing angle that the wind may have.
*/
private Bearing windBearingUpperBound;
/**
* The speed the wind starts at, in knots.
*/
private double windBaselineSpeed;
/**
* The lower speed that the wind may have, in knots.
*/
private double windSpeedLowerBound;
/**
* The upper speed that the wind may have, in knots.
*/
private double windSpeedUpperBound;
/**
* Creates a wind generator, with a baseline, lower bound, and upper bound, for the wind speed and direction.
* @param windBaselineBearing Baseline wind direction.
* @param windBearingLowerBound Lower bound for wind direction.
* @param windBearingUpperBound Upper bound for wind direction.
* @param windBaselineSpeed Baseline wind speed, in knots.
* @param windSpeedLowerBound Lower bound for wind speed, in knots.
* @param windSpeedUpperBound Upper bound for wind speed, in knots.
*/
public RandomWindGenerator(Bearing windBaselineBearing, Bearing windBearingLowerBound, Bearing windBearingUpperBound, double windBaselineSpeed, double windSpeedLowerBound, double windSpeedUpperBound) {
this.windBaselineBearing = windBaselineBearing;
this.windBearingLowerBound = windBearingLowerBound;
this.windBearingUpperBound = windBearingUpperBound;
this.windBaselineSpeed = windBaselineSpeed;
this.windSpeedLowerBound = windSpeedLowerBound;
this.windSpeedUpperBound = windSpeedUpperBound;
}
@Override
public Wind generateBaselineWind() {
return new Wind(windBaselineBearing, windBaselineSpeed);
}
/**
* Generates a random Wind object, that is within the provided bounds.
* @return Generated wind object.
*/
public Wind generateRandomWind() {
double windSpeed = generateRandomWindSpeed();
Bearing windBearing = generateRandomWindBearing();
return new Wind(windBearing, windSpeed);
}
/**
* Generates a random wind speed within the specified bounds. In knots.
* @return Wind speed, in knots.
*/
private double generateRandomWindSpeed() {
double randomSpeedKnots = generateRandomValueInBounds(windSpeedLowerBound, windSpeedUpperBound);
return randomSpeedKnots;
}
/**
* Generates a random wind bearing within the specified bounds.
* @return Wind bearing.
*/
private Bearing generateRandomWindBearing() {
double randomBearingDegrees = generateRandomValueInBounds(windBearingLowerBound.degrees(), windBearingUpperBound.degrees());
return Bearing.fromDegrees(randomBearingDegrees);
}
/**
* Generates a random value within a specified interval.
* @param lowerBound The lower bound of the interval.
* @param upperBound The upper bound of the interval.
* @return A random value within the interval.
*/
private static double generateRandomValueInBounds(double lowerBound, double upperBound) {
float proportion = new Random().nextFloat();
double delta = upperBound - lowerBound;
double amount = delta * proportion;
double finalAmount = amount + lowerBound;
return finalAmount;
}
/**
* Generates a new value within an interval, given a start value, chance to change, and change amount.
* @param lowerBound Lower bound of interval.
* @param upperBound Upper bound of interval.
* @param currentValue The current value to change.
* @param changeAmount The amount to change by.
* @param chanceToChange The change to actually change the value.
* @return The new value.
*/
private static double generateNextValueInBounds(double lowerBound, double upperBound, double currentValue, double changeAmount, double chanceToChange) {
float chance = new Random().nextFloat();
if (chance <= chanceToChange) {
currentValue += changeAmount;
} else if (chance <= (2 * chanceToChange)) {
currentValue -= changeAmount;
}
currentValue = clamp(lowerBound, upperBound, currentValue);
return currentValue;
}
@Override
public Wind generateNextWind(Wind currentWind) {
double windSpeed = generateNextWindSpeed(currentWind.getWindSpeed());
Bearing windBearing = generateNextWindBearing(currentWind.getWindDirection());
return new Wind(windBearing, windSpeed);
}
/**
* Generates the next wind speed to use.
* @param windSpeed Current wind speed, in knots.
* @return Next wind speed, in knots.
*/
private double generateNextWindSpeed(double windSpeed) {
double chanceToChange = 0.2;
double changeAmount = 0.1;
double nextWindSpeed = generateNextValueInBounds(
windSpeedLowerBound,
windSpeedUpperBound,
windSpeed,
changeAmount,
chanceToChange);
return nextWindSpeed;
}
/**
* Generates the next wind speed to use.
* @param windBearing Current wind bearing.
* @return Next wind speed.
*/
private Bearing generateNextWindBearing(Bearing windBearing) {
double chanceToChange = 0.2;
double changeAmount = 0.5;
double nextWindBearingDegrees = generateNextValueInBounds(
windBearingLowerBound.degrees(),
windBearingUpperBound.degrees(),
windBearing.degrees(),
changeAmount,
chanceToChange);
return Bearing.fromDegrees(nextWindBearingDegrees);
}
/**
* Clamps a value to be within an interval.
* @param lower Lower bound of the interval.
* @param upper Upper bound of the interval.
* @param value Value to clamp.
* @return The clamped value.
*/
private static double clamp(double lower, double upper, double value) {
if (value > upper) {
value = upper;
} else if (value < lower) {
value = lower;
}
return value;
}
}
@@ -0,0 +1,70 @@
package mock.model;
import mock.exceptions.SourceIDAllocationException;
import java.util.ArrayList;
import java.util.List;
/**
* This class is responsible for allocating boat source IDs for use in a race, upon request.
*/
public class SourceIdAllocator {
/**
* This list contains all unallocated source IDs.
*/
List<Integer> unallocatedIDs = new ArrayList<>();
/**
* This list contains all allocated source IDs.
*/
List<Integer> allocatedIDs = new ArrayList<>();
/**
* Creates a source ID allocator, using the given list of unallocated source IDs.
* @param unallocatedIDs List of unallocated source IDs.
*/
public SourceIdAllocator(List<Integer> unallocatedIDs) {
//We need to copy the list.
this.unallocatedIDs.addAll(unallocatedIDs);
}
/**
* Allocates a source ID for a boat.
* @return The allocated source ID.
* @throws SourceIDAllocationException Thrown if we cannot allocate any more source IDs.
*/
public synchronized int allocateSourceID() throws SourceIDAllocationException {
if (!unallocatedIDs.isEmpty()) {
int sourceID = unallocatedIDs.remove(0);
allocatedIDs.add(sourceID);
return sourceID;
} else {
throw new SourceIDAllocationException("Could not allocate a source ID.");
}
}
/**
* Returns a source ID to the source ID allocator, so that it can be reused.
* @param sourceID Source ID to return.
*/
public void returnSourceID(Integer sourceID) {
//We remove an Integer, not an int, so that we remove by value not by index.
allocatedIDs.remove(sourceID);
unallocatedIDs.add(sourceID);
}
}
@@ -0,0 +1,555 @@
//package mock.model;
//
//import javafx.animation.AnimationTimer;
//import network.Messages.BoatLocation;
//import network.Messages.BoatStatus;
//import network.Messages.Enums.BoatStatusEnum;
//import network.Messages.Enums.RaceStatusEnum;
//import network.Messages.LatestMessages;
//import network.Messages.RaceStatus;
//import network.Utils.AC35UnitConverter;
//import shared.dataInput.BoatDataSource;
//import shared.dataInput.RaceDataSource;
//import shared.dataInput.RegattaDataSource;
//import shared.model.*;
//
//import java.time.ZonedDateTime;
//import java.time.temporal.ChronoUnit;
//import java.util.ArrayList;
//import java.util.Iterator;
//import java.util.List;
//import java.util.Map;
//
//import static java.lang.Math.cos;
//
///**
// * Unused class, copy of MockRace so methods can be deleted once they are moved (more of a checklist)
// */
//public class SplitTODO {
//
//
// /**
// * Represents a yacht race.
// * Has a course, boats, boundaries, etc...
// * Is responsible for simulating the race, and sending messages to a MockOutput instance.
// */
// public class MockRace extends Race {
//
// /**
// * Constructs a race object with a given RaceDataSource, BoatDataSource, and RegattaDataSource and sends events to the given mockOutput.
// * @param boatDataSource Data source for boat related data (yachts and marker boats).
// * @param raceDataSource Data source for race related data (participating boats, legs, etc...).
// * @param regattaDataSource Data source for race related data (course name, location, timezone, etc...).
// * @param latestMessages The LatestMessages to send events to.
// * @param polars The polars table to be used for boat simulation.
// * @param timeScale The timeScale for the race. See {@link Constants#RaceTimeScale}.
// */
// public MockRace(BoatDataSource boatDataSource, RaceDataSource raceDataSource, RegattaDataSource regattaDataSource, LatestMessages latestMessages, Polars polars, int timeScale) {
//
// super(boatDataSource, raceDataSource, regattaDataSource, latestMessages);
//
// this.scaleFactor = timeScale;
// }
//
//
//
// /**
// * Parse the compound marker boats through mock output.
// */
// private void parseMarks() {
// for (CompoundMark compoundMark : this.compoundMarks) {
//
// //Get the individual marks from the compound mark.
// Mark mark1 = compoundMark.getMark1();
// Mark mark2 = compoundMark.getMark2();
//
// //If they aren't null, parse them (some compound marks only have one mark).
// if (mark1 != null) {
// this.parseIndividualMark(mark1);
// }
//
// if (mark2 != null) {
// this.parseIndividualMark(mark2);
// }
//
// }
// }
//
// /**
// * Parses an individual marker boat, and sends it to mockOutput.
// * @param mark The marker boat to parse.
// */
// private void parseIndividualMark(Mark mark) {
//
// //Create message.
// BoatLocation boatLocation = new BoatLocation(
// mark.getSourceID(),
// mark.getPosition().getLatitude(),
// mark.getPosition().getLongitude(),
// this.boatLocationSequenceNumber,
// 0, 0,
// this.raceClock.getCurrentTimeMilli());
//
// //Iterates the sequence number.
// this.boatLocationSequenceNumber++;
//
// this.latestMessages.setBoatLocation(boatLocation);
//
//
// }
//
// /**
// * Parse the boats in the race, and send it to mockOutput.
// */
// private void parseBoatLocations() {
//
// //Parse each boat.
// for (MockBoat boat : this.boats) {
//
// this.parseIndividualBoatLocation(boat);
//
// }
//
// }
//
// /**
// * Parses an individual boat, and sends it to mockOutput.
// * @param boat The boat to parse.
// */
// private void parseIndividualBoatLocation(MockBoat boat) {
//
// BoatLocation boatLocation = new BoatLocation(
// boat.getSourceID(),
// boat.getCurrentPosition().getLatitude(),
// boat.getCurrentPosition().getLongitude(),
// this.boatLocationSequenceNumber,
// boat.getBearing().degrees(),
// boat.getCurrentSpeed(),
// this.raceClock.getCurrentTimeMilli());
//
// //Iterates the sequence number.
// this.boatLocationSequenceNumber++;
//
// this.latestMessages.setBoatLocation(boatLocation);
//
// }
//
//
// /**
// * Updates the race time to a specified value, in milliseconds since the unix epoch.
// * @param currentTime Milliseconds since unix epoch.
// */
// private void updateRaceTime(long currentTime) {
// this.raceClock.setUTCTime(currentTime);
// }
//
//
// /**
// * Updates the race status enumeration based on the current time.
// */
// private void updateRaceStatusEnum() {
//
// //The millisecond duration of the race. Negative means it hasn't started, so we flip sign.
// long timeToStart = - this.raceClock.getDurationMilli();
//
//
// if (timeToStart > Constants.RacePreStartTime) {
// //Time > 3 minutes is the prestart period.
// this.setRaceStatusEnum(RaceStatusEnum.PRESTART);
//
// } else if ((timeToStart <= Constants.RacePreStartTime) && (timeToStart >= Constants.RacePreparatoryTime)) {
// //Time between [1, 3] minutes is the warning period.
// this.setRaceStatusEnum(RaceStatusEnum.WARNING);
//
// } else if ((timeToStart <= Constants.RacePreparatoryTime) && (timeToStart > 0)) {
// //Time between (0, 1] minutes is the preparatory period.
// this.setRaceStatusEnum(RaceStatusEnum.PREPARATORY);
//
// } else {
// //Otherwise, the race has started!
// this.setRaceStatusEnum(RaceStatusEnum.STARTED);
//
// }
//
//
// }
//
// /**
// * Parses the race status, and sends it to mockOutput.
// */
// private void parseRaceStatus() {
//
// //A race status message contains a list of boat statuses.
// List<BoatStatus> boatStatuses = new ArrayList<>();
//
// //Add each boat status to the status list.
// for (MockBoat boat : this.boats) {
//
// BoatStatus boatStatus = new BoatStatus(
// boat.getSourceID(),
// boat.getStatus(),
// boat.getCurrentLeg().getLegNumber(),
// boat.getEstimatedTimeAtNextMark().toInstant().toEpochMilli() );
//
// boatStatuses.add(boatStatus);
// }
//
//
// //Convert wind direction and speed to ints. //TODO this conversion should be done inside the racestatus class.
// int windDirectionInt = AC35UnitConverter.encodeHeading(this.getWindDirection().degrees());
// int windSpeedInt = (int) (this.getWindSpeed() * Constants.KnotsToMMPerSecond);
//
// //Create race status object, and send it.
// RaceStatus raceStatus = new RaceStatus(
// System.currentTimeMillis(),
// this.raceId,
// this.getRaceStatusEnum().getValue(),
// this.raceClock.getStartingTimeMilli(),
// windDirectionInt,
// windSpeedInt,
// this.getRaceType().getValue(),
// boatStatuses);
//
//
// this.latestMessages.setRaceStatus(raceStatus);
//
//
// }
//
//
// /**
// * Sets the status of all boats in the race to RACING.
// */
// private void setBoatsStatusToRacing() {
//
// for (MockBoat boat : this.boats) {
// boat.setStatus(BoatStatusEnum.RACING);
// }
// }
//
//
// /**
// * Sets the estimated time at next mark for each boat to a specified time. This is used during the countdown timer to provide this value to boat before the race starts.
// * @param time The time to provide to each boat.
// */
// private void setBoatsTimeNextMark(ZonedDateTime time) {
//
// for (MockBoat boat : this.boats) {
// boat.setEstimatedTimeAtNextMark(time);
// }
// }
//
//
// /**
// * Countdown timer until race starts.
// */
// protected AnimationTimer countdownTimer = new AnimationTimer() {
//
//
// long currentTime = System.currentTimeMillis();
//
// @Override
// public void handle(long arg0) {
//
// //Update race time.
// updateRaceTime(currentTime);
//
// //Update the race status based on the current time.
// updateRaceStatusEnum();
//
// //Provide boat's with an estimated time at next mark until the race starts.
// setBoatsTimeNextMark(raceClock.getCurrentTime());
//
// //Parse the boat locations.
// parseBoatLocations();
//
// //Parse the marks.
// parseMarks();
//
// // Change wind direction
// changeWindDirection();
//
// //Parse the race status.
// parseRaceStatus();
//
//
// if (getRaceStatusEnum() == RaceStatusEnum.STARTED) {
// setBoatsStatusToRacing();
// raceTimer.start();
// this.stop();
// }
//
// //Update the animations timer's time.
// currentTime = System.currentTimeMillis();
// }
// };
//
//
// /**
// * Timer that runs for the duration of the race, until all boats finish.
// */
// private AnimationTimer raceTimer = new AnimationTimer() {
//
// /**
// * Start time of loop, in milliseconds.
// */
// long timeRaceStarted = System.currentTimeMillis();
//
// /**
// * Current time during a loop iteration.
// */
// long currentTime = System.currentTimeMillis();
//
// /**
// * The time of the previous frame, in milliseconds.
// */
// long lastFrameTime = timeRaceStarted;
//
// @Override
// public void handle(long arg0) {
//
// //Get the current time.
// currentTime = System.currentTimeMillis();
//
// //Update race time.
// updateRaceTime(currentTime);
//
//
// //As long as there is at least one boat racing, we still simulate the race.
// if (getNumberOfActiveBoats() != 0) {
//
// //Get the time period of this frame.
// long framePeriod = currentTime - lastFrameTime;
//
// //For each boat, we update its position, and generate a BoatLocationMessage.
// for (MockBoat boat : boats) {
//
// //If it is still racing, update its position.
// if (boat.getStatus() == BoatStatusEnum.RACING) {
//
// updatePosition(boat, framePeriod, raceClock.getDurationMilli());
//
// }
//
// }
//
// } else {
// //Otherwise, the race is over!
// raceFinished.start();
// setRaceStatusEnum(RaceStatusEnum.FINISHED);
// this.stop();
// }
//
// if (getNumberOfActiveBoats() != 0) {
// // Change wind direction
// changeWindDirection();
//
// //Parse the boat locations.
// parseBoatLocations();
//
// //Parse the marks.
// parseMarks();
//
// //Parse the race status.
// parseRaceStatus();
//
//
// //Update the last frame time.
// this.lastFrameTime = currentTime;
// }
// }
// };
//
// /**
// * Broadcast that the race has finished.
// */
// protected AnimationTimer raceFinished = new AnimationTimer(){
// int iters = 0;
// @Override
// public void handle(long now) {
//
// parseRaceStatus();
//
// if (iters > 500) {
// stop();
// }
// iters++;
// }
// };
//
//
// /**
// * Calculates a boat's VMG.
// * @param boat The boat to calculate VMG for.
// * @return VMG for the specified boat.
// */
// private VMG calculateVMG(MockBoat boat) {
//
//
// //Find the VMG inside these bounds.
// VMG bestVMG = boat.getPolars().calculateVMG(this.getWindDirection(), this.getWindSpeed(), boat.calculateBearingToNextMarker(), Bearing.fromDegrees(0d), Bearing.fromDegrees(359.99999d));
//
//
// return bestVMG;
//
// }
//
//
// /**
// * Determines whether or not a given VMG improves the velocity of a boat, if it were currently using currentVMG.
// * @param currentVMG The current VMG of the boat.
// * @param potentialVMG The new VMG to test.
// * @param bearingToDestination The bearing between the boat and its destination.
// * @return True if the new VMG is improves velocity, false otherwise.
// */
// private boolean improvesVelocity(VMG currentVMG, VMG potentialVMG, Bearing bearingToDestination) {
//
// //Calculates the angle between the boat and its destination.
// Angle angleBetweenDestAndHeading = Angle.fromDegrees(currentVMG.getBearing().degrees() - bearingToDestination.degrees());
//
// //Calculates the angle between the new VMG and the boat's destination.
// Angle angleBetweenDestAndNewVMG = Angle.fromDegrees(potentialVMG.getBearing().degrees() - bearingToDestination.degrees());
//
//
// //Calculate the boat's current velocity.
// double currentVelocity = Math.cos(angleBetweenDestAndHeading.radians()) * currentVMG.getSpeed();
//
// //Calculate the potential velocity with the new VMG.
// double vmgVelocity = Math.cos(angleBetweenDestAndNewVMG.radians()) * potentialVMG.getSpeed();
//
// //Return whether or not the new VMG gives better velocity.
// return vmgVelocity > currentVelocity;
//
// }
//
// /**
// * Determines whether or not a given VMG improves the velocity of a boat.
// * @param boat The boat to test.
// * @param vmg The new VMG to test.
// * @return True if the new VMG is improves velocity, false otherwise.
// */
// private boolean improvesVelocity(MockBoat boat, VMG vmg) {
//
// //Get the boats "current" VMG.
// VMG boatVMG = new VMG(boat.getCurrentSpeed(), boat.getBearing());
//
// //Check if the new VMG is better than the boat's current VMG.
// return this.improvesVelocity(boatVMG, vmg, boat.calculateBearingToNextMarker());
//
// }
//
//
// /**
// * Calculates the distance a boat has travelled and updates its current position according to this value.
// *
// * @param boat The boat to be updated.
// * @param updatePeriodMilliseconds The time, in milliseconds, since the last update.
// * @param totalElapsedMilliseconds The total number of milliseconds that have elapsed since the start of the race.
// */
// protected void updatePosition(MockBoat boat, long updatePeriodMilliseconds, long totalElapsedMilliseconds) {
//
// //Checks if the current boat has finished the race or not.
// boolean finish = this.isLastLeg(boat.getCurrentLeg());
//
// if (!finish) {
//
//
// //Calculates the distance travelled, in meters, in the current timeslice.
// double distanceTravelledMeters = boat.calculateMetersTravelled(updatePeriodMilliseconds);
//
// //Scale it.
// distanceTravelledMeters = distanceTravelledMeters * this.scaleFactor;
//
//
// //Move the boat forwards that many meters, and advances its time counters by enough milliseconds.
// boat.moveForwards(distanceTravelledMeters, updatePeriodMilliseconds * this.scaleFactor);
//
// long tackPeriod = 15000;
// if (boat.getTimeSinceTackChange() > tackPeriod) {
// //Calculate the new VMG.
// VMG newVMG = this.calculateVMG(boat);
//
//
// //If the new vmg improves velocity, use it.
// if (improvesVelocity(boat, newVMG)) {
// boat.setVMG(newVMG);
//
// }
// }
//
// this.updateEstimatedTime(boat);
//
//
// //Check the boats position (update leg and stuff).
// this.checkPosition(boat, totalElapsedMilliseconds);
//
// }
//
// }
//
//
// /**
// * Checks if a boat has finished any legs, or has pulled out of race (DNF).
// * @param boat The boat to check.
// * @param timeElapsed The total time, in milliseconds, that has elapsed since the race started.
// */
// protected void checkPosition(MockBoat boat, long timeElapsed) {
//
// //The distance, in nautical miles, within which the boat needs to get in order to consider that it has reached the marker.
// double epsilonNauticalMiles = 100.0 / Constants.NMToMetersConversion; //100 meters. TODO should be more like 5-10.
//
// if (boat.calculateDistanceToNextMarker() < epsilonNauticalMiles) {
// //Boat has reached its target marker, and has moved on to a new leg.
//
//
//
// //Calculate how much the boat overshot the marker by.
// double overshootMeters = boat.calculateDistanceToNextMarker();
//
//
// //Move boat on to next leg.
// Leg nextLeg = this.legs.get(boat.getCurrentLeg().getLegNumber() + 1);
// boat.setCurrentLeg(nextLeg);
//
// //Add overshoot distance into the distance travelled for the next leg.
// boat.setDistanceTravelledInLeg(overshootMeters);
//
// //Setting a high value for this allows the boat to immediately do a large turn, as it needs to in order to get to the next mark.
// boat.setTimeSinceTackChange(999999);
//
//
// //Check if the boat has finished or stopped racing.
//
// if (this.isLastLeg(boat.getCurrentLeg())) {
// //Boat has finished.
// boat.setTimeFinished(timeElapsed);
// boat.setCurrentSpeed(0);
// boat.setStatus(BoatStatusEnum.FINISHED);
//
// }
//
// }
//
// }
//
// /**
// * Updates the boat's estimated time to next mark if positive
// * @param boat to estimate time given its velocity
// */
// private void updateEstimatedTime(MockBoat boat) {
//
// double velocityToMark = boat.getCurrentSpeed() * cos(boat.getBearing().radians() - boat.calculateBearingToNextMarker().radians()) / Constants.KnotsToMMPerSecond;
//
// if (velocityToMark > 0) {
//
// //Calculate milliseconds until boat reaches mark.
// long timeFromNow = (long) (1000 * boat.calculateDistanceToNextMarker() / velocityToMark);
//
// //Calculate time at which it will reach mark.
// ZonedDateTime timeAtMark = this.raceClock.getCurrentTime().plus(timeFromNow, ChronoUnit.MILLIS);
// boat.setEstimatedTimeAtNextMark(timeAtMark);
// }
//
// }
// }
//}
@@ -1,249 +1,29 @@
package mock.model;
import shared.model.Bearing;
import shared.model.Wind;
import java.util.Random;
/**
* This class generates Wind objects for use in a MockRace.
* Bounds on bearing and speed can be specified.
* Wind can be completely random, or random incremental change.
* Interface for wind generators. It allows for generating a baseline wind, and subsequent winds.
*/
public class WindGenerator {
public interface WindGenerator {
/**
* The bearing the wind direction starts at.
*/
private Bearing windBaselineBearing;
/**
* The lower bearing angle that the wind may have.
*/
private Bearing windBearingLowerBound;
/**
* The upper bearing angle that the wind may have.
*/
private Bearing windBearingUpperBound;
/**
* The speed the wind starts at, in knots.
*/
private double windBaselineSpeed;
/**
* The lower speed that the wind may have, in knots.
*/
private double windSpeedLowerBound;
/**
* The upper speed that the wind may have, in knots.
*/
private double windSpeedUpperBound;
/**
* Creates a wind generator, with a baseline, lower bound, and upper bound, for the wind speed and direction.
* @param windBaselineBearing Baseline wind direction.
* @param windBearingLowerBound Lower bound for wind direction.
* @param windBearingUpperBound Upper bound for wind direction.
* @param windBaselineSpeed Baseline wind speed, in knots.
* @param windSpeedLowerBound Lower bound for wind speed, in knots.
* @param windSpeedUpperBound Upper bound for wind speed, in knots.
*/
public WindGenerator(Bearing windBaselineBearing, Bearing windBearingLowerBound, Bearing windBearingUpperBound, double windBaselineSpeed, double windSpeedLowerBound, double windSpeedUpperBound) {
this.windBaselineBearing = windBaselineBearing;
this.windBearingLowerBound = windBearingLowerBound;
this.windBearingUpperBound = windBearingUpperBound;
this.windBaselineSpeed = windBaselineSpeed;
this.windSpeedLowerBound = windSpeedLowerBound;
this.windSpeedUpperBound = windSpeedUpperBound;
}
/**
* Generates a wind object using the baseline wind speed and bearing.
* @return Baseline wind object.
*/
public Wind generateBaselineWind() {
return new Wind(windBaselineBearing, windBaselineSpeed);
}
Wind generateBaselineWind();
/**
* Generates a random Wind object, that is within the provided bounds.
* @return Generated wind object.
*/
public Wind generateRandomWind() {
double windSpeed = generateRandomWindSpeed();
Bearing windBearing = generateRandomWindBearing();
return new Wind(windBearing, windSpeed);
}
/**
* Generates a random wind speed within the specified bounds. In knots.
* @return Wind speed, in knots.
*/
private double generateRandomWindSpeed() {
double randomSpeedKnots = generateRandomValueInBounds(windSpeedLowerBound, windSpeedUpperBound);
return randomSpeedKnots;
}
/**
* Generates a random wind bearing within the specified bounds.
* @return Wind bearing.
*/
private Bearing generateRandomWindBearing() {
double randomBearingDegrees = generateRandomValueInBounds(windBearingLowerBound.degrees(), windBearingUpperBound.degrees());
return Bearing.fromDegrees(randomBearingDegrees);
}
/**
* Generates a random value within a specified interval.
* @param lowerBound The lower bound of the interval.
* @param upperBound The upper bound of the interval.
* @return A random value within the interval.
*/
private static double generateRandomValueInBounds(double lowerBound, double upperBound) {
float proportion = new Random().nextFloat();
double delta = upperBound - lowerBound;
double amount = delta * proportion;
double finalAmount = amount + lowerBound;
return finalAmount;
}
/**
* Generates a new value within an interval, given a start value, chance to change, and change amount.
* @param lowerBound Lower bound of interval.
* @param upperBound Upper bound of interval.
* @param currentValue The current value to change.
* @param changeAmount The amount to change by.
* @param chanceToChange The change to actually change the value.
* @return The new value.
*/
private static double generateNextValueInBounds(double lowerBound, double upperBound, double currentValue, double changeAmount, double chanceToChange) {
float chance = new Random().nextFloat();
if (chance <= chanceToChange) {
currentValue += changeAmount;
} else if (chance <= (2 * chanceToChange)) {
currentValue -= changeAmount;
}
currentValue = clamp(lowerBound, upperBound, currentValue);
return currentValue;
}
/**
* Generates the next Wind object, that is within the provided bounds. This randomly increases or decreases the wind's speed and bearing.
* Generates the next Wind object, according to the implementation of the wind generator.
* @param currentWind The current wind to change. This is not modified.
* @return Generated wind object.
*/
public Wind generateNextWind(Wind currentWind) {
double windSpeed = generateNextWindSpeed(currentWind.getWindSpeed());
Bearing windBearing = generateNextWindBearing(currentWind.getWindDirection());
return new Wind(windBearing, windSpeed);
}
/**
* Generates the next wind speed to use.
* @param windSpeed Current wind speed, in knots.
* @return Next wind speed, in knots.
*/
private double generateNextWindSpeed(double windSpeed) {
double chanceToChange = 0.2;
double changeAmount = 0.1;
double nextWindSpeed = generateNextValueInBounds(
windSpeedLowerBound,
windSpeedUpperBound,
windSpeed,
changeAmount,
chanceToChange);
return nextWindSpeed;
}
/**
* Generates the next wind speed to use.
* @param windBearing Current wind bearing.
* @return Next wind speed.
*/
private Bearing generateNextWindBearing(Bearing windBearing) {
double chanceToChange = 0.2;
double changeAmount = 0.5;
double nextWindBearingDegrees = generateNextValueInBounds(
windBearingLowerBound.degrees(),
windBearingUpperBound.degrees(),
windBearing.degrees(),
changeAmount,
chanceToChange);
return Bearing.fromDegrees(nextWindBearingDegrees);
}
/**
* Clamps a value to be within an interval.
* @param lower Lower bound of the interval.
* @param upper Upper bound of the interval.
* @param value Value to clamp.
* @return The clamped value.
*/
private static double clamp(double lower, double upper, double value) {
if (value > upper) {
value = upper;
} else if (value < lower) {
value = lower;
}
return value;
}
Wind generateNextWind(Wind currentWind);
}
@@ -1,8 +1,10 @@
package mock.model.commandFactory;
import mock.exceptions.CommandConstructionException;
import mock.model.MockBoat;
import mock.model.MockRace;
import network.Messages.Enums.BoatActionEnum;
import network.Messages.BoatAction;
import shared.exceptions.BoatNotFoundException;
/**
* Factory class for Command objects
@@ -11,17 +13,28 @@ public class CommandFactory {
/**
* Generates a command on a race and boat corresponding to the protocol action number.
* @param race to receive command
* @param boat to receive command in race
* @param action number to select command
* @return
* @return The command to execute the given action.
* @throws CommandConstructionException Thrown if the command cannot be constructed (e.g., unknown action type).
*/
public static Command createCommand(MockRace race, MockBoat boat, BoatActionEnum action) {
switch(action) {
public static Command createCommand(MockRace race, BoatAction action) throws CommandConstructionException {
MockBoat boat = null;
try {
boat = race.getBoat(action.getSourceID());
} catch (BoatNotFoundException e) {
throw new CommandConstructionException("Could not create command for BoatAction: " + action + ". Boat with sourceID: " + action.getSourceID() + " not found.", e);
}
switch(action.getBoatAction()) {
case AUTO_PILOT: return new VMGCommand(race, boat);
case TACK_GYBE: return new TackGybeCommand(race, boat);
case UPWIND: return new WindCommand(race, boat, true);
case DOWNWIND: return new WindCommand(race, boat, false);
default: return null; // TODO - please please have discussion over what to default to
default: throw new CommandConstructionException("Could not create command for BoatAction: " + action + ". Unknown BoatAction.");
}
}
}
@@ -2,31 +2,52 @@ package mock.model.commandFactory;
import mock.model.MockBoat;
import mock.model.MockRace;
import shared.model.Bearing;
/**
* Created by David on 2/08/2017.
* Command class for tacking and gybing
*/
public class TackGybeCommand implements Command {
private MockRace race;
private MockBoat boat;
/**
* Constructor for class
* @param race mock race
* @param boat mock boat to update
*/
public TackGybeCommand(MockRace race, MockBoat boat) {
this.race = race;
this.boat = boat;
}
//The refactoring of MockRace will require changes to be made
@Override
public void execute() {
/*VMG newVMG = boat.getPolars().calculateVMG(
race.getWindDirection(),
race.getWindSpeed(),
boat.calculateBearingToNextMarker(),
Bearing.fromDegrees(0d),
Bearing.fromDegrees(359.99999d));
VMG boatVMG = new VMG(boat.getCurrentSpeed(), boat.getBearing());
if(race.improvesVelocity(boatVMG, newVMG, boat.calculateBearingToNextMarker())){
boat.setVMG(newVMG);
}*/
boat.setAutoVMG(false);
double boatAngle = boat.getBearing().degrees();
double windAngle =race.getWindDirection().degrees();
double differenceAngle = calcDistance(boatAngle, windAngle);
double angleA = windAngle + differenceAngle;
double angleB = windAngle - differenceAngle;
if(angleA % 360 == boatAngle){
boat.setBearing(Bearing.fromDegrees(angleB));
} else {
boat.setBearing(Bearing.fromDegrees(angleA));
}
}
/**
* Method to calculate smallest angle between 2 angles
* @param degreeA first angle degree
* @param degreeB second angle degree
* @return the calculated smallest angle
*/
public double calcDistance(double degreeA, double degreeB){
double phi = Math.abs(degreeB - degreeA) % 360;
return phi > 180 ? 360 - phi : phi;
}
}
@@ -4,26 +4,28 @@ import mock.model.MockBoat;
import mock.model.MockRace;
/**
* Created by David on 2/08/2017.
* Command class for autoVMG
*/
public class VMGCommand implements Command {
private MockRace race;
private MockBoat boat;
/**
* Constructor for class
* @param race mock race
* @param boat mock boat to update
*/
public VMGCommand(MockRace race, MockBoat boat) {
this.race = race;
this.boat = boat;
}
//The refactoring of MockRace will require changes to be made
@Override
public void execute() {
/*VMG newVMG = boat.getPolars().calculateVMG(
race.getWindDirection(),
race.getWindSpeed(),
boat.calculateBearingToNextMarker(),
Bearing.fromDegrees(0d),
Bearing.fromDegrees(359.99999d));
boat.setVMG(newVMG);*/
if (boat.getAutoVMG()){
boat.setAutoVMG(false);
} else {
boat.setAutoVMG(true);
}
}
}
@@ -20,13 +20,17 @@ public class WindCommand implements Command {
@Override
public void execute() {
boat.setAutoVMG(false);
double wind = race.getWindDirection().degrees();
double heading = boat.getBearing().degrees();
double offset = 3.0;
offset *= direction;
if(wind - heading < 0) offset *= -1;
double headWindDelta = wind - heading;
if ((headWindDelta < 0) || (headWindDelta > 180)) offset *= -1;
boat.setBearing(Bearing.fromDegrees(heading + offset));
}