public void TextChatRequest(string user_id, string message, string type, string target) { _ChatRequest = SimulationEventFactory.BuildEvent(ref _SimModel, "TextChatRequest"); ((StringValue)(_ChatRequest["UserID"])).value = user_id; ((StringValue)(_ChatRequest["ChatBody"])).value = message; // ALL for a global message, TEAM for a team message, P2P for a private message. ((StringValue)(_ChatRequest["ChatType"])).value = type; // Only need to be set if ChatType == P2P, this is the unique ID of the decision maker receiving the message. ((StringValue)(_ChatRequest["TargetUserID"])).value = target; if (DDD_Global.Instance.IsConnected) { DDD_Global.Instance.PutEvent(_ChatRequest); } }
private void btnChangeTag_Click(object sender, EventArgs e) { string chosenText = ""; string chosenAsset = ""; string chosenDM = ""; if (null != lbxDecisionMakers.SelectedItem) { chosenDM = lbxDecisionMakers.SelectedItem.ToString(); } if (null != lbxAssets.SelectedItem) { chosenAsset = lbxAssets.SelectedItem.ToString(); } if (null != txArg1.Text) { chosenText = txArg1.Text; } if ("" == chosenDM) { MessageBox.Show("Please select a Decision Maker"); return; } if ("" == chosenAsset) { MessageBox.Show("Please select an asset"); return; } if ("" == chosenText) { DialogResult dr = MessageBox.Show("Do you wish to remove the current tag from " + chosenAsset + "?", "", MessageBoxButtons.YesNo); if (DialogResult.No == dr) { return; } } SimulationEvent chTag = SimulationEventFactory.BuildEvent(ref simModelInfo, "ChangeTagRequest"); chTag["UnitID"] = DataValueFactory.BuildString(chosenAsset); chTag["DecisionMakerID"] = DataValueFactory.BuildString(chosenDM); chTag["Tag"] = DataValueFactory.BuildString(chosenText); EventListener.Network.PutEvent(chTag); }
/// <summary> /// /// </summary> /// <param name="playerID"></param> /// <param name="message"></param> private void SendSystemMessageToAll(string message) { //might be nice to send out a confirmation of player X's joining to the server //and selection of a DM. The msg would be a text chat? SimulationEvent e; foreach (string playerID in allDMs.Keys) { if (allDMs[playerID].availability != DecisionMaker.Availability.AVAILABLE) { e = SimulationEventFactory.BuildEvent(ref simModelInfo, "SystemMessage"); e["Message"] = DataValueFactory.BuildString(message); e["TextColor"] = DataValueFactory.BuildInteger(System.Drawing.Color.Black.ToArgb()); e["PlayerID"] = DataValueFactory.BuildString(playerID); server.PutEvent(e); } } }
public void WhiteboardLineRequest(string user_id, int mode, LocationValue start, LocationValue end, double width, double originalScale, int color, string text, string target) { _WBRequest = SimulationEventFactory.BuildEvent(ref _SimModel, "WhiteboardLineRequest"); ((StringValue)(_WBRequest["UserID"])).value = user_id; ((IntegerValue)(_WBRequest["Mode"])).value = mode; _WBRequest["StartLocation"] = start; _WBRequest["EndLocation"] = end; ((DoubleValue)(_WBRequest["Width"])).value = width; ((DoubleValue)(_WBRequest["OriginalScale"])).value = originalScale; ((IntegerValue)(_WBRequest["Color"])).value = color; ((StringValue)(_WBRequest["Text"])).value = text; ((StringValue)(_WBRequest["TargetUserID"])).value = target; if (DDD_Global.Instance.IsConnected) { DDD_Global.Instance.PutEvent(_WBRequest); } }
private void btnCloseChat_Click(object sender, EventArgs e) { if (null == lbxDecisionMakers.SelectedItem) { MessageBox.Show("Please select an owner for the chat room."); return; } if (null == lbxCloseChatNames.SelectedItem) { MessageBox.Show("Please select the name of the room to close."); return; } SimulationEvent closeChat = SimulationEventFactory.BuildEvent(ref simModelInfo, "RequestCloseChatRoom"); closeChat["RoomName"] = DataValueFactory.BuildString((string)lbxCloseChatNames.SelectedItem); closeChat["SenderDM_ID"] = DataValueFactory.BuildString((string)lbxDecisionMakers.SelectedItem); EventListener.Network.PutEvent(closeChat); }
/// <summary> /// This event receives an attack object, sends out the attack, and returns false if the current time /// is the same as the attack end time. This info is used to remove the attack from the attack list if the /// time is up. /// </summary> /// <param name="attack"></param> /// <returns></returns> private bool SendAttackEvent(Attack attack) { bool returnBool = true; int endTime = attack.endTime; if (endTime <= currentTick) { //attack is over returnBool = false; } SimulationEvent e = SimulationEventFactory.BuildEvent(ref simModel, "ViewProAttackUpdate"); e["AttackerID"] = DataValueFactory.BuildString(attack.attacker); e["TargetID"] = DataValueFactory.BuildString(attack.target); e["AttackEndTime"] = DataValueFactory.BuildInteger(attack.endTime); e["Time"] = DataValueFactory.BuildInteger(currentTick); distClient.PutEvent(e); return(returnBool); }
private void btnTransfer_Click(object sender, EventArgs e) { string chosenAsset = ""; string chosenDM = ""; string receivingDM = ""; if (null != lbxDecisionMakers.SelectedItem) { chosenDM = lbxDecisionMakers.SelectedItem.ToString(); } if (null != lbxAssets.SelectedItem) { chosenAsset = lbxAssets.SelectedItem.ToString(); } if (null != lbxTransferReceiver.SelectedItem) { receivingDM = lbxTransferReceiver.SelectedItem.ToString(); } if ("" == chosenDM) { MessageBox.Show("Please select a Decision Maker to cause the transfer"); return; } if ("" == chosenAsset) { MessageBox.Show("Please select an asset"); return; } if ("" == receivingDM) { MessageBox.Show("Please select a Decision MAker to receive the asset"); return; } SimulationEvent xfer = SimulationEventFactory.BuildEvent(ref simModelInfo, "TransferObjectRequest"); xfer["ObjectID"] = DataValueFactory.BuildString(chosenAsset); xfer["UserID"] = DataValueFactory.BuildString(chosenDM); xfer["RecipientID"] = DataValueFactory.BuildString(receivingDM); EventListener.Network.PutEvent(xfer); }
// So here's the deal. I created a generic attack request event for you called "ClientAttackRequest". It has the following attributes in it: //* PlayerID - StringValue - Your user's PlayerID //* AttackingObjectID - StringValue - The ID of the attacking object //* TargetObjectID - StringValue - The ID of the target object //* WeaponOrCapabilityName - StringValue - The capability name or the weapon ID of the weapon or capability being used. public void DoAttack(string user_id, string object_id, string target_id, string capability) { _AttackEvent = SimulationEventFactory.BuildEvent(ref _SimModel, "ClientAttackRequest"); ((StringValue)(_AttackEvent["PlayerID"])).value = user_id; ((StringValue)(_AttackEvent["AttackingObjectID"])).value = object_id; ((StringValue)(_AttackEvent["TargetObjectID"])).value = target_id; ((StringValue)(_AttackEvent["WeaponOrCapabilityName"])).value = capability; if (DDD_Global.Instance.IsConnected) { DDD_Global.Instance.PutEvent(_AttackEvent); } else { lock (this) { if (DemoEvents != null) { DemoEvents.Add(_AttackEvent); } } } }
/// <summary> /// This event is broadcast out to each client. That client will attempt to put the object in motion, but will only /// succeed if the object already exists in its playfield. /// </summary> /// <param name="objectID"></param> /// <param name="ownerID"></param> /// <param name="location"></param> /// <param name="desLocation"></param> /// <param name="maxSpeed"></param> /// <param name="throttle"></param> /// <param name="time"></param> /// <param name="iconName"></param> /// <param name="isWeapon"></param> private void SendViewProMotionUpdate(string objectID, string ownerID, LocationValue location, LocationValue desLocation, double maxSpeed, double throttle, string iconName, bool isWeapon, double activeRegionSpeedMultiplier) { SimulationEvent vpmu = null; vpmu = SimulationEventFactory.BuildEvent(ref simModel, "ViewProMotionUpdate"); vpmu["ObjectID"] = DataValueFactory.BuildString(objectID); vpmu["OwnerID"] = DataValueFactory.BuildString(ownerID); vpmu["Location"] = location; vpmu["DestinationLocation"] = desLocation; //Console.WriteLine(String.Format("VPMU: ID:{0} dX:{1} dY:{2}", objectID, desLocation.X, desLocation.Y)); //if (objectID == "Fighter01_Troop_2") //{ // Console.Out.Write(String.Format("\n{0} is moving at {1}*{2}\n", objectID, maxSpeed, activeRegionSpeedMultiplier)); //} vpmu["MaximumSpeed"] = DataValueFactory.BuildDouble(maxSpeed * activeRegionSpeedMultiplier); vpmu["Throttle"] = DataValueFactory.BuildDouble(throttle); vpmu["Time"] = DataValueFactory.BuildInteger(currentTick); vpmu["IconName"] = DataValueFactory.BuildString(iconName); //add label color to the mix try { vpmu["LabelColor"] = DataValueFactory.BuildInteger(dmColorMapping[ownerID]); } catch (Exception ex) { vpmu["LabelColor"] = DataValueFactory.BuildInteger(-984833); } vpmu["IsWeapon"] = DataValueFactory.BuildBoolean(isWeapon); distClient.PutEvent(vpmu); if (!movingObjects.Contains(objectID) && !DataValueFactory.CompareDataValues(location, desLocation)) { movingObjects.Add(objectID); } }
private void ClockStart() { switch (clockState) { case ClockState.STOPPED: clockState = ClockState.RUNNING; startButton.Text = "Pause"; clockTimer.Interval = updateFrequency; clockTimer.Start(); SimulationEvent tick = SimulationEventFactory.BuildEvent(ref simModel, "TimeTick"); ((IntegerValue)tick["Time"]).value = simulationTime; netClient.PutEvent(tick); manualCheckBox.Enabled = false; break; case ClockState.RUNNING: clockState = ClockState.STOPPED; startButton.Text = "Start"; clockTimer.Stop(); break; } }
public void DisconnectTerminal(SimulationEvent e) { string termID = ((StringValue)e["TerminalID"]).value; string dmID = ""; if (termToDMMap.ContainsKey(termID)) { dmID = termToDMMap[termID]; //.ToUpper()]; } if (dmToTerminalMap.ContainsKey(dmID)) { termID = dmToTerminalMap[dmID]; dmToTerminalMap.Remove(dmID); termToDMMap.Remove(termID); } if (dmsIsReady.ContainsKey(dmID)) { dmsIsReady.Remove(dmID); } if (allDMs.ContainsKey(dmID)) { allDMs[dmID].availability = DecisionMaker.Availability.AVAILABLE; } SimulationEvent player = SimulationEventFactory.BuildEvent(ref simModelInfo, "PlayerControl"); ((StringValue)player["DecisionMakerID"]).value = dmID; ((StringValue)player["ControlledBy"]).value = "COMPUTER"; server.PutEvent(player); player = SimulationEventFactory.BuildEvent(ref simModelInfo, "DisconnectDecisionMaker"); ((StringValue)player["DecisionMakerID"]).value = dmID; server.PutEvent(player); }
private void buttonSendMessage_Click(object sender, EventArgs e) { //Check if a '/' command leads the string. //construct the send event string[] temp = textBoxMessage.Text.Split(' '); string sendingString = string.Empty; string targetUser = string.Empty; string chatType = string.Empty; bool send = true; if (temp[0] == @"/p") { //peer to peer command if (temp.Length < 3) { AddToTextBoxText("Incorrect Parameters for that message"); send = false; } else { sendingString = string.Empty; targetUser = temp[1]; temp[0] = string.Empty; temp[1] = string.Empty; chatType = "P2P"; foreach (string s in temp) { sendingString += s + " "; } } } else if (temp[0] == @"/t") { //TEAM CHAT sendingString = string.Empty; targetUser = "******"; //This should be the team name? temp[0] = string.Empty; temp[1] = string.Empty; chatType = "TEAM"; foreach (string s in temp) { sendingString += s + " "; } } else { //default sendingString = string.Empty; targetUser = "******"; chatType = "ALL"; foreach (string s in temp) { sendingString += s + " "; } } if (send) { sendingString = sendingString.Trim(); SimulationEvent se = SimulationEventFactory.BuildEvent(ref simModelInfo, "TextChatRequest"); ((StringValue)se["UserID"]).value = userID; ((StringValue)se["ChatBody"]).value = sendingString; ((StringValue)se["TargetUserID"]).value = targetUser; ((StringValue)se["ChatType"]).value = chatType; ((IntegerValue)se["Time"]).value = 0; server.PutEvent(se); if (chatType == "P2P") { AddToTextBoxText(String.Format("({0}) (PRIVATE to {1}): {2}", "0", targetUser, sendingString)); } else if (chatType == "TEAM") { // AddToTextBoxText(String.Format("({0}) (TEAMNAME): {1}", "0", sendingString)); } } //clear textbox textBoxMessage.Text = string.Empty; textBoxMessage.Focus(); }
public static void SendEvent(RootEventType sendingEvent) { //This will discover the RootEventType's actual Type of event, //and then based on that, will break out the information into //a simulation model event, and then putEvent to the NetworkClient string eventType; eventType = sendingEvent.GetType().Name.ToString(); SimulationEvent e = null; DataValue dv; bool hasAtt = false; string attName = null, attSettingType = null; switch (eventType) { /******************Very Basic Event Type Creation*******************************/ case "RootEventType": e = SimulationEventFactory.BuildEvent(ref simModelInfo, "BaseEvent"); dv = new IntegerValue(); ((IntegerValue)dv).value = sendingEvent.Timer; e.parameters["Time"] = dv; break; /******************Base Scenario Event Type Creation****************************/ case "ScenarioEventType": e = SimulationEventFactory.BuildEvent(ref simModelInfo, "BaseEvent"); dv = new IntegerValue(); ((IntegerValue)dv).value = sendingEvent.Timer; e.parameters["Time"] = dv; break; /******************New Object Event Type Creation ******************************/ case "Create_EventType": e = SimulationEventFactory.BuildEvent(ref simModelInfo, "NewObject"); Dictionary <string, DataValue> myAtt; myAtt = new Dictionary <string, DataValue>(); dv = new IntegerValue(); ((IntegerValue)dv).value = sendingEvent.Timer; e.parameters["Time"] = dv; //((StringValue)e.parameters["ObjectType"]).value = "PhysicalObject"; //Replaced by Kind from Scenario file ((StringValue)e.parameters["ObjectType"]).value = ((Create_EventType)sendingEvent).UnitKind.ToString(); // Attribute Insertion // if (((Create_EventType)sendingEvent).UnitID != null) { dv = new StringValue(); ((StringValue)dv).value = ((Create_EventType)sendingEvent).UnitID.ToString(); myAtt.Add("ID", dv); hasAtt = true; } List <ParameterSettingType> eventsList = ((Create_EventType)sendingEvent).Parameters; foreach (ParameterSettingType key in eventsList) { attName = key.Name; attSettingType = key.Setting.GetType().Name; if (attSettingType == "VectorType") { dv = new LocationValue(); ((LocationValue)dv).X = ((VectorType)key.Setting).X; ((LocationValue)dv).Y = ((VectorType)key.Setting).Y; ((LocationValue)dv).Z = ((VectorType)key.Setting).Z; myAtt.Add(attName, dv); } else if (attSettingType == "String") { switch (attName) { case "ID": //this shouldn't occur? dv = new StringValue(); ((StringValue)dv).value = key.Setting.ToString(); myAtt.Add(attName, dv); break; case "ObjectName": dv = new StringValue(); ((StringValue)dv).value = key.Setting.ToString(); myAtt.Add(attName, dv); break; case "ObjectState": dv = new StringValue(); ((StringValue)dv).value = key.Setting.ToString(); myAtt.Add(attName, dv); break; case "ClassName": dv = new StringValue(); ((StringValue)dv).value = key.Setting.ToString(); myAtt.Add(attName, dv); break; case "MaximumSpeed": dv = new DoubleValue(); ((DoubleValue)dv).value = Convert.ToDouble(key.Setting.ToString()); myAtt.Add(attName, dv); break; case "Throttle": dv = new DoubleValue(); ((DoubleValue)dv).value = Convert.ToDouble(key.Setting.ToString()); myAtt.Add(attName, dv); break; default: break; } } else { ; //Should be a vector type or a string, if not... do nothing. } } if (hasAtt) { ((AttributeCollectionValue)e.parameters["Attributes"]).attributes = myAtt; } break; /******************Move Object Event Type Creation******************************/ case "Move_EventType": e = SimulationEventFactory.BuildEvent(ref simModelInfo, "MoveObject"); if (((Move_EventType)sendingEvent).UnitID != null) { dv = new StringValue(); ((StringValue)dv).value = ((Move_EventType)sendingEvent).UnitID.ToString(); e.parameters["ObjectID"] = dv; } if (((Move_EventType)sendingEvent).Location != null) { dv = new LocationValue(); ((LocationValue)dv).X = ((VectorType)((Move_EventType)sendingEvent).Location).X; ((LocationValue)dv).Y = ((VectorType)((Move_EventType)sendingEvent).Location).Y; ((LocationValue)dv).Z = ((VectorType)((Move_EventType)sendingEvent).Location).Z; e.parameters["DestinationLocation"] = dv; } dv = new DoubleValue(); ((DoubleValue)dv).value = ((Double)((Move_EventType)sendingEvent).Throttle); e.parameters["Throttle"] = dv; dv = new IntegerValue(); ((IntegerValue)dv).value = sendingEvent.Timer; e.parameters["Time"] = dv; break; /******************Tick Event Type Creation*************************************/ case "TickEventType": e = SimulationEventFactory.BuildEvent(ref simModelInfo, "TimeTick"); dv = new IntegerValue(); ((IntegerValue)dv).value = sendingEvent.Timer; e.parameters["Time"] = dv; break; /******************No valid event entered***************************************/ default: //What should it do in this case? Nothing? break; } if (e != null) { server.PutEvent(e); } }
static void Main(string[] args) { /* setup the exit handler */ Console.TreatControlCAsInput = false; Console.CancelKeyPress += new ConsoleCancelEventHandler(MyExitHandler); /* read in the config file */ if (args.Length != 2) { Console.WriteLine(String.Format("Usage: {0} [CONFIG_FILE] [DDD_SIMULATION_MODEL]", Environment.CommandLine)); Environment.Exit(1); } string configFileName = args[0]; Console.WriteLine(String.Format("Reading config file: {0}", configFileName)); string simModelFile = args[1]; SimulationModelInfo simModel = null; SimulationModelReader smr = new SimulationModelReader(); try { simModel = smr.readModel(simModelFile); } catch (Exception e) { Console.WriteLine(e.Message); Environment.Exit(1); } ConfigFile config = new ConfigFile(); try { config.readFile(configFileName); } catch (Exception e) { Console.WriteLine(e.Message); Environment.Exit(1); } try { config.verifyConfig(); } catch (Exception e) { Console.WriteLine(e.Message); Environment.Exit(1); } /* connect to the DDD Server */ dddNetworkClient = new NetworkClient(); if (!dddNetworkClient.Connect(config.dddServerHostname, config.dddServerPortNumber)) { Environment.Exit(1); } /* connect to the IMAP server */ imapServer = new Chilkat.Imap(); imapServer.Port = config.emailServerPortNumber; imapServer.Ssl = config.emailServerUseSSL; bool success; // Anything unlocks the component and begins a fully-functional 30-day trial. success = imapServer.UnlockComponent("SAptimaIMAPMAIL_yyq2ULZCFw4G"); if (success != true) { Console.WriteLine(imapServer.LastErrorText); ExitApp(); } /* loop reading from the IMAP Server until user cancels or the DDD disconnects us */ int count = config.emailCheckFrequency; while (dddNetworkClient.IsConnected()) { if (count == config.emailCheckFrequency) { Console.WriteLine("Checking email"); // Connect to an IMAP server. success = imapServer.Connect(config.emailServerHostname); if (success != true) { Console.WriteLine(imapServer.LastErrorText); ExitApp(); } // Login success = imapServer.Login(config.emailUsername, config.emailPassword); if (success != true) { Console.WriteLine(imapServer.LastErrorText); ExitApp(); } // Select an IMAP mailbox success = imapServer.SelectMailbox("Inbox"); if (success != true) { Console.WriteLine(imapServer.LastErrorText); ExitApp(); } Chilkat.MessageSet messageSet; // We can choose to fetch UIDs or sequence numbers. bool fetchUids; fetchUids = true; /* downloading new emails from IMAP server */ messageSet = imapServer.Search("NOT SEEN", fetchUids); if (messageSet == null) { Console.WriteLine(imapServer.LastErrorText); ExitApp(); } // Fetch the emails into a bundle object: Chilkat.EmailBundle bundle; bundle = imapServer.FetchBundle(messageSet); if (bundle == null) { Console.WriteLine(imapServer.LastErrorText); ExitApp(); } imapServer.Disconnect(); int i; Chilkat.Email email; for (i = 0; i <= bundle.MessageCount - 1; i++) { email = bundle.GetEmail(i); SimulationEvent ev = SimulationEventFactory.BuildEvent(ref simModel, "ExternalEmailReceived"); ((StringValue)ev["FromAddress"]).value = email.FromAddress; for (int k = 0; k < email.NumTo; k++) { ((StringListValue)ev["ToAddresses"]).strings.Add(email.GetToAddr(k)); //Console.WriteLine("To:" + email.GetToAddr(k)); } //Console.WriteLine("Wall clock time:" + email.LocalDate.ToString()); ((StringValue)ev["WallClockTime"]).value = email.LocalDate.ToString(); //Console.WriteLine("Subject:" + email.Subject); ((StringValue)ev["Subject"]).value = email.Subject; //Console.WriteLine("Body:" + email.Body); ((StringValue)ev["Body"]).value = email.Body; //Console.WriteLine("NumAttachments:" + email.NumAttachments.ToString()); string attachName; string attachDir; string dirPath; for (int j = 0; j < email.NumAttachments; j++) { attachName = email.GetAttachmentFilename(j); //Console.WriteLine("filename=" + email.GetAttachmentFilename(j)); attachDir = String.Format("Attachments{0}", email.LocalDate.ToString("yyyyMMddHHmmss")); dirPath = String.Format("{0}\\{1}", config.attachmentBaseDirectory, UniqueDirName(config.attachmentBaseDirectory, attachDir)); Directory.CreateDirectory(dirPath); attachName = String.Format("{0}\\{1}", dirPath, email.GetAttachmentFilename(j)); ((StringListValue)ev["Attachments"]).strings.Add(attachName); email.SaveAttachedFile(j, dirPath); } dddNetworkClient.PutEvent(ev); Console.WriteLine(SimulationEventFactory.XMLSerialize(ev)); } count = 0; } Thread.Sleep(1000); count++; } ExitApp(); }
private void TimeTick(SimulationEvent e) { time = ((IntegerValue)e["Time"]).value; DataValue dv = null; SimulationObjectProxy targetProx = null; Vec3D targetLoc = new Vec3D(0, 0, 0); SimulationObjectProxy obProx = null; bool selfDefenseStartAttack; string selfDefenseCapability; string selfDefenseTargetID; Dictionary <string, Dictionary <string, List <AttackCollectionValue.AttackValue> > > currentAttackCollection = new Dictionary <string, Dictionary <string, List <AttackCollectionValue.AttackValue> > >(); //[ [TargetID]/[ CapabilityUsed]/[List of Attacks] ] Dictionary <string, List <AttackCollectionValue.AttackValue> > attacksToRemove = new Dictionary <string, List <AttackCollectionValue.AttackValue> >(); // [AttackerID]/[List of attacks to remove] //as you clean up attacks, add them to this list. once done iterating over targets, go through this list and update the attacks in the keys. foreach (string id in objectProxies.Keys) { obProx = objectProxies[id]; //Generate Attack dictionary AttackCollectionValue attacks = (AttackCollectionValue)obProx["CurrentAttacks"].GetDataValue(); foreach (AttackCollectionValue.AttackValue av in attacks.GetCurrentAttacks()) { if (!currentAttackCollection.ContainsKey(av.targetObjectId)) { currentAttackCollection.Add(av.targetObjectId, new Dictionary <string, List <AttackCollectionValue.AttackValue> >()); } if (!currentAttackCollection[av.targetObjectId].ContainsKey(av.capabilityName)) { currentAttackCollection[av.targetObjectId].Add(av.capabilityName, new List <AttackCollectionValue.AttackValue>()); } currentAttackCollection[av.targetObjectId][av.capabilityName].Add(av); //store pointer } selfDefenseStartAttack = ((BooleanValue)obProx["SelfDefenseStartAttack"].GetDataValue()).value; if (selfDefenseStartAttack) { selfDefenseCapability = ((StringValue)obProx["SelfDefenseCapability"].GetDataValue()).value; selfDefenseTargetID = ((StringValue)obProx["SelfDefenseTargetID"].GetDataValue()).value; targetProx = objectProxies[selfDefenseTargetID]; if (((AttackCollectionValue)obProx["CurrentAttacks"].GetDataValue()).GetCurrentAttacks().Count == 0 && ((StringValue)obProx["State"].GetDataValue()).value != "Dead" && ((StringValue)targetProx["State"].GetDataValue()).value != "Dead") { AttackObject(id, selfDefenseTargetID, selfDefenseCapability, 100, true); if (((StringValue)obProx["AttackState"].GetDataValue()).value == "") { SendSelfDefenseAttackStarted(id, selfDefenseTargetID); } } } } foreach (string targetID in objectProxies.Keys) { targetProx = objectProxies[targetID]; string currentState = ((StringValue)objectProxies[targetID]["State"].GetDataValue()).value; dv = targetProx["AttackState"].GetDataValue(); if (((StringValue)dv).value == "BEING_ATTACKED") { if (!currentAttackCollection.ContainsKey(targetID)) { currentAttackCollection.Add(targetID, new Dictionary <string, List <AttackCollectionValue.AttackValue> >()); //this should not happen, or we're in trouble } int capabilitiesCompleted = 0; //this gets incremented as you add to attacksToRemove foreach (String capability in currentAttackCollection[targetID].Keys) { //update attack windows for each attack object? int attackEndTime = -1; foreach (AttackCollectionValue.AttackValue av in currentAttackCollection[targetID][capability]) { if (attackEndTime == -1) { attackEndTime = av.attackStartTime + av.attackTimeWindow; } else { attackEndTime = Math.Min(attackEndTime, av.attackStartTime + av.attackTimeWindow); } } int newDuration = attackEndTime - time; foreach (AttackCollectionValue.AttackValue av in currentAttackCollection[targetID][capability]) { av.attackTimeWindow = attackEndTime - av.attackStartTime;// newDuration; } //check attack window vs current time if (time >= attackEndTime) { //cleanup if needed //add attacks to remove list foreach (AttackCollectionValue.AttackValue av in currentAttackCollection[targetID][capability]) { if (!attacksToRemove.ContainsKey(av.attackingObjectId)) { attacksToRemove.Add(av.attackingObjectId, new List <AttackCollectionValue.AttackValue>()); } attacksToRemove[av.attackingObjectId].Add(av); } //check vulnerabilities VulnerabilityValue targetVul = (VulnerabilityValue)targetProx["Vulnerability"].GetDataValue(); bool attackSuccess = false; List <string> capabilitiesApplied; List <string> attackers = new List <string>(); foreach (VulnerabilityValue.Transition t in targetVul.transitions) { foreach (String cap in t.GetAppliedCapabilities()) { if (!currentAttackCollection[targetID].ContainsKey(cap)) { continue; //workaround for issue at USF; for some reason capability was not added to current attack collection. } foreach (AttackCollectionValue.AttackValue val in currentAttackCollection[targetID][cap]) { string attackerID = val.attackingObjectId; if (!attackers.Contains(attackerID)) { attackers.Add(attackerID); } } } if (t.ConditionsMet()) { capabilitiesApplied = t.GetAppliedCapabilities(); // Send state change string newState = t.state; SimulationEvent sc = SimulationEventFactory.BuildEvent(ref simModel, "StateChange"); ((StringValue)sc["ObjectID"]).value = targetID; ((StringValue)sc["NewState"]).value = newState; ((IntegerValue)sc["Time"]).value = time; distClient.PutEvent(sc); foreach (string attackerID in attackers) { distClient.PutEvent(SimUtility.BuildSystemMessageEvent(ref simModel, time, ((StringValue)(objectProxies[attackerID]["OwnerID"].GetDataValue())).value, attackerID + " has succesfully engaged " + targetID)); distClient.PutEvent(SimUtility.BuildSystemMessageEvent(ref simModel, time, ((StringValue)(targetProx["OwnerID"].GetDataValue())).value, targetID + " has been succesfully engaged by " + attackerID)); ScoringDB.UpdateScore_StateChange(new ScoringDB.ActorFrame(attackerID, StateDB.physicalObjects[attackerID].speciesName, StateDB.physicalObjects[attackerID].ownerID, StateDB.physicalObjects[attackerID].activeRegions), currentState, t.state, new ScoringDB.ActorFrame(targetID, StateDB.physicalObjects[targetID].speciesName, StateDB.physicalObjects[targetID].ownerID, StateDB.physicalObjects[targetID].activeRegions)); } t.ClearAppliedEffects(); distClient.PutEvent(SimUtility.BuildHistory_AttackedObjectReportEvent(ref simModel, time, targetID, targetLoc, true, t.state)); distClient.PutEvent(SimUtility.BuildAttackSucceededEvent(ref simModel, time, attackers[0], targetID, newState, capabilitiesApplied)); attackSuccess = true; break; } } //send messages if (!attackSuccess) { foreach (String attackerID in attackers) { distClient.PutEvent(SimUtility.BuildSystemMessageEvent(ref simModel, time, ((StringValue)(objectProxies[attackerID]["OwnerID"].GetDataValue())).value, attackerID + " has failed in engagement of " + targetID)); distClient.PutEvent(SimUtility.BuildSystemMessageEvent(ref simModel, time, ((StringValue)(targetProx["OwnerID"].GetDataValue())).value, targetID + " has been unsuccesfully engaged by " + attackerID)); } foreach (VulnerabilityValue.Transition t in targetVul.transitions) { t.ClearAppliedEffects(); } distClient.PutEvent(SimUtility.BuildHistory_AttackedObjectReportEvent(ref simModel, time, targetID, targetLoc, false, "")); } capabilitiesCompleted++; //if there are more capabilities being applied than this one, don't remove target's attack state. if (currentAttackCollection[targetID].Count - capabilitiesCompleted == 0) {// this occurs when all attacks will be removed in this loop dv = targetProx["AttackState"].GetDataValue(); ((StringValue)dv).value = ""; targetProx["AttackState"].SetDataValue(dv); } } } foreach (string attackerID in attacksToRemove.Keys) { SimulationObjectProxy attackerProxy = objectProxies[attackerID]; if (attackerProxy != null) { AttackCollectionValue acv = attackerProxy["CurrentAttacks"].GetDataValue() as AttackCollectionValue; foreach (AttackCollectionValue.AttackValue attackVal in attacksToRemove[attackerID]) { if (!acv.RemoveAttack(attackVal)) { acv.RemoveAttack(attackVal.capabilityName, attackVal.targetObjectId, attackVal.attackingObjectId, attackVal.attackStartTime); } } attackerProxy["CurrentAttacks"].SetDataValue(acv); if (((BooleanValue)attackerProxy["IsWeapon"].GetDataValue()).value) { distClient.PutEvent(SimUtility.BuildStateChangeEvent(ref simModel, time, attackerID, "Dead")); } } } if (capabilitiesCompleted > 0) {//some attacks were removed, actually remove them from the currentAttackCollection, update attacker list. //update attack lists (this will require some iteration over the attacks. List <string> attackers = null; dv = targetProx["AttackerList"].GetDataValue(); attackers = ((StringListValue)dv).strings; attackers.Clear(); foreach (String capability in currentAttackCollection[targetID].Keys) { foreach (AttackCollectionValue.AttackValue av in currentAttackCollection[targetID][capability]) { if (!attackers.Contains(av.attackingObjectId)) { attackers.Add(av.attackingObjectId); } } } ((StringListValue)dv).strings = attackers; targetProx["AttackerList"].SetDataValue(dv); } } } }
private void TimeTick(SimulationEvent e) { int oldTime = time; DataValue dv = null; //Vec3D curVec = new Vec3D(0, 0, 0); //Vec3D destVec = new Vec3D(0, 0, 0); //Vec3D velVec = new Vec3D(0, 0, 0); Vec3D loc1 = new Vec3D(0, 0, 0); Vec3D loc2 = new Vec3D(0, 0, 0); Vec3D next1 = new Vec3D(0, 0, 0); Vec3D next2 = new Vec3D(0, 0, 0); Vec3D vel1 = new Vec3D(0, 0, 0); Vec3D vel2 = new Vec3D(0, 0, 0); dv = e["Time"]; time = ((IntegerValue)dv).value; double dTime = ((double)(time - oldTime)) / 1000; SimulationObjectProxy obProx1 = null; SimulationObjectProxy obProx2 = null; List <string> ids = new List <string>(objectProxies.Keys); string id1; SimulationEvent collision = null; double distance; double? d; while (ids.Count > 0) { id1 = ids[0]; ids.Remove(id1); foreach (string id2 in ids) { d = ObjectDistances.GetScalarDistanceBetweenObjects(id1, id2); if (d == null) { // Don't look for collisions if they aren't on the screen continue; } distance = d.Value; double objectSize1 = 0; double objectSize2 = 0; obProx1 = objectProxies[id1]; obProx2 = objectProxies[id2]; //// Don't look for collisions if they aren't on the screen dv = obProx1["Location"].GetDataValue(); //if (!((LocationValue)dv).exists) //{ // continue; //} loc1.Set((LocationValue)dv); dv = obProx2["Location"].GetDataValue(); //if (!((LocationValue)dv).exists) //{ // continue; //} loc2.Set((LocationValue)dv); if (((BooleanValue)obProx1["DockedToParent"].GetDataValue()).value) { continue; } if (((BooleanValue)obProx2["DockedToParent"].GetDataValue()).value) { continue; } // Don't look for collisions if they are owned by the same player if (StateDB.physicalObjects[id1].ownerID == StateDB.physicalObjects[id2].ownerID) { continue; } // Don't look for collisions if they are on the same team if (StateDB.physicalObjects[id1].teamName == StateDB.physicalObjects[id2].teamName) { continue; } //Don't look for collisions if they are not hostile if (StateDB.teams.ContainsKey(StateDB.physicalObjects[id1].teamName) && StateDB.teams.ContainsKey(StateDB.physicalObjects[id2].teamName)) { if (!StateDB.teams[StateDB.physicalObjects[id1].teamName].hostility.Contains(StateDB.teams[StateDB.physicalObjects[id2].teamName].id) && !StateDB.teams[StateDB.physicalObjects[id2].teamName].hostility.Contains(StateDB.teams[StateDB.physicalObjects[id1].teamName].id)) {//only continue if both teams are not hostile to one another continue; } } CapabilityValue.Effect eff = null; // check ranges and add objects to target lists for self defense sim CapabilityValue cap1 = ((CapabilityValue)obProx1["Capability"].GetDataValue()); VulnerabilityValue vul1 = ((VulnerabilityValue)obProx1["Vulnerability"].GetDataValue()); CapabilityValue cap2 = ((CapabilityValue)obProx2["Capability"].GetDataValue()); VulnerabilityValue vul2 = ((VulnerabilityValue)obProx2["Vulnerability"].GetDataValue()); //double distance = loc1.ScalerDistanceTo(loc2); eff = SimUtility.FindCapabilityEffect(cap1, vul2); dv = obProx1["TargetsInRange"].GetDataValue(); //AD: TODO need a "TargetsInSensorRange"? which can drive the ViewPro loops if (eff != null && distance <= eff.range && ((StringValue)obProx2["State"].GetDataValue()).value != "Dead") { if (!((StringListValue)dv).strings.Contains(id2)) { ((StringListValue)dv).strings.Add(id2); } } else { if (((StringListValue)dv).strings.Contains(id2)) { ((StringListValue)dv).strings.Remove(id2); } } obProx1["TargetsInRange"].SetDataValue(dv); eff = SimUtility.FindCapabilityEffect(cap2, vul1); dv = obProx2["TargetsInRange"].GetDataValue(); if (eff != null && distance <= eff.range && ((StringValue)obProx1["State"].GetDataValue()).value != "Dead") { if (!((StringListValue)dv).strings.Contains(id1)) { ((StringListValue)dv).strings.Add(id1); } } else { if (((StringListValue)dv).strings.Contains(id1)) { ((StringListValue)dv).strings.Remove(id1); } } obProx2["TargetsInRange"].SetDataValue(dv); // Don't look for collisions if they are dead if (((StringValue)obProx1["State"].GetDataValue()).value == "Dead") { continue; } if (((StringValue)obProx2["State"].GetDataValue()).value == "Dead") { continue; } // Don't look for collisions if they are too small to collide dv = obProx1["Size"].GetDataValue(); objectSize1 = ((DoubleValue)dv).value; if (objectSize1 <= 0.000001) { continue; } dv = obProx2["Size"].GetDataValue(); objectSize2 = ((DoubleValue)dv).value; if (objectSize2 <= 0.000001) { continue; } dv = obProx1["Velocity"].GetDataValue(); vel1.Set((VelocityValue)dv); dv = obProx2["Velocity"].GetDataValue(); vel2.Set((VelocityValue)dv); if (vel1.X == 0 && vel2.X == 0 && vel1.Y == 0 && vel2.Y == 0 && vel1.Z == 0 && vel2.Z == 0) { continue; } next1 = loc1.Add(vel1.Multiply(dTime)); next2 = loc2.Add(vel2.Multiply(dTime)); if (next1.ScalerDistanceTo(next2) < (objectSize1 + objectSize2)) { collision = SimulationEventFactory.BuildEvent(ref simModel, "ObjectCollision"); ((StringValue)collision["ObjectID1"]).value = id1; ((StringValue)collision["ObjectID2"]).value = id2; ((IntegerValue)collision["Time"]).value = time; distClient.PutEvent(collision); } } } /*foreach (string id1 in objectProxies.Keys) * { * foreach (string id2 in objectProxies.Keys) * { * if (id1 == id2) * { * continue; * } * obProx1 = objectProxies[id1]; * obProx2 = objectProxies[id1]; * * dv = obProx1["Location"].GetDataValue(); * loc1.Set((LocationValue)dv); * dv = obProx2["Location"].GetDataValue(); * loc2.Set((LocationValue)dv); * * } * * }*/ }
/// <summary> /// *Intercepted Event From Client* When this event is received, you'll need to extract /// the weapon's class from the ObjectID field, and use this class along with the /// ParentObjectID to determine which weapon is actually being launched. /// </summary> /// <param name="e">Incoming event</param> private void ClientAttackRequest(SimulationEvent e) { string playerID = string.Empty; string attObjectID = string.Empty; string tarObjectID = string.Empty; string weaponName = string.Empty; int time = ((IntegerValue)e["Time"]).value; SimulationObjectProxy attackingObjectProxy; SimulationEvent sendingEvent; playerID = ((StringValue)e["PlayerID"]).value; attObjectID = ((StringValue)e["AttackingObjectID"]).value; tarObjectID = ((StringValue)e["TargetObjectID"]).value; weaponName = ((StringValue)e["WeaponOrCapabilityName"]).value; //// Added now that weapons are sent out with a quantity if (weaponName.Contains("x)") && weaponName.Contains("(")) {//Most likely a weapon with a quantity char[] ch = { '(' }; string[] splits = weaponName.Split(ch, StringSplitOptions.RemoveEmptyEntries); weaponName = splits[0].Trim(); } //// if (objectProxies.ContainsKey(attObjectID)) { attackingObjectProxy = objectProxies[attObjectID]; List <string> dockedWeapons = ((StringListValue)attackingObjectProxy["DockedWeapons"].GetDataValue()).strings; SimulationObjectProxy weaponProxy; foreach (string w in dockedWeapons) { weaponProxy = objectProxies[w]; if (((StringValue)weaponProxy["ClassName"].GetDataValue()).value == weaponName) { weaponName = w; } } if (dockedWeapons.Contains(weaponName)) { //send weapon attack sendingEvent = SimulationEventFactory.BuildEvent(ref simModel, "WeaponLaunchRequest"); sendingEvent["UserID"] = DataValueFactory.BuildString(playerID); sendingEvent["ParentObjectID"] = DataValueFactory.BuildString(attObjectID); sendingEvent["TargetObjectID"] = DataValueFactory.BuildString(tarObjectID); sendingEvent["ObjectID"] = DataValueFactory.BuildString(weaponName); sendingEvent["Time"] = DataValueFactory.BuildInteger(time); distClient.PutEvent(sendingEvent); //remove from docked weapons, per MS State bug report. If weapon launch fails, re-add subplatform to docked weapons DataValue dv = attackingObjectProxy["DockedWeapons"].GetDataValue(); bool result = dockedWeapons.Remove(weaponName); if (result) { ((StringListValue)dv).strings = dockedWeapons; attackingObjectProxy["DockedWeapons"].SetDataValue(dv); } else { //should not happen, throw error. } } else {//send capability attack sendingEvent = SimulationEventFactory.BuildEvent(ref simModel, "AttackObjectRequest"); sendingEvent["UserID"] = DataValueFactory.BuildString(playerID); sendingEvent["ObjectID"] = DataValueFactory.BuildString(attObjectID); sendingEvent["TargetObjectID"] = DataValueFactory.BuildString(tarObjectID); sendingEvent["CapabilityName"] = DataValueFactory.BuildString(weaponName); sendingEvent["Time"] = DataValueFactory.BuildInteger(time); distClient.PutEvent(sendingEvent); } } }
/// <summary> /// This method extracts an objects attributes from DetectedValues in an ACV, and then sends /// out the appropriate info to a specified player. /// </summary> /// <param name="destinationPlayerID"></param> /// <param name="objectsAttributes"></param> /// <param name="time"></param> private void SendViewProAttributeUpdate(string destinationPlayerID, AttributeCollectionValue objectsAttributes) { if (!activeDMs.Contains(destinationPlayerID)) { return; } SimulationEvent vpu = null; objectsAttributes = ExtractDetectedValuesFromACV(objectsAttributes); AddCapabilitiesAndWeaponsList(ref objectsAttributes); if (objectsAttributes.attributes.ContainsKey("Vulnerability")) { List <string> vulnerabilityList = new List <string>(); foreach (VulnerabilityValue.Transition t in ((VulnerabilityValue)objectsAttributes["Vulnerability"]).transitions) { foreach (VulnerabilityValue.TransitionCondition tc in t.conditions) { if (!vulnerabilityList.Contains(tc.capability)) { vulnerabilityList.Add(tc.capability); } } } // objectsAttributes.attributes.Remove("Vulnerability"); StringListValue sl = new StringListValue(); sl.strings = vulnerabilityList; objectsAttributes.attributes.Add("VulnerabilityList", sl as DataValue); } if (objectsAttributes.attributes.ContainsKey("Sensors")) { List <string> sensorList = new List <string>(); foreach (SensorValue sv in ((SensorArrayValue)objectsAttributes["Sensors"]).sensors) { if (!sensorList.Contains(sv.sensorName)) { sensorList.Add(sv.sensorName); } } // objectsAttributes.attributes.Remove("Sensors"); StringListValue sl = new StringListValue(); sl.strings = sensorList; objectsAttributes.attributes.Add("SensorList", sl as DataValue); } objectsAttributes["DockedObjects"] = new StringListValue(); List <string> strList = new List <string>(); //if (((StringValue)objectProxies[((StringValue)objectsAttributes["ID"]).value]["ParentObjectID"].GetDataValue()).value != string.Empty) //{ // strList.Add("Dock To Parent"); //} strList.AddRange(((StringListValue)objectProxies[((StringValue)objectsAttributes["ID"]).value]["DockedObjects"].GetDataValue()).strings); ((StringListValue)objectsAttributes["DockedObjects"]).strings = strList; vpu = SimulationEventFactory.BuildEvent(ref simModel, "ViewProAttributeUpdate"); if (!objectsAttributes.attributes.ContainsKey("MaximumSpeed")) { DoubleValue dv = new DoubleValue(); dv.value = ((DoubleValue)objectProxies[((StringValue)objectsAttributes["ID"]).value]["MaximumSpeed"].GetDataValue()).value * ((DoubleValue)objectProxies[((StringValue)objectsAttributes["ID"]).value]["ActiveRegionSpeedMultiplier"].GetDataValue()).value; objectsAttributes.attributes.Add("MaximumSpeed", dv as DataValue); } String classification = GetClassificationForDM(((StringValue)objectsAttributes["ID"]).value, destinationPlayerID); objectsAttributes["CurrentClassification"] = DataValueFactory.BuildString(classification); String overrideIcon = GetClassificationBasedIcon(((StringValue)objectsAttributes["ID"]).value, classification); if (overrideIcon != String.Empty) { objectsAttributes["IconName"] = DataValueFactory.BuildString(overrideIcon); } else { SimulationObjectProxy ob = objectProxies[((StringValue)objectsAttributes["ID"]).value]; objectsAttributes["IconName"] = DataValueFactory.BuildString(((StringValue)ob["IconName"].GetDataValue()).value); } vpu["TargetPlayer"] = DataValueFactory.BuildString(destinationPlayerID); vpu["ObjectID"] = objectsAttributes["ID"]; vpu["OwnerID"] = objectsAttributes["OwnerID"]; //RANGE RING LOGIC string ownerId = ((StringValue)objectsAttributes["OwnerID"]).value; if (((destinationPlayerID == ownerId || selectedRangeRingLevel == RangeRingLevels.FULL) || (selectedRangeRingLevel == RangeRingLevels.SENSORNETWORK && AreDecisionMakersInSharedNetwork(destinationPlayerID, ownerId))) && selectedRangeRingLevel != RangeRingLevels.DISABLED) //this needs to be based on ownership, etc. { SimulationObjectProxy objProxy = null; if (objectProxies.ContainsKey(((StringValue)objectsAttributes["ID"]).value)) { objProxy = objectProxies[((StringValue)objectsAttributes["ID"]).value]; AddRangeRings(ref objectsAttributes, ref objProxy); } else { //if not, something's wrong Console.WriteLine("HELP"); } } else { objectsAttributes.attributes.Remove("Vulnerability"); objectsAttributes.attributes.Remove("Sensors"); objectsAttributes.attributes.Remove("Capability"); } // //if (objectsAttributes.attributes.ContainsKey("MaximumSpeed")) //{ // Console.Out.Write(String.Format("{0} moving at {1}", ((StringValue)objectsAttributes["ID"]).value, ((DoubleValue)objectsAttributes["MaximumSpeed"]).value)); // //foreach (string s in objectsAttributes.attributes.Keys) // //{ // // Console.Out.Write(String.Format("{0}, ", s)); // //} // Console.Out.WriteLine(); //} vpu["Attributes"] = objectsAttributes; vpu["Time"] = DataValueFactory.BuildInteger(currentTick); string xml = DataValueFactory.XMLSerialize(objectsAttributes); AttributeCollectionValue temp = new AttributeCollectionValue(); temp.FromXML(xml); distClient.PutEvent(vpu); }
private void TimeTick(SimulationEvent e) { int oldTime = time; DataValue dv = null; dv = e["Time"]; time = ((IntegerValue)dv).value; double dTime = ((double)(time - oldTime)) / 1000; SimulationObjectProxy obProx = null; double throttle = 0; double fuelAmount = 0; double fuelConsumptionRate = 0; bool dockedToParent = false; foreach (string id in objectProxies.Keys) { obProx = objectProxies[id]; dv = obProx["FuelConsumptionRate"].GetDataValue(); fuelConsumptionRate = ((DoubleValue)dv).value; if (fuelConsumptionRate == 0) { continue; } dv = obProx["DockedToParent"].GetDataValue(); dockedToParent = ((BooleanValue)dv).value; if (dockedToParent) { continue; } dv = obProx["FuelAmount"].GetDataValue(); fuelAmount = ((DoubleValue)dv).value; if (fuelAmount == 0) { continue; } dv = obProx["Throttle"].GetDataValue(); throttle = ((DoubleValue)dv).value; dv = obProx["FuelAmount"].GetDataValue(); fuelAmount = ((DoubleValue)dv).value; fuelAmount -= dTime * throttle * fuelConsumptionRate; if (fuelAmount <= 0) { fuelAmount = 0; // Send state change dv = obProx["FuelDepletionState"].GetDataValue(); if (dv != null) { SimulationEvent sc = SimulationEventFactory.BuildEvent(ref simModel, "StateChange"); ((StringValue)sc["ObjectID"]).value = id; ((StringValue)sc["NewState"]).value = ((StringValue)dv).value; ((IntegerValue)sc["Time"]).value = time; distClient.PutEvent(sc); } } dv = obProx["FuelAmount"].GetDataValue(); ((DoubleValue)dv).value = fuelAmount; obProx["FuelAmount"].SetDataValue(dv); } }
private void AttackSucceeded(SimulationEvent e) { if (objectProxies.Count == 0) { return; //another weird edge case } try { String objectID = ((StringValue)e["ObjectID"]).value; SimulationObjectProxy proxy = objectProxies[objectID]; String targetID = ((StringValue)e["TargetID"]).value; SimulationObjectProxy targetProxy = objectProxies[targetID]; String transitionState = ((StringValue)e["NewState"]).value; // It's a sea vessel if it's not a BAMS or Firescout String targetClassName = ((StringValue)targetProxy["ClassName"].GetDataValue()).value; if (targetClassName != "BAMS" && targetClassName != "Firescout" && transitionState == "Dead") { targetProxy["DestroyedTime"].SetDataValue(DataValueFactory.BuildInteger(time)); targetProxy["DestroyedBy"].SetDataValue(DataValueFactory.BuildString(objectID)); //AD: TODO Send view pro attribute event for these objects. SimulationEvent ev = SimulationEventFactory.BuildEvent(ref simModel, "ViewProAttributeUpdate"); AttributeCollectionValue acv = new AttributeCollectionValue(); // acv.attributes.Add("DestroyedTime", DataValueFactory.BuildDetectedValue(DataValueFactory.BuildInteger(time), 100)); // acv.attributes.Add("DestroyedBy", DataValueFactory.BuildDetectedValue(DataValueFactory.BuildString(objectID), 100)); acv.attributes.Add("DestroyedTime", DataValueFactory.BuildInteger(time)); acv.attributes.Add("DestroyedBy", DataValueFactory.BuildString(objectID)); ((StringValue)ev["TargetPlayer"]).value = "BAMS DM"; ((StringValue)ev["ObjectID"]).value = ((StringValue)targetProxy["ID"].GetDataValue()).value; ((StringValue)ev["OwnerID"]).value = ((StringValue)targetProxy["OwnerID"].GetDataValue()).value; ((IntegerValue)ev["Time"]).value = time * 1000; ev["Attributes"] = acv; distClient.PutEvent(ev); ((StringValue)ev["TargetPlayer"]).value = "Firescout DM"; distClient.PutEvent(ev); ((StringValue)ev["TargetPlayer"]).value = "Individual DM"; distClient.PutEvent(ev); } String targetOwnerID = ((StringValue)targetProxy["OwnerID"].GetDataValue()).value; String attackerOwnerID = ((StringValue)proxy["OwnerID"].GetDataValue()).value; if (transitionState == "Dead") { //Clear the intent of any other vessel mentioned in target's intent (pursued or pursuee). String targetIntent = ((StringValue)targetProxy["Intent"].GetDataValue()).value; if (targetIntent != "") { String[] intentArray = targetIntent.Split(":".ToCharArray()); if (intentArray.Length > 1) { SimulationObjectProxy vesselProxyToClear = objectProxies[intentArray[1]]; vesselProxyToClear["Intent"].SetDataValue(DataValueFactory.BuildString("")); } } //IF friendly, increment counter if (!targetOwnerID.ToLower().Contains("pirate")) { IncrementFriendliesLost(1); String attackClassName = ((StringValue)proxy["ClassName"].GetDataValue()).value; if (attackClassName == "BAMS" || attackClassName == "Firescout") { //IF friendly, and attacker was BAMS/FS IncrementFriendliesDestroyedByPlayers(1); } } else { //if hostile increment counter IncrementHostileTargetsDestroyed(1); } } //if (targetClassName == "BAMS" || targetClassName == "Firescout") //{ // //if bams/firescout, increment counter // IncrementHitsTakenByAssets(1); //} if (!attackerOwnerID.Contains("BAMS") && !attackerOwnerID.Contains("Firescout") && !attackerOwnerID.Contains("Individual")) { return; //the following section is only for YOUR attacks, so return if its not BAMS or FS } String attackClass = ((StringValue)proxy["ClassName"].GetDataValue()).value; String targetClassification = ""; try { targetClassification = classifications[targetID]; } catch (Exception exc) { } if (targetClassification != "Hostile" && (targetClassName != "BAMS" || targetClassName != "Firescout")) { //if asset was not classified as hostile, violated ROE IncrementRulesOfEngagementViolations(1); } } catch (Exception ex) { } }
private void EventLoop() { try { List <SimulationEvent> events = null; DateTime nowTimer = new DateTime(); DateTime tickTimer = DateTime.Now; DateTime startTime = new DateTime(); int eventCounter = 0; long start; long end; Dictionary <string, long> simTimes = new Dictionary <string, long>(); foreach (SimulatorExecutionInfo sei in simModelInfo.simulationExecutionModel.simulators) { simTimes[sei.simulatorName] = 0; } while (true) { nowTimer = DateTime.Now; lock (simCoreLock) { switch (state) { case SimCoreState.UNINITIALIZED: throw new Exception("SimCore: shouldn't be in event loop if uninitialized"); case SimCoreState.RUNNING: //distributor.StopIncoming(); events = distClient.GetEvents(); eventCounter = events.Count; foreach (SimulationEvent e in events) { switch (e.eventType) { case "TimeTick": lock (simTimeLock) { simulationTime = (int)((IntegerValue)e["Time"]).value; if (ServerOptions.UsePerformanceLog) { StringBuilder b = new StringBuilder(); b.AppendFormat("SimCore Metric: SimTime: {0}; Processing Time: {1}.", simulationTime / 1000, DateTime.Now - tickTimer); PerformanceLog.Write(b.ToString()); } tickTimer = DateTime.Now; if (simulationTime == 1000) { startTime = DateTime.Now; } } break; case "ExternalApp_SimStop": //Console.Out.WriteLine("SimCore Metric: Exiting SimCore loop. Total run time: {0}; Total ticks: {1}.", DateTime.Now - startTime, (simulationTime / 1000) - 1);//-1 because it is starting at time 1 isReady = false; break; //case "PauseScenario": // if (simulators.ContainsKey("ViewPro")) // { // ((ViewProSim)simulators["ViewPro"]).PauseScenario(); // } // break; //case "ResumeScenario": // if (simulators.ContainsKey("ViewPro")) // { // ((ViewProSim)simulators["ViewPro"]).ResumeScenario(); // } // break; case "ResetSimulation": lock (simTimeLock) { simulationTime = 0; isReady = false; } break; default: break; } //foreach (SimulatorExecutionInfo sei in simModelInfo.simulationExecutionModel.simulators) foreach (KeyValuePair <String, ISimulator> sim in simulators) { start = DateTime.Now.Ticks; //simulators[sei.simulatorName].ProcessEvent(e); sim.Value.ProcessEvent(e); end = DateTime.Now.Ticks; //simTimes[sei.simulatorName] += (end - start); simTimes[sim.Key] += (end - start); } if (e.eventType == "StartupComplete") { SimulationEvent ev = SimulationEventFactory.BuildEvent(ref simModelInfo, "SimCoreReady"); isReady = true; distClient.PutEvent(ev); if (ServerOptions.UsePerformanceLog) { foreach (SimulatorExecutionInfo sei in simModelInfo.simulationExecutionModel.simulators) { if (!simTimes.ContainsKey(sei.simulatorName)) { continue; } StringBuilder b = new StringBuilder(); b.AppendFormat("SimCore Metric: Initialization time in: {0} was {1} seconds.", sei.simulatorName, simTimes[sei.simulatorName] / 10000000.0); PerformanceLog.Write(b.ToString()); simTimes[sei.simulatorName] = 0; } } } } if (eventCounter > 0) { //Console.Out.WriteLine("SimCore Metric: Events Processed: {0}; processing time: {1}.", eventCounter, DateTime.Now - nowTimer); //distributor.ResumeIncoming(); } break; case SimCoreState.STOPPING: long total = 0; if (ServerOptions.UsePerformanceLog) { foreach (SimulatorExecutionInfo sei in simModelInfo.simulationExecutionModel.simulators) { if (!simTimes.ContainsKey(sei.simulatorName)) { continue; } total += simTimes[sei.simulatorName]; } foreach (SimulatorExecutionInfo sei in simModelInfo.simulationExecutionModel.simulators) { if (!simTimes.ContainsKey(sei.simulatorName)) { continue; } StringBuilder b = new StringBuilder(); b.AppendFormat("SimCore Metric: Total time in: {0} was {1} seconds which is {2}% of total simulator time.", sei.simulatorName, simTimes[sei.simulatorName] / 10000000.0, (((double)simTimes[sei.simulatorName]) / total) * 100.0); PerformanceLog.Write(b.ToString()); } } state = SimCoreState.UNINITIALIZED; return; } } Thread.Sleep(updateFrequency / 10); } } catch (ThreadAbortException) { } catch (Exception exc) { MessageBox.Show("An error '" + exc.Message + "' has occurred in the Simulation Server.\nPlease email the C:\\DDDErrorLog.txt file to Aptima customer support with a description of what you were doing at the time of the error."); ErrorLog.Write(exc.ToString() + "\n"); throw new Exception(); } }
//[STAThread] static void Main(string[] args) { string hostname = args[0]; int port = Int32.Parse(args[1]); string simModelName = args[2]; SimulationModelReader smr = new SimulationModelReader(); SimulationModelInfo simModelInfo = smr.readModel(simModelName); SimulationEventDistributor dist = new SimulationEventDistributor(ref simModelInfo); SimulationEventDistributorClient cc = new SimulationEventDistributorClient(); dist.RegisterClient(ref cc); cc.Subscribe("ALL"); ScenarioReader scenarioReader = new ScenarioReader(); QueueManager queueManager = QueueManager.UniqueInstance(); c = new NetworkClient(); c.Connect(hostname, port); EventListener myEL = EventListener.UniqueInstance(c); int t = 0; int dt = simModelInfo.simulationExecutionModel.updateFrequency; SimulationEvent tick = SimulationEventFactory.BuildEvent(ref simModelInfo, "TimeTick"); ((IntegerValue)tick["Time"]).value = t; ConsoleKeyInfo cki; //Console.TreatControlCAsInput = false; //This explodes my code for some reason, but is in Gabe's client code and works fine, what does it do? Console.CancelKeyPress += new ConsoleCancelEventHandler(MyExitHandler); List <SimulationEvent> events = null; while (c.IsConnected() && queueManager.count() > 0) { //Read incoming events queue //if any events deal with a conditional event, remove the conditional //event from the conditional list, and place it onto the event queue //if a unit dies, remove them from the event queue and condition list while (c.IsConnected() && !(queueManager.eventsAtTime(t))) { events = c.GetEvents(); foreach (SimulationEvent e in events) { if (e.eventType == "MoveDone") { c.PutEvent(myEL.MoveDoneReceived(e, simModelInfo, tick)); } System.Console.WriteLine(SimulationEventFactory.XMLSerialize(e)); } ((IntegerValue)tick["Time"]).value = t; c.PutEvent(tick); //Console.WriteLine("Sending..."); //Console.WriteLine(SimulationEventFactory.XMLSerialize(tick)); Thread.Sleep(dt); t += dt; } if (c.IsConnected()) { QueueManager.sendEventsAtTime(t, c); ((IntegerValue)tick["Time"]).value = t; c.PutEvent(tick); //Console.WriteLine("Sending..."); //Console.WriteLine(SimulationEventFactory.XMLSerialize(e)); t += dt; } } while (c.IsConnected()) { ((IntegerValue)tick["Time"]).value = t; c.PutEvent(tick); //Console.WriteLine("Sending..."); //Console.WriteLine(SimulationEventFactory.XMLSerialize(tick)); Thread.Sleep(dt); t += dt; } }