diff --git a/assignments/src/MV3500Cohort2021JulySeptember/projects/Fisher/MV3500ProjectFisher.java b/assignments/src/MV3500Cohort2021JulySeptember/projects/Fisher/MV3500ProjectFisher.java index 96dab06203c26c9f4cfdd7473dc9edadd92bcf68..319889ea59c70ca9d2fdb1d1c9c18d9ce9f451c0 100644 --- a/assignments/src/MV3500Cohort2021JulySeptember/projects/Fisher/MV3500ProjectFisher.java +++ b/assignments/src/MV3500Cohort2021JulySeptember/projects/Fisher/MV3500ProjectFisher.java @@ -1,507 +1,507 @@ -/** - * Copyright (c) 2008-2021, MOVES Institute, Naval Postgraduate School (NPS). All rights reserved. - * This work is provided under a BSD open-source license, see project license.html and license.txt - * - * This Program is a modified version of ExampleSimulationProgramFisher in order to see the - * verbose plain text pdu log. I was unable to figure out the issue in my original code, - * so I just copied the example and pasted my additions into this file. - * - * @author adfis - */ -package MV3500Cohort2021JulySeptember.projects.Fisher; - -import edu.nps.moves.dis7.entities.afg.lifeform.land.CivilianAdultMalewCellPhone; -import edu.nps.moves.dis7.entities.usa.lifeform.land.*; -import edu.nps.moves.dis7.entities.usa.platform.land.M1281CloseCombatWeaponsCarrierJLTVCCWC; -import edu.nps.moves.dis7.enumerations.*; // match any -import edu.nps.moves.dis7.pdus.*; // match any of the PDU classes, easier than listing individually -import edu.nps.moves.dis7.utilities.DisThreadedNetworkInterface; -import edu.nps.moves.dis7.utilities.PduFactory; -import edu.nps.moves.dis7.utilities.stream.PduRecorder; -import java.util.ArrayList; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** The purpose of this program is to provide an easily modifiable example simulation program - * that includes DIS-capable entities doing tasks and reporting them to the network. - * Default settings include PDU recording turned on by default. - */ -public class MV3500ProjectFisher -{ - private boolean verboseComments = true; - static final String NETWORK_ADDRESS_DEFAULT = "239.1.2.3"; - static final int NETWORK_PORT_DEFAULT = 3000; - static String networkAddress = NETWORK_ADDRESS_DEFAULT; - static int networkPort = NETWORK_PORT_DEFAULT; - String DEFAULT_OUTPUT_DIRECTORY = "./src./MV3500Cohort2021JulySeptember./projects./Fisher./pdulogs"; - - /** - * This runSimulationLoops() method is for you, a - * programmer-modifiable method for defining and running a new simulation of interest. - * Welcome! Other parts of this program handle bookkeeping and plumbing tasks so that - * you can focus on your model entities and activities. - * Expandable support includes DIS EntityStatePdu, FirePdu and CommentPdu all available for - * modification and sending in a simulation loop. - * Continuous improvement efforts seek to make this program as easy and straightforward - * as possible for DIS simulationists to use and adapt. - * All of the other methods are setup, teardown and configuration that you may find - * interesting, even helpful, but don't really have to worry about. - */ - @SuppressWarnings("SleepWhileInLoop") // yes we do that - public void runSimulationLoops () - { - try - { - /** seconds for real-time execution (not simulation time, which may or may not be the same) */ - final double SIMULATION_LOOP_DURATION_SECONDS = 1.0; - final int SIMULATION_MAX_LOOP_COUNT = 10; // be deliberate out out there! also avoid infinite loops. - int simulationLoopCount = 0; // variable, initialized at 0 - boolean simulationComplete = false; // sentinel variable as termination condition,, are we done yet? - - - - -// This is an example of the not to good way to do things -// entityType_1.setCountry(Country.UNITED_STATES_OF_AMERICA_USA); // 225 = USA -// entityType_1.setEntityKind(EntityKind.PLATFORM); -// entityType_1.setCategory(6); //Small wheeled utility vehicle -// entityType_1.setSubCategory(30); // JLTV -// entityType_1.setSpecific(37); // Up armored with M240 - - - //Entity 1 is a US JLTV traveling down the road with a M240 - EntityID entityID_1 = new EntityID(); - entityID_1.setEntityID(1); // made-up example ID; - EntityStatePdu entityStatePdu_1 = pduFactory.makeEntityStatePdu(); - entityStatePdu_1.setEntityType(new M1281CloseCombatWeaponsCarrierJLTVCCWC()); // create new object vice using the class - Vector3Float pEntityLinearVelocity = new Vector3Float(); - pEntityLinearVelocity.setX(1).setY(0).setZ(0); - entityStatePdu_1.setEntityLinearVelocity(pEntityLinearVelocity); - entityStatePdu_1.setEntityID(entityID_1); - entityStatePdu_1.getEntityLocation().setX(0).setY(0).setZ(0); - entityStatePdu_1.setForceId(ForceID.FRIENDLY); - entityStatePdu_1.setAlternativeEntityType(new _762x51mmM240E4M240BGPMG() ); - -// Again, example of the not so good way to do things -// EntityType entityType_2 = new EntityType(); -// entityType_2.setCountry(Country.AFGHANISTAN_AFG); -// entityType_2.setEntityKind(EntityKind.LIFE_FORM); -// entityType_2.setCategory(1); // civilian male with cellphone -// entityType_2.setSubCategory(171); // personal electronic -// entityType_2.setSubCategory(1); // cell phone - - - // Entity 2 is an enemy Afghan male with cell phone. - EntityID entityID_2 = new EntityID(); - entityID_2.setEntityID(2); - EntityStatePdu entityStatePdu_2 = pduFactory.makeEntityStatePdu(); - entityStatePdu_2.setEntityType(new CivilianAdultMalewCellPhone()); - entityStatePdu_2.setEntityID(entityID_2); - entityStatePdu_2.getEntityLocation().setX(10).setY(0).setZ(100); - entityStatePdu_2.setForceId(ForceID.OPPOSING); - - // 762 munition to be fired from M240 - FirePdu firePdu_1a = pduFactory.makeFirePdu(); - MunitionDescriptor fireDescriptor = new MunitionDescriptor(); - EntityType munitionType = new EntityType(); - munitionType.setCountry(Country.UNITED_STATES_OF_AMERICA_USA); - munitionType.setEntityKind(EntityKind.MUNITION); - munitionType.setCategory(2); // ballistic - munitionType.setSubCategory(2); //762 - munitionType.setSpecific(4); // _762x51mm4balland1tracerlinked - //fireDescriptor.setMunitionType(new _762x51mm4balland1tracerlinked()); - firePdu_1a.setFiringEntityID(entityID_1); - firePdu_1a.setTargetEntityID(entityID_2); - firePdu_1a.setRange(1000.0f); // range 1000m - fireDescriptor.setRate(200); //rate 200 rounds per minute - Vector3Float pVelocity = new Vector3Float(); - pVelocity.setX(0.0f); - pVelocity.setY(0.0f); - pVelocity.setZ(100.0f); - firePdu_1a.setVelocity(pVelocity); - fireDescriptor.setMunitionType(munitionType); - firePdu_1a.setDescriptor(fireDescriptor); - - //Pdu for impacts of 762 on the dirt before making contact with enemy - DetonationPdu fireDetPdu1 = pduFactory.makeDetonationPdu(); - fireDetPdu1.getLocationInWorldCoordinates().setX(12).setY(0).setZ(0); - fireDetPdu1.setDetonationResult(DetonationResult.GROUND_IMPACT); - fireDetPdu1.setSourceEntityID(entityID_1).setTargetEntityID(entityID_2); - - // Pdu for impacts of 762 on the enemy - DetonationPdu fireDetPdu2 = pduFactory.makeDetonationPdu(); - fireDetPdu2.getLocationInWorldCoordinates().setX(12).setY(0).setZ(0); - fireDetPdu2.setDetonationResult(DetonationResult.ENTITY_IMPACT); - fireDetPdu2.setSourceEntityID(entityID_1).setTargetEntityID(entityID_2); - - // IED blast and detonation details - MunitionDescriptor pDescriotor = new MunitionDescriptor(); - pDescriotor.setWarhead(MunitionDescriptorWarhead.HE_FRAGMENTATION); //High explosive frag - EntityType iedMunitionType = new EntityType(); - iedMunitionType.setCountry(Country.OTHER); - iedMunitionType.setEntityKind(EntityKind.MUNITION); - iedMunitionType.setCategory(3); // fixed - iedMunitionType.setSubCategory(3); //PipeBombPVC - //pDescriotor.setMunitionType(new PipeBombPVC()); - pDescriotor.setFuse(MunitionDescriptorFuse.COMMAND_ELECTRONIC_REMOTELY_SET); //command detonated - DetonationPdu detonationPdu = pduFactory.makeDetonationPdu(); - detonationPdu.getLocationInWorldCoordinates().setX(12).setY(0).setZ(0); - pDescriotor.setMunitionType(iedMunitionType); - detonationPdu.setDescriptor(pDescriotor); - detonationPdu.setSourceEntityID(entityID_2).setTargetEntityID(entityID_1); - - // User chooses cases to see effects based on det probability - float probabilityOfDetonation = 0.2f; - // experiment with munition reliability - if (0.0f < probabilityOfDetonation && probabilityOfDetonation <= 0.8f) - { - detonationPdu.setDetonationResult(DetonationResult.ENTITY_PROXIMATE_DETONATION); - } - else if (probabilityOfDetonation > 0.8f) - { - detonationPdu.setDetonationResult(DetonationResult.ENTITY_IMPACT); // worst case IED direct hit - } - else if (probabilityOfDetonation == 0.0f) - { - detonationPdu.setDetonationResult(DetonationResult.NONE_OR_NO_DETONATION_DUD); // best case IED dud - } - - - // loop the simulation while allowed, programmer can set additional conditions to break out and finish - while (simulationLoopCount < SIMULATION_MAX_LOOP_COUNT) // are we done yet? - { - simulationLoopCount++; // good practice: increment loop counter as first action in that loop - - // ============================================================================================= - // * your own simulation code starts here! * - // ============================================================================================= - - // are there any other variables to modify at the beginning of your loop? - - // compute a track, update an ESPDU, whatever it is that your model is doing... - - // Where is my entity? Insert changes in position; this sample only changes X position. - entityStatePdu_1.getEntityLocation().setX(entityStatePdu_1.getEntityLocation().getX() + 1.0); // 1m per timestep - - // decide whether to fire, and then update the firePdu. Hmmm, you might want a target to shoort at! - - // etc. etc. your code goes here for your simulation of interest - - // something happens between my simulation entities, la de da de da... - System.out.println ("Entity 1 is moving a 1m per timestep in the x direction"); - - - // make your reports: narrative code for CommentPdu here (set all to empty strings to avoid sending) - narrativeMessage1 = "Entity 1 (friendly) on the move on route 1"; - //narrativeMessage2 = "runSimulation() loop " + simulationLoopCount; - //narrativeMessage3 = "this is working!"; // intentionally blank for testing - - // your loop termination condition goes here - if (simulationLoopCount > 11) // for example - { - simulationComplete = true; - } - // ============================================================================================= - // * your own simulation code is finished here! * - // ============================================================================================= - - // staying synchronized with timestep: wait duration for elapsed time in this loop - // Thread.sleep needs a (long) parameter for milliseconds, which are clumsy to use sometimes - Thread.sleep((long)(SIMULATION_LOOP_DURATION_SECONDS * 1000)); // seconds * (1000 msec/sec) = milliseconds - System.out.println ("... [Pausing for " + SIMULATION_LOOP_DURATION_SECONDS + " seconds]"); - - // OK now send the status PDUs for this loop, and then continue - System.out.println ("sending PDUs for simulation step " + simulationLoopCount + ", monitor loopback to confirm sent"); - //sendAllPdusForLoopTimestep(entityStatePdu_1, timeStepComment, narrativeMessage1); - sendSinglePdu(entityStatePdu_1); // me too i.e. 2! - System.out.println ("... [PDUs successfully sent for this loop]"); - - int contactCounter = 0; - // When entity reaches a point on the route detonate IED and - // begin firing at the enemy - if (entityStatePdu_1.getEntityLocation().getX() == 10) - { - sendSinglePdu(detonationPdu); - sendCommentPdu(otherComment, "IED detonated near Entity 1"); - - // This would show the 4 bursts to be shot at the enemy. We can adjust - // how quicly we get effects on target. - while (contactCounter < 4) - { - // To be changed by anyone, if we assume our first 2 bursts will not hit the enemy - // Can be changes to reflect better marksmanship or worse. - if (contactCounter <2) - { - contactCounter++; - sendSinglePdu(entityStatePdu_2); - sendSinglePdu(firePdu_1a); - sendSinglePdu(fireDetPdu1); - sendCommentPdu(otherComment, "Missed entity 2!"); - } - else - { - contactCounter++; - sendSinglePdu(entityStatePdu_2); - sendSinglePdu(firePdu_1a); - sendSinglePdu(fireDetPdu2); - sendCommentPdu(otherComment, "Entity 2 is hit!"); - } - } - } - - // =============================== - // loop now finished, check whether to terminate if simulation complete, otherwise continue - if (simulationComplete || (simulationLoopCount > 10000)) // for example; including fail-safe condition is good - { - //sendSinglePdu(detonationPdu); - System.out.println ("... [Termination condition met, simulationComplete=" + simulationComplete + "]"); // ", final loopCount=" + loopCount + - break; - } - } // end of simulation loop - - narrativeMessage2 = "runSimulation() completed successfully"; // all done - sendCommentPdu(otherComment, "Entity has been neutralized. Simulation over."); - //sendCommentPdu(narrativeComment, narrativeMessage1, narrativeMessage2, narrativeMessage3); - System.out.println ("... [final CommentPdu successfully sent for simulation]"); - // TODO simulation management PDUs - } - catch (InterruptedException iex) // handle any exception that your code might choose to provoke! - { - Logger.getLogger(MV3500ProjectFisher.class.getName()).log(Level.SEVERE, null, iex); - } - } - /* **************************** infrastructure code, modification is seldom needed ************************* */ - - String narrativeMessage1 = new String(); - String narrativeMessage2 = new String(); - String narrativeMessage3 = new String(); - - /* VariableRecordType enumerations have potential use with CommentPdu logs */ - /* TODO contrast to EntityType */ - VariableRecordType descriptionComment = VariableRecordType.DESCRIPTION; - VariableRecordType narrativeComment = VariableRecordType.COMPLETE_EVENT_REPORT; - VariableRecordType statusComment = VariableRecordType.APPLICATION_STATUS; - VariableRecordType timeStepComment = VariableRecordType.APPLICATION_TIMESTEP; - VariableRecordType otherComment = VariableRecordType.OTHER; - - /** - * Output prefix to identify this class, helps with logging - */ - private final static String TRACE_PREFIX = "[" + MV3500ProjectFisher.class.getName() + "] "; - - // class variables - PduFactory pduFactory = new PduFactory(); - DisThreadedNetworkInterface disNetworkInterface; - DisThreadedNetworkInterface.PduListener pduListener; - Pdu receivedPdu; - PduRecorder pduRecorder; - - /** - * Constructor design goal: additional built-in initialization conveniences can go here - * to keep student efforts focused on the runSimulation() method. - */ - public MV3500ProjectFisher() - { - // Constructor is under consideration. Constructor is not currently needed. - } - - /** - * Utility Constructor that allows your example simulation program to override default network address and port - * @param address network address to use - * @param port corresponding network port to use - */ - public MV3500ProjectFisher(String address, int port) - { - setNetworkAddress(address); - - setNetworkPort(port); - } - - /** - * @return the networkAddress - */ - public String getNetworkAddress() - { - return networkAddress; - } - - /** - * @param newNetworkAddress the networkAddress to set - */ - public final void setNetworkAddress(String newNetworkAddress) - { - MV3500ProjectFisher.networkAddress = newNetworkAddress; - } - - /** - * @return the networkPort - */ - public int getNetworkPort() - { - return networkPort; - } - - /** - * @param newNetworkPort the networkPort to set - */ - public final void setNetworkPort(int newNetworkPort) - { - MV3500ProjectFisher.networkPort = newNetworkPort; - } - - /** - * Initialize network interface, choosing best available network interface - */ - public void setUpNetworkInterface() - { - disNetworkInterface = new DisThreadedNetworkInterface(getNetworkAddress(), getNetworkPort()); - disNetworkInterface.setDescriptor ("MV3500ProjectFisher pdu looping"); - - System.out.println("Network confirmation:" + - " address=" + disNetworkInterface.getAddress()+ // disNetworkInterface.getMulticastGroup() + - " port=" + disNetworkInterface.getPort()); // + disNetworkInterface.getDisPort()); - pduListener = (Pdu newPdu) -> { - receivedPdu = newPdu; - } /** Callback handler for listener */ ; - disNetworkInterface.addListener(pduListener); - - String outputDirectory = DEFAULT_OUTPUT_DIRECTORY; - System.out.println("Beginning pdu save to directory " + outputDirectory); - pduRecorder = new PduRecorder(outputDirectory, getNetworkAddress(), getNetworkPort()); // assumes save - pduRecorder.setDescriptor ("MV3500ProjectFisher pduRecorder"); - pduRecorder.start(); // begin running - } - - /** All done, release network resources */ - public void tearDownNetworkInterface() - { - pduRecorder.stop(); - - disNetworkInterface.removeListener(pduListener); - - disNetworkInterface.close(); -// disNetworkInterface.kill(); // renamed as close(), deprecated -// disNetworkInterface = null; // making sure no possibility of zombie process remaining... - } - - /** - * Send a single Protocol Data Unit (PDU) of any type - * @param pdu the pdu to send - */ - private void sendSinglePdu(Pdu pdu) - { - try - { - disNetworkInterface.send(pdu); - Thread.sleep(100); // TODO consider refactoring the wait logic and moving externally - } - catch (InterruptedException ex) - { - System.err.println(this.getClass().getName() + " Error sending PDU: " + ex.getLocalizedMessage()); - System.exit(1); - } - } - - /** - * Send Comment PDU - * @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html">Passing Information to a Method or a Constructor</a> Arbitrary Number of Arguments - * @param commentType enumeration value describing purpose of the narrative comment - * @param comments String array of narrative comments - */ - public void sendCommentPdu(VariableRecordType commentType, - // vararg... variable-length set of String comments can optionally follow - String... comments) - { - sendAllPdusForLoopTimestep (null, commentType, comments); - } - - /** - * Send EntityState, Fire, Comment PDUs that got updated for this loop, reflecting state of current simulation timestep. - * @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html">Passing Information to a Method or a Constructor</a> Arbitrary Number of Arguments - * @param entityStatePdu the ESPDU to send, if any - * @param commentType enumeration value describing purpose of the narrative comment - * @param comments String array of narrative comments - */ - public void sendAllPdusForLoopTimestep(EntityStatePdu entityStatePdu, VariableRecordType commentType, - // vararg... variable-length set of String comments can optionally follow - String... comments) - { - if (entityStatePdu != null) - sendSinglePdu(entityStatePdu); - - //if (firePdu != null) - // sendSinglePdu(firePdu); // bang - - if ((comments != null) && (comments.length > 0)) - { - ArrayList<String> newCommentsList = new ArrayList<>(); - for (String comment : comments) - { - if (!comment.isEmpty()) - { - newCommentsList.add(comment); // OK found something to send - } - } - if (!newCommentsList.isEmpty()) - { - if (commentType == null) - commentType = otherComment; // fallback value otherComment - // now build the commentPdu from these string inputs, thus constructing a narrative entry - CommentPdu commentPdu = pduFactory.makeCommentPdu(commentType, newCommentsList.toArray(new String[0])); // comments); - sendSinglePdu(commentPdu); - if (isVerboseComments()) - System.out.println("*** [Narrative comment sent: " + commentType.name() + "] " + newCommentsList.toString()); - } - } - } - - /** - * Main method is first executed when a program instance is loaded. - * @see <a href="https://docs.oracle.com/javase/tutorial/getStarted/application/index.html">Java Tutorials: A Closer Look at the "Hello World!" Application</a> - * @param args command-line arguments are an array of optional String parameters that are passed from execution environment during invocation - */ - public static void main(String[] args) - { - System.out.println(TRACE_PREFIX + "started..."); - - MV3500ProjectFisher thisProgram = new MV3500ProjectFisher(); // creates instance - - // initial execution: can handle args array of initialization arguments here - if (args.length == 2) - { - if ((args[0] != null) && !args[0].isEmpty()) - thisProgram.setNetworkAddress(args[0]); - - if ((args[1] != null) && !args[1].isEmpty()) - thisProgram.setNetworkPort(Integer.parseInt(args[1])); - } - else if (args.length != 0) - { - System.err.println("Usage: " + thisProgram.getClass().getName() + " [address port]"); - System.exit(-1); - } - // OK here we go... - - thisProgram.setUpNetworkInterface(); - - thisProgram.runSimulationLoops (); // ... your simulation execution code goes in there ... - - thisProgram.tearDownNetworkInterface(); // make sure no processes are left lingering - - System.out.println(TRACE_PREFIX + "complete."); // report successful completion - } - - /** - * @return whether verboseComments mode is enabled - */ - public boolean isVerboseComments() { - return verboseComments; - } - - /** - * @param newVerboseComments whether verboseComments mode is enabled - */ - public void setVerboseComments(boolean newVerboseComments) { - this.verboseComments = newVerboseComments; - } -} +/** + * Copyright (c) 2008-2021, MOVES Institute, Naval Postgraduate School (NPS). All rights reserved. + * This work is provided under a BSD open-source license, see project license.html and license.txt + * + * This Program is a modified version of ExampleSimulationProgramFisher in order to see the + * verbose plain text pdu log. I was unable to figure out the issue in my original code, + * so I just copied the example and pasted my additions into this file. + * + * @author adfis + */ +package MV3500Cohort2021JulySeptember.projects.Fisher; + +import edu.nps.moves.dis7.entities.afg.lifeform.land.CivilianAdultMalewCellPhone; +import edu.nps.moves.dis7.entities.usa.lifeform.land.*; +import edu.nps.moves.dis7.entities.usa.platform.land.M1281CloseCombatWeaponsCarrierJLTVCCWC; +import edu.nps.moves.dis7.enumerations.*; // match any +import edu.nps.moves.dis7.pdus.*; // match any of the PDU classes, easier than listing individually +import edu.nps.moves.dis7.utilities.DisThreadedNetworkInterface; +import edu.nps.moves.dis7.utilities.PduFactory; +import edu.nps.moves.dis7.utilities.stream.PduRecorder; +import java.util.ArrayList; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** The purpose of this program is to provide an easily modifiable example simulation program + * that includes DIS-capable entities doing tasks and reporting them to the network. + * Default settings include PDU recording turned on by default. + */ +public class MV3500ProjectFisher +{ + private boolean verboseComments = true; + static final String NETWORK_ADDRESS_DEFAULT = "239.1.2.3"; + static final int NETWORK_PORT_DEFAULT = 3000; + static String networkAddress = NETWORK_ADDRESS_DEFAULT; + static int networkPort = NETWORK_PORT_DEFAULT; + String DEFAULT_OUTPUT_DIRECTORY = "./src./MV3500Cohort2021JulySeptember./projects./Fisher./pdulogs"; + + /** + * This runSimulationLoops() method is for you, a + * programmer-modifiable method for defining and running a new simulation of interest. + * Welcome! Other parts of this program handle bookkeeping and plumbing tasks so that + * you can focus on your model entities and activities. + * Expandable support includes DIS EntityStatePdu, FirePdu and CommentPdu all available for + * modification and sending in a simulation loop. + * Continuous improvement efforts seek to make this program as easy and straightforward + * as possible for DIS simulationists to use and adapt. + * All of the other methods are setup, teardown and configuration that you may find + * interesting, even helpful, but don't really have to worry about. + */ + @SuppressWarnings("SleepWhileInLoop") // yes we do that + public void runSimulationLoops () + { + try + { + /** seconds for real-time execution (not simulation time, which may or may not be the same) */ + final double SIMULATION_LOOP_DURATION_SECONDS = 1.0; + final int SIMULATION_MAX_LOOP_COUNT = 10; // be deliberate out out there! also avoid infinite loops. + int simulationLoopCount = 0; // variable, initialized at 0 + boolean simulationComplete = false; // sentinel variable as termination condition,, are we done yet? + + + + +// This is an example of the not to good way to do things +// entityType_1.setCountry(Country.UNITED_STATES_OF_AMERICA_USA); // 225 = USA +// entityType_1.setEntityKind(EntityKind.PLATFORM); +// entityType_1.setCategory(6); //Small wheeled utility vehicle +// entityType_1.setSubCategory(30); // JLTV +// entityType_1.setSpecific(37); // Up armored with M240 + + + //Entity 1 is a US JLTV traveling down the road with a M240 + EntityID entityID_1 = new EntityID(); + entityID_1.setEntityID(1); // made-up example ID; + EntityStatePdu entityStatePdu_1 = pduFactory.makeEntityStatePdu(); + entityStatePdu_1.setEntityType(new M1281CloseCombatWeaponsCarrierJLTVCCWC()); // create new object vice using the class + Vector3Float pEntityLinearVelocity = new Vector3Float(); + pEntityLinearVelocity.setX(1).setY(0).setZ(0); + entityStatePdu_1.setEntityLinearVelocity(pEntityLinearVelocity); + entityStatePdu_1.setEntityID(entityID_1); + entityStatePdu_1.getEntityLocation().setX(0).setY(0).setZ(0); + entityStatePdu_1.setForceId(ForceID.FRIENDLY); + entityStatePdu_1.setAlternativeEntityType(new _762x51mmM240E4M240BGPMG() ); + +// Again, example of the not so good way to do things +// EntityType entityType_2 = new EntityType(); +// entityType_2.setCountry(Country.AFGHANISTAN_AFG); +// entityType_2.setEntityKind(EntityKind.LIFE_FORM); +// entityType_2.setCategory(1); // civilian male with cellphone +// entityType_2.setSubCategory(171); // personal electronic +// entityType_2.setSubCategory(1); // cell phone + + + // Entity 2 is an enemy Afghan male with cell phone. + EntityID entityID_2 = new EntityID(); + entityID_2.setEntityID(2); + EntityStatePdu entityStatePdu_2 = pduFactory.makeEntityStatePdu(); + entityStatePdu_2.setEntityType(new CivilianAdultMalewCellPhone()); + entityStatePdu_2.setEntityID(entityID_2); + entityStatePdu_2.getEntityLocation().setX(10).setY(0).setZ(100); + entityStatePdu_2.setForceId(ForceID.OPPOSING); + + // 762 munition to be fired from M240 + FirePdu firePdu_1a = pduFactory.makeFirePdu(); + MunitionDescriptor fireDescriptor = new MunitionDescriptor(); + EntityType munitionType = new EntityType(); + munitionType.setCountry(Country.UNITED_STATES_OF_AMERICA_USA); + munitionType.setEntityKind(EntityKind.MUNITION); + munitionType.setCategory(2); // ballistic + munitionType.setSubCategory(2); //762 + munitionType.setSpecific(4); // _762x51mm4balland1tracerlinked + //fireDescriptor.setMunitionType(new _762x51mm4balland1tracerlinked()); + firePdu_1a.setFiringEntityID(entityID_1); + firePdu_1a.setTargetEntityID(entityID_2); + firePdu_1a.setRange(1000.0f); // range 1000m + fireDescriptor.setRate(200); //rate 200 rounds per minute + Vector3Float pVelocity = new Vector3Float(); + pVelocity.setX(0.0f); + pVelocity.setY(0.0f); + pVelocity.setZ(100.0f); + firePdu_1a.setVelocity(pVelocity); + fireDescriptor.setMunitionType(munitionType); + firePdu_1a.setDescriptor(fireDescriptor); + + //Pdu for impacts of 762 on the dirt before making contact with enemy + DetonationPdu fireDetPdu1 = pduFactory.makeDetonationPdu(); + fireDetPdu1.getLocationInWorldCoordinates().setX(12).setY(0).setZ(0); + fireDetPdu1.setDetonationResult(DetonationResult.GROUND_IMPACT); + fireDetPdu1.setSourceEntityID(entityID_1).setTargetEntityID(entityID_2); + + // Pdu for impacts of 762 on the enemy + DetonationPdu fireDetPdu2 = pduFactory.makeDetonationPdu(); + fireDetPdu2.getLocationInWorldCoordinates().setX(12).setY(0).setZ(0); + fireDetPdu2.setDetonationResult(DetonationResult.ENTITY_IMPACT); + fireDetPdu2.setSourceEntityID(entityID_1).setTargetEntityID(entityID_2); + + // IED blast and detonation details + MunitionDescriptor pDescriotor = new MunitionDescriptor(); + pDescriotor.setWarhead(MunitionDescriptorWarhead.HE_FRAGMENTATION); //High explosive frag + EntityType iedMunitionType = new EntityType(); + iedMunitionType.setCountry(Country.OTHER); + iedMunitionType.setEntityKind(EntityKind.MUNITION); + iedMunitionType.setCategory(3); // fixed + iedMunitionType.setSubCategory(3); //PipeBombPVC + //pDescriotor.setMunitionType(new PipeBombPVC()); + pDescriotor.setFuse(MunitionDescriptorFuse.COMMAND_ELECTRONIC_REMOTELY_SET); //command detonated + DetonationPdu detonationPdu = pduFactory.makeDetonationPdu(); + detonationPdu.getLocationInWorldCoordinates().setX(12).setY(0).setZ(0); + pDescriotor.setMunitionType(iedMunitionType); + detonationPdu.setDescriptor(pDescriotor); + detonationPdu.setSourceEntityID(entityID_2).setTargetEntityID(entityID_1); + + // User chooses cases to see effects based on det probability + float probabilityOfDetonation = 0.2f; + // experiment with munition reliability + if (0.0f < probabilityOfDetonation && probabilityOfDetonation <= 0.8f) + { + detonationPdu.setDetonationResult(DetonationResult.ENTITY_PROXIMATE_DETONATION); + } + else if (probabilityOfDetonation > 0.8f) + { + detonationPdu.setDetonationResult(DetonationResult.ENTITY_IMPACT); // worst case IED direct hit + } + else if (probabilityOfDetonation == 0.0f) + { + detonationPdu.setDetonationResult(DetonationResult.NONE_OR_NO_DETONATION_DUD); // best case IED dud + } + + + // loop the simulation while allowed, programmer can set additional conditions to break out and finish + while (simulationLoopCount < SIMULATION_MAX_LOOP_COUNT) // are we done yet? + { + simulationLoopCount++; // good practice: increment loop counter as first action in that loop + + // ============================================================================================= + // * your own simulation code starts here! * + // ============================================================================================= + + // are there any other variables to modify at the beginning of your loop? + + // compute a track, update an ESPDU, whatever it is that your model is doing... + + // Where is my entity? Insert changes in position; this sample only changes X position. + entityStatePdu_1.getEntityLocation().setX(entityStatePdu_1.getEntityLocation().getX() + 1.0); // 1m per timestep + + // decide whether to fire, and then update the firePdu. Hmmm, you might want a target to shoort at! + + // etc. etc. your code goes here for your simulation of interest + + // something happens between my simulation entities, la de da de da... + System.out.println ("Entity 1 is moving a 1m per timestep in the x direction"); + + + // make your reports: narrative code for CommentPdu here (set all to empty strings to avoid sending) + narrativeMessage1 = "Entity 1 (friendly) on the move on route 1"; + //narrativeMessage2 = "runSimulation() loop " + simulationLoopCount; + //narrativeMessage3 = "this is working!"; // intentionally blank for testing + + // your loop termination condition goes here + if (simulationLoopCount > 11) // for example + { + simulationComplete = true; + } + // ============================================================================================= + // * your own simulation code is finished here! * + // ============================================================================================= + + // staying synchronized with timestep: wait duration for elapsed time in this loop + // Thread.sleep needs a (long) parameter for milliseconds, which are clumsy to use sometimes + Thread.sleep((long)(SIMULATION_LOOP_DURATION_SECONDS * 1000)); // seconds * (1000 msec/sec) = milliseconds + System.out.println ("... [Pausing for " + SIMULATION_LOOP_DURATION_SECONDS + " seconds]"); + + // OK now send the status PDUs for this loop, and then continue + System.out.println ("sending PDUs for simulation step " + simulationLoopCount + ", monitor loopback to confirm sent"); + //sendAllPdusForLoopTimestep(entityStatePdu_1, timeStepComment, narrativeMessage1); + sendSinglePdu(entityStatePdu_1); // me too i.e. 2! + System.out.println ("... [PDUs successfully sent for this loop]"); + + int contactCounter = 0; + // When entity reaches a point on the route detonate IED and + // begin firing at the enemy + if (entityStatePdu_1.getEntityLocation().getX() == 10) + { + sendSinglePdu(detonationPdu); + sendCommentPdu(otherComment, "IED detonated near Entity 1"); + + // This would show the 4 bursts to be shot at the enemy. We can adjust + // how quicly we get effects on target. + while (contactCounter < 4) + { + // To be changed by anyone, if we assume our first 2 bursts will not hit the enemy + // Can be changes to reflect better marksmanship or worse. + if (contactCounter <2) + { + contactCounter++; + sendSinglePdu(entityStatePdu_2); + sendSinglePdu(firePdu_1a); + sendSinglePdu(fireDetPdu1); + sendCommentPdu(otherComment, "Missed entity 2!"); + } + else + { + contactCounter++; + sendSinglePdu(entityStatePdu_2); + sendSinglePdu(firePdu_1a); + sendSinglePdu(fireDetPdu2); + sendCommentPdu(otherComment, "Entity 2 is hit!"); + } + } + } + + // =============================== + // loop now finished, check whether to terminate if simulation complete, otherwise continue + if (simulationComplete || (simulationLoopCount > 10000)) // for example; including fail-safe condition is good + { + //sendSinglePdu(detonationPdu); + System.out.println ("... [Termination condition met, simulationComplete=" + simulationComplete + "]"); // ", final loopCount=" + loopCount + + break; + } + } // end of simulation loop + + narrativeMessage2 = "runSimulation() completed successfully"; // all done + sendCommentPdu(otherComment, "Entity has been neutralized. Simulation over."); + //sendCommentPdu(narrativeComment, narrativeMessage1, narrativeMessage2, narrativeMessage3); + System.out.println ("... [final CommentPdu successfully sent for simulation]"); + // TODO simulation management PDUs + } + catch (InterruptedException iex) // handle any exception that your code might choose to provoke! + { + Logger.getLogger(MV3500ProjectFisher.class.getName()).log(Level.SEVERE, null, iex); + } + } + /* **************************** infrastructure code, modification is seldom needed ************************* */ + + String narrativeMessage1 = new String(); + String narrativeMessage2 = new String(); + String narrativeMessage3 = new String(); + + /* VariableRecordType enumerations have potential use with CommentPdu logs */ + /* TODO contrast to EntityType */ + VariableRecordType descriptionComment = VariableRecordType.DESCRIPTION; + VariableRecordType narrativeComment = VariableRecordType.COMPLETE_EVENT_REPORT; + VariableRecordType statusComment = VariableRecordType.APPLICATION_STATUS; + VariableRecordType timeStepComment = VariableRecordType.APPLICATION_TIMESTEP; + VariableRecordType otherComment = VariableRecordType.OTHER; + + /** + * Output prefix to identify this class, helps with logging + */ + private final static String TRACE_PREFIX = "[" + MV3500ProjectFisher.class.getName() + "] "; + + // class variables + PduFactory pduFactory = new PduFactory(); + DisThreadedNetworkInterface disNetworkInterface; + DisThreadedNetworkInterface.PduListener pduListener; + Pdu receivedPdu; + PduRecorder pduRecorder; + + /** + * Constructor design goal: additional built-in initialization conveniences can go here + * to keep student efforts focused on the runSimulation() method. + */ + public MV3500ProjectFisher() + { + // Constructor is under consideration. Constructor is not currently needed. + } + + /** + * Utility Constructor that allows your example simulation program to override default network address and port + * @param address network address to use + * @param port corresponding network port to use + */ + public MV3500ProjectFisher(String address, int port) + { + setNetworkAddress(address); + + setNetworkPort(port); + } + + /** + * @return the networkAddress + */ + public String getNetworkAddress() + { + return networkAddress; + } + + /** + * @param newNetworkAddress the networkAddress to set + */ + public final void setNetworkAddress(String newNetworkAddress) + { + MV3500ProjectFisher.networkAddress = newNetworkAddress; + } + + /** + * @return the networkPort + */ + public int getNetworkPort() + { + return networkPort; + } + + /** + * @param newNetworkPort the networkPort to set + */ + public final void setNetworkPort(int newNetworkPort) + { + MV3500ProjectFisher.networkPort = newNetworkPort; + } + + /** + * Initialize network interface, choosing best available network interface + */ + public void setUpNetworkInterface() + { + disNetworkInterface = new DisThreadedNetworkInterface(getNetworkAddress(), getNetworkPort()); + disNetworkInterface.setDescriptor ("MV3500ProjectFisher pdu looping"); + + System.out.println("Network confirmation:" + + " address=" + disNetworkInterface.getAddress() + // disNetworkInterface.getMulticastGroup() + + " port=" + disNetworkInterface.getPort()); // + disNetworkInterface.getDisPort()); + pduListener = (Pdu newPdu) -> { + receivedPdu = newPdu; + } /** Callback handler for listener */ ; + disNetworkInterface.addListener(pduListener); + + String outputDirectory = DEFAULT_OUTPUT_DIRECTORY; + System.out.println("Beginning pdu save to directory " + outputDirectory); + pduRecorder = new PduRecorder(outputDirectory, getNetworkAddress(), getNetworkPort()); // assumes save + pduRecorder.setDescriptor ("MV3500ProjectFisher pduRecorder"); + pduRecorder.start(); // begin running + } + + /** All done, release network resources */ + public void tearDownNetworkInterface() + { + pduRecorder.stop(); + + disNetworkInterface.removeListener(pduListener); + + disNetworkInterface.close(); +// disNetworkInterface.kill(); // renamed as close(), deprecated +// disNetworkInterface = null; // making sure no possibility of zombie process remaining... + } + + /** + * Send a single Protocol Data Unit (PDU) of any type + * @param pdu the pdu to send + */ + private void sendSinglePdu(Pdu pdu) + { + try + { + disNetworkInterface.send(pdu); + Thread.sleep(100); // TODO consider refactoring the wait logic and moving externally + } + catch (InterruptedException ex) + { + System.err.println(this.getClass().getName() + " Error sending PDU: " + ex.getLocalizedMessage()); + System.exit(1); + } + } + + /** + * Send Comment PDU + * @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html">Passing Information to a Method or a Constructor</a> Arbitrary Number of Arguments + * @param commentType enumeration value describing purpose of the narrative comment + * @param comments String array of narrative comments + */ + public void sendCommentPdu(VariableRecordType commentType, + // vararg... variable-length set of String comments can optionally follow + String... comments) + { + sendAllPdusForLoopTimestep (null, commentType, comments); + } + + /** + * Send EntityState, Fire, Comment PDUs that got updated for this loop, reflecting state of current simulation timestep. + * @see <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html">Passing Information to a Method or a Constructor</a> Arbitrary Number of Arguments + * @param entityStatePdu the ESPDU to send, if any + * @param commentType enumeration value describing purpose of the narrative comment + * @param comments String array of narrative comments + */ + public void sendAllPdusForLoopTimestep(EntityStatePdu entityStatePdu, VariableRecordType commentType, + // vararg... variable-length set of String comments can optionally follow + String... comments) + { + if (entityStatePdu != null) + sendSinglePdu(entityStatePdu); + + //if (firePdu != null) + // sendSinglePdu(firePdu); // bang + + if ((comments != null) && (comments.length > 0)) + { + ArrayList<String> newCommentsList = new ArrayList<>(); + for (String comment : comments) + { + if (!comment.isEmpty()) + { + newCommentsList.add(comment); // OK found something to send + } + } + if (!newCommentsList.isEmpty()) + { + if (commentType == null) + commentType = otherComment; // fallback value otherComment + // now build the commentPdu from these string inputs, thus constructing a narrative entry + CommentPdu commentPdu = pduFactory.makeCommentPdu(commentType, newCommentsList.toArray(new String[0])); // comments); + sendSinglePdu(commentPdu); + if (isVerboseComments()) + System.out.println("*** [Narrative comment sent: " + commentType.name() + "] " + newCommentsList.toString()); + } + } + } + + /** + * Main method is first executed when a program instance is loaded. + * @see <a href="https://docs.oracle.com/javase/tutorial/getStarted/application/index.html">Java Tutorials: A Closer Look at the "Hello World!" Application</a> + * @param args command-line arguments are an array of optional String parameters that are passed from execution environment during invocation + */ + public static void main(String[] args) + { + System.out.println(TRACE_PREFIX + "started..."); + + MV3500ProjectFisher thisProgram = new MV3500ProjectFisher(); // creates instance + + // initial execution: can handle args array of initialization arguments here + if (args.length == 2) + { + if ((args[0] != null) && !args[0].isEmpty()) + thisProgram.setNetworkAddress(args[0]); + + if ((args[1] != null) && !args[1].isEmpty()) + thisProgram.setNetworkPort(Integer.parseInt(args[1])); + } + else if (args.length != 0) + { + System.err.println("Usage: " + thisProgram.getClass().getName() + " [address port]"); + System.exit(-1); + } + // OK here we go... + + thisProgram.setUpNetworkInterface(); + + thisProgram.runSimulationLoops (); // ... your simulation execution code goes in there ... + + thisProgram.tearDownNetworkInterface(); // make sure no processes are left lingering + + System.out.println(TRACE_PREFIX + "complete."); // report successful completion + } + + /** + * @return whether verboseComments mode is enabled + */ + public boolean isVerboseComments() { + return verboseComments; + } + + /** + * @param newVerboseComments whether verboseComments mode is enabled + */ + public void setVerboseComments(boolean newVerboseComments) { + this.verboseComments = newVerboseComments; + } +}