package seng302.Model; import javafx.animation.AnimationTimer; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import org.geotools.referencing.GeodeticCalculator; import seng302.DataInput.RaceDataSource; import SharedModel.*; import seng302.Networking.MessageEncoders.RaceVisionByteEncoder; import seng302.Networking.MockOutput; import seng302.Networking.Utils.BoatLocationMessage; import java.awt.geom.Point2D; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Parent class for races * Created by fwy13 on 3/03/17. */ public class Race implements Runnable { //protected BoatInRace[] startingBoats; protected ObservableList startingBoats; protected List legs; protected int boatsFinished = 0; protected long totalTimeElapsed; protected int heartbeat = 0; protected int scaleFactor; protected int PRERACE_TIME = 120000; //time in milliseconds to pause during pre-race private int lastFPS = 20; private int dnfChance = 0; //percentage chance a boat fails at each checkpoint private MockOutput mockOutput; /** * Initailiser for Race * * @param boats Takes in an array of boats that are participating in the race. * @param legs Number of marks in order that the boats pass in order to complete the race. * @param scaleFactor for race */ public Race(List boats, List legs, int scaleFactor, MockOutput mockOutput) { this.startingBoats = FXCollections.observableArrayList(boats); this.legs = legs; this.legs.add(new Leg("Finish", this.legs.size())); this.scaleFactor = scaleFactor; this.mockOutput = mockOutput; if (startingBoats != null && startingBoats.size() > 0) { initialiseBoats(); } } public Race(RaceDataSource raceData, int scaleFactor, MockOutput mockOutput) { this(raceData.getBoats(), raceData.getLegs(), scaleFactor, mockOutput); } /** * Calculates the boats next GPS position based on its distance travelled and heading * * @param oldCoordinates GPS coordinates of the boat's starting position * @param distanceTravelled distance in nautical miles * @param azimuth boat's current direction. Value between -180 and 180 * @return The boat's new coordinate */ public static GPSCoordinate calculatePosition(GPSCoordinate oldCoordinates, double distanceTravelled, double azimuth) { //Find new coordinate using current heading and distance GeodeticCalculator geodeticCalculator = new GeodeticCalculator(); //Load start point into calculator Point2D startPoint = new Point2D.Double(oldCoordinates.getLongitude(), oldCoordinates.getLatitude()); geodeticCalculator.setStartingGeographicPoint(startPoint); //load direction and distance tranvelled into calculator geodeticCalculator.setDirection(azimuth, distanceTravelled * Constants.NMToMetersConversion); //get new point Point2D endPoint = geodeticCalculator.getDestinationGeographicPoint(); return new GPSCoordinate(endPoint.getY(), endPoint.getX()); } /** * Runnable for the thread. */ public void run() { initialiseBoats(); countdownTimer(); } /** * Starts the heartbeat timer, which sends a heartbeat message every so often (i.e., 5 seconds). */ /** * Countdown timer until race starts. Use PRERACE_TIME to set countdown duration. */ protected void countdownTimer() { AnimationTimer timer = new AnimationTimer() { long currentTime = System.currentTimeMillis(); long startTime = currentTime + (PRERACE_TIME / scaleFactor); long minutes; long currentTimeInSeconds; long remainingSeconds; long hours; long timeLeft; @Override public void handle(long arg0) { timeLeft = startTime - currentTime; if (timeLeft <= 0) { stop(); simulateRace(); } else { currentTimeInSeconds = (timeLeft * scaleFactor) / 1000; minutes = currentTimeInSeconds / 60; remainingSeconds = currentTimeInSeconds % 60; hours = minutes / 60; minutes = minutes % 60; } currentTime = System.currentTimeMillis(); } }; timer.start(); } /** * Takes total time elapsed and format to hour:minute:second * * @return Formatted time as string */ protected String calcTimer() { long minutes; long currentTimeInSeconds; long remainingSeconds; long hours; currentTimeInSeconds = (totalTimeElapsed * scaleFactor) / 1000; minutes = currentTimeInSeconds / 60; remainingSeconds = currentTimeInSeconds % 60; hours = minutes / 60; minutes = minutes % 60; return String.format("Race clock: %02d:%02d:%02d", hours, minutes, remainingSeconds); } /** * Starts the Race Simulation, playing the race start to finish with the timescale. * This prints the boats participating, the order that the events occur in time order, and the respective information of the events. */ private void simulateRace() { System.setProperty("javafx.animation.fullspeed", "true"); for (BoatInRace boat : startingBoats) { boat.setStarted(true); } new AnimationTimer() { //Start time of loop. long timeRaceStarted = System.currentTimeMillis(); @Override public void handle(long arg0) { if (boatsFinished < startingBoats.size()) { //Get the current time. long currentTime = System.currentTimeMillis(); //Update the total elapsed time. totalTimeElapsed = currentTime - timeRaceStarted; //For each boat, we update it's position, and generate a BoatLocationMessage. for (BoatInRace boat : startingBoats) { if (boat != null && !boat.isFinished()) { //Update position. updatePosition(boat, Math.round(1000 / lastFPS) > 20 ? 15 : Math.round(1000 / lastFPS)); checkPosition(boat, totalTimeElapsed); //Generate a boat location message for the updated boat. BoatLocationMessage boatLocationMessage = new BoatLocationMessage(); boatLocationMessage.setTime(currentTime); boatLocationMessage.setSourceID(boat.getSourceID()); boatLocationMessage.setSequenceNumber(boat.getNextSequenceNumber()); boatLocationMessage.setDeviceType(BoatLocationMessage.RacingYacht); boatLocationMessage.setLatitude(BoatLocationMessage.convertCoordinateDoubleToInt(boat.getCurrentPosition().getLatitude())); boatLocationMessage.setLongitude(BoatLocationMessage.convertCoordinateDoubleToInt(boat.getCurrentPosition().getLongitude())); boatLocationMessage.setAltitude(0);//Junk value. boatLocationMessage.setHeading(BoatLocationMessage.convertHeadingDoubleToInt(boat.getHeading())); boatLocationMessage.setPitch((short) 0);//Junk value. boatLocationMessage.setRoll((short) 0);//Junk value. boatLocationMessage.setBoatSpeed(BoatLocationMessage.convertBoatSpeedDoubleToInt(boat.getVelocity())); boatLocationMessage.setBoatCOG(0);//Junk value. boatLocationMessage.setBoatSOG(0);//Junk value. boatLocationMessage.setApparentWindSpeed(0);//Junk value. boatLocationMessage.setApparentWindAngle((short) 0);//Junk value. boatLocationMessage.setTrueWindSpeed(0);//Junk value. boatLocationMessage.setTrueWindDirection(0);//Junk value. boatLocationMessage.setTrueWindAngle((short) 0);//Junk value. boatLocationMessage.setCurrentDrift(0);//Junk value. boatLocationMessage.setCurrentSet(0);//Junk value. boatLocationMessage.setRudderAngle((short) 0);//Junk value. //We have finished creating the message. mockOutput.parseBoatLocation(boat); } else { stop(); } } } } }.start(); } /** * Update position of boats in race, no position if on starting leg or DNF. */ protected void updatePositions() { FXCollections.sort(startingBoats, (a, b) -> b.getCurrentLeg().getLegNumber() - a.getCurrentLeg().getLegNumber()); for (BoatInRace boat : startingBoats) { if (boat != null) { boat.setPosition(Integer.toString(startingBoats.indexOf(boat) + 1)); //System.out.println(boat.toString() + " " + boat.getPosition());//TEMP debug print if (boat.getCurrentLeg().getName().equals("DNF") || boat.getCurrentLeg().getLegNumber() == 0) boat.setPosition("-"); } } //System.out.println("=====");//TEMP debug print } public void initialiseBoats() { Leg officialStart = legs.get(0); String name = officialStart.getName(); Marker endMarker = officialStart.getEndMarker(); ArrayList startMarkers = getSpreadStartingPositions(); for (int i = 0; i < startingBoats.size(); i++) { BoatInRace boat = startingBoats.get(i); if (boat != null) { boat.setScaledVelocity(boat.getVelocity() * scaleFactor); Leg startLeg = new Leg(name, 0); boat.setCurrentPosition(startMarkers.get(i).getAverageGPSCoordinate()); startLeg.setStartMarker(startMarkers.get(i)); startLeg.setEndMarker(endMarker); startLeg.calculateDistance(); boat.setCurrentLeg(startLeg); boat.setHeading(boat.calculateHeading()); } } } /** * Creates a list of starting positions for the different boats, so they do not appear cramped at the start line * * @return list of starting positions */ public ArrayList getSpreadStartingPositions() { int nBoats = startingBoats.size(); Marker marker = legs.get(0).getStartMarker(); GeodeticCalculator initialCalc = new GeodeticCalculator(); initialCalc.setStartingGeographicPoint(marker.getMark1().getLongitude(), marker.getMark1().getLatitude()); initialCalc.setDestinationGeographicPoint(marker.getMark2().getLongitude(), marker.getMark2().getLatitude()); double azimuth = initialCalc.getAzimuth(); double distanceBetweenMarkers = initialCalc.getOrthodromicDistance(); double distanceBetweenBoats = distanceBetweenMarkers / (nBoats + 1); GeodeticCalculator positionCalc = new GeodeticCalculator(); positionCalc.setStartingGeographicPoint(marker.getMark1().getLongitude(), marker.getMark1().getLatitude()); ArrayList positions = new ArrayList<>(); for (int i = 0; i < nBoats; i++) { positionCalc.setDirection(azimuth, distanceBetweenBoats); Point2D position = positionCalc.getDestinationGeographicPoint(); positions.add(new Marker(new GPSCoordinate(position.getY(), position.getX()))); positionCalc = new GeodeticCalculator(); positionCalc.setStartingGeographicPoint(position); } return positions; } /** * Sets the chance each boat has of failing at a gate or marker * * @param chance percentage chance a boat has of failing per checkpoint. */ protected void setDnfChance(int chance) { if (chance >= 0 && chance <= 100) { dnfChance = chance; } } protected boolean doNotFinish() { Random rand = new Random(); return rand.nextInt(100) < dnfChance; } /** * Calculates the distance a boat has travelled and updates its current position according to this value. * * @param boat to be updated * @param millisecondsElapsed since last update */ protected void updatePosition(BoatInRace boat, int millisecondsElapsed) { //distanceTravelled = velocity (nm p hr) * time taken to update loop double distanceTravelled = (boat.getScaledVelocity() * millisecondsElapsed) / 3600000; double totalDistanceTravelled = distanceTravelled + boat.getDistanceTravelledInLeg(); boolean finish = boat.getCurrentLeg().getName().equals("Finish"); if (!finish) { boat.setHeading(boat.calculateHeading()); //update boat's distance travelled boat.setDistanceTravelledInLeg(totalDistanceTravelled); //Calculate boat's new position by adding the distance travelled onto the start point of the leg boat.setCurrentPosition(calculatePosition(boat.getCurrentLeg().getStartMarker().getAverageGPSCoordinate(), totalDistanceTravelled, boat.calculateAzimuth())); } } protected void checkPosition(BoatInRace boat, long timeElapsed) { if (boat.getDistanceTravelledInLeg() > boat.getCurrentLeg().getDistance()) { //boat has passed onto new leg if (boat.getCurrentLeg().getName().equals("Finish")) { //boat has finished boatsFinished++; boat.setFinished(true); boat.setTimeFinished(timeElapsed); } else if (doNotFinish()) { boatsFinished++; boat.setFinished(true); boat.setCurrentLeg(new Leg("DNF", -1)); boat.setVelocity(0); boat.setScaledVelocity(0); } else { //Calculate how much the boat overshot the marker by boat.setDistanceTravelledInLeg(boat.getDistanceTravelledInLeg() - boat.getCurrentLeg().getDistance()); //Move boat on to next leg Leg nextLeg = legs.get(boat.getCurrentLeg().getLegNumber() + 1); boat.setCurrentLeg(nextLeg); //Add overshoot distance into the distance travelled for the next leg boat.setDistanceTravelledInLeg(boat.getDistanceTravelledInLeg()); } //Update the boat display table in the GUI to reflect the leg change updatePositions(); } } /** * Returns the boats that have started the race. * * @return ObservableList of BoatInRace class that participated in the race. * @see ObservableList * @see BoatInRace */ public ObservableList getStartingBoats() { return startingBoats; } }