public static bool Prefix(string saveFileName) { string fileName = saveFileName; string fileContent = System.IO.File.ReadAllText(GenFilePaths.FilePathForSavedGame(saveFileName)); if (SyncTickData.cliendID == 0) { PirateRPC.PirateRPC.SendInvocation(NetDemo.ns, u => { NetDemo.SetSFD(new NetDemo.SaveFileData() { tcontext = fileContent, partial_name = fileName + "_received" }); PirateRPC.PirateRPC.SendInvocation(u, uu => { NetDemo.LoadFromRemoteSFD(); }); }); LongEventHandler.QueueLongEvent(() => { for (; NetDemo.GetSFD() == null;) { } }, "Downloading savefile".Translate(), true, e => { RimLog.Error(e.ToString()); }); } return(false); }
public static void GenerateWorld() { ThingIDMakerPatch.stopID = true; ThinkTreeKeyAssigner.Reset(); foreach (var def in DefDatabase <ThinkTreeDef> .AllDefsListForReading) { ThinkTreeKeyAssigner.AssignKeys(def.thinkRoot, 0); } if (SyncTickData.cliendID == 0) { Find.WindowStack.Add(new Dialog_SaveFileList_Load()); } else { LongEventHandler.QueueLongEvent(() => { NetDemo.LoadFromRemoteSFD(); for (; NetDemo.GetSFD() == null;) { } }, "Downloading savefile".Translate(), true, e => { RimLog.Error(e.ToString()); }); } }
public override void Initialize() { inst = this; NetDemo.setupCallbacks(); (typeof(Rand).GetField("random", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null) as RandomNumberGenerator).seed = 0; HarmonyInstance harmony = HarmonyInst; RimLog.Message(System.Diagnostics.Process.GetCurrentProcess().StartInfo.Arguments); List <Type> designatorInheritees = new List <Type>(); InitBullshit(); foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) { foreach (Type t in a.GetTypes()) { if (!t.IsAbstract) { if (t.IsSubclassOf(typeof(Thing))) { MethodInfo targetmethod = AccessTools.Method(t, "GetGizmos"); HarmonyMethod postfix = new HarmonyMethod(typeof(CooperateRim.GenericGizmoPatch).GetMethod("Postfix")); harmony.Patch(targetmethod, null, postfix, null); } } } } if (System.Diagnostics.Process.GetCurrentProcess().StartInfo.Arguments.Contains("network_launch")) { //harmony.PatchAll(Assembly.GetExecutingAssembly()); } }
public static bool FlushSyncTickData(int tickNum) { /*if (new System.Collections.ICollection[] * { * singleton.jobsToSerialize, * singleton.jobPriorities, * singleton.designations, * singleton.designatorCellCalls, * singleton.designatorMultiCellCalls, * singleton.ForbiddenCallDataCall * }.Any(u => { return u.Count > 0; }))*/ { try { #if FILE_TRANSFER string s = @"D:\CoopReplays\_" + tickNum + "client_" + cliendID + ".xml"; //RimLog.Message("Written : " + s); BinaryFormatter ser = new BinaryFormatter(); var fs = System.IO.File.OpenWrite(s); SyncTickData buffered = singleton; singleton = new SyncTickData(); ser.Serialize(fs, buffered); fs.Flush(); fs.Close(); System.IO.File.WriteAllText(s + ".sync", ""); #else if (cliendID > -1) { singleton.randomToVerify = new int[] { Verse.Rand.Int }; var colonists = Find.ColonistBar.GetColonistsInOrder(); singleton.colonistJobsToVerify = colonists == null ? new List <string> { } : colonists.ConvertAll <string>(u => u.CurJobDef == null ? u.ThingID + "::" + "<null>" : u.ThingID + "::" + u.CurJobDef.defName); singleton.serializationServiceData = SerializationService.Flush(); BinaryFormatter ser = new BinaryFormatter() { TypeFormat = System.Runtime.Serialization.Formatters.FormatterTypeStyle.TypesWhenNeeded }; SyncTickData buffered = singleton; MemoryStream fs = new MemoryStream(); singleton = new SyncTickData(); //RimLog.Message("sending data for tick " + tickNum); NetDemo.PushStateToDirectory(cliendID, tickNum, buffered, 0); fs.Close(); return(true); } return(false); #endif } catch (Exception ee) { RimLog.Error(ee.ToString()); return(false); } } }
static Action <Stream> GetCallbackForSuccessfulPlayerJoin(int id, int roundLen) { return(k => { SyncTickData.SetClientID(id); NetDemo.ClientSetRoundLength(roundLen); hasClientID = true; LongEventHandler.QueueLongEvent(CooperateRimming.GenerateWorld, "Waiting to make a world", true, e => { NetDemo.Log(e.ToString()); }); }); }
public static void Main() { NetDemo.setupCallbacks(); Console.WriteLine("running remote directory host"); for (; ;) { Thread.Sleep(10); } }
public PTZExtend(NetDemo netDemo) { this.m_oNetDemo = netDemo; m_deviceInfoList = netDemo.getDeviceInfoList(); m_lpDevHandle = m_deviceInfoList[netDemo.getCurRealPanel().m_deviceIndex].m_lpDevHandle; m_iChannelID = netDemo.getCurRealPanel().m_channelID; m_curRealPlayPanel = netDemo.getCurRealPanel(); m_curSelectedTreeDeviceIndex = netDemo.m_CurSelectTreeNodeInfo.dwDeviceIndex; m_curSelectedTreeChannelIndex = netDemo.getChannelIndex(); InitializeComponent(); m_oPtzControl = new PTZControl(); }
public static void ServerHandlePlayerJoined(int id, Stream s) { if (id >= desiredPlayerCount) { Log("Client tried to connect, but server is full" + id); PirateRPC.PirateRPC.SendInvocation(s, u => { NetDemo.ForcePlayerDisconnect("Connection refused : server full"); }); } else { Log("sending client id " + id); int roundLen = ServerGetRoundLength(); Log("sending round len " + roundLen); PirateRPC.PirateRPC.SendInvocation(s, GetCallbackForSuccessfulPlayerJoin(id, roundLen)); } }
public override void DoWindowContents(Rect inRect) { int size = 52; Rect r = inRect; r.height = size - 1; r.width = 150; if (Widgets.ButtonText(r, "Connect to ")) { NetDemo.WaitForConnection(hostName); } r.y += size; Widgets.ButtonText(r, "MEANINGLESS BUTTON"); r.y += size; hostName = Widgets.TextArea(r, hostName); }
public static void WaitForConnection(string host) { tc = new TcpClient(); tc.Client.NoDelay = true; tc.Connect(host, 12345); ns = tc.GetStream(); hasClientID = false; forcedDisconnect = false; try { LongEventHandler.QueueLongEvent(() => { PirateRPC.PirateRPC.SendInvocation(ns, u => { int cid = SyncTickData.cliendID; Interlocked.Increment(ref SyncTickData.cliendID); NetDemo.ServerHandlePlayerJoined(cid, u); }); for (; !hasClientID && !forcedDisconnect;) { } }, "Waiting for server".Translate(), true, e => { RimLog.Error(e.ToString()); }); } catch (Exception ee) { log(ee.ToString()); } Thread t = new Thread(() => { for (; ;) { PirateRPC.PirateRPC.ReceiveInvocation(ns); } }); t.Start(); }
public static void ReceiveInvocation(Stream s) { BinaryReader br = new BinaryReader(s); string ss = br.ReadString(); byte[] b = Convert.FromBase64String(ss); NetDemo.log("RPC size : " + b.Length); MemoryStream ms = new MemoryStream(b); BinaryFormatter bf = new BinaryFormatter() { TypeFormat = System.Runtime.Serialization.Formatters.FormatterTypeStyle.TypesWhenNeeded }; { try { (bf.Deserialize(ms) as Modification).Apply(s); } catch (Exception ee) { NetDemo.log(ee.ToString()); } finally { } } }
public static bool Prefix(ref int ___ticksGameInt, ref TickManager __instance) { Rand.PushState(___ticksGameInt); getValuePatch.SendDiagDataToServer(); getValuePatch.diagData.Clear(); CooperateRimming.dumpRand = true; if (sw == null) { sw = new Stopwatch(); ACKSW = new Stopwatch(); sw.Start(); ACKSW.Start(); /*fix for newly loaded game*/ TickManagerPatch.nextCommunicationTick = Verse.Find.TickManager.TicksGame; TickManagerPatch.nextProcessionTick = Verse.Find.TickManager.TicksGame; if (!imInSync) { if (nextCommunicationTick == Verse.Find.TickManager.TicksGame) { imInSync = SyncTickData.FlushSyncTickData(nextProcessionTick + syncRoundLength * syncTickRoundOffset); } } if (cachedData == null) { return(false); } //for (; cachedData == null;) { } } shouldReallyTick = false; if (NetDemo.HasAllDataForFrame(Verse.Find.TickManager.TicksGame)) { NetDemo.Receive(); } if (sw.ElapsedMilliseconds > (1000 / ticksPerSecond) && !__instance.Paused) { sw.Reset(); sw.Start(); bool canNormallyTick = nextProcessionTick > Verse.Find.TickManager.TicksGame; //RimLog.Message("Tick " + ___ticksGameInt + " canNormallyTick " + canNormallyTick + "| comm " + nextCommunicationTick + " | " + nextProcessionTick); if (canNormallyTick) { //Utilities.RimLog.Message("normal tick at " + Verse.Find.TickManager.TicksGame + " nsync " + nextSyncTickValue); ulong i = 0; foreach (var act in RandContextCounter.replacement_seed) { act((ulong)___ticksGameInt + (i++)); } __instance.DoSingleTick(); } if (SyncTickData.cliendID > -1 && ACKSW.ElapsedMilliseconds > 50) { ACKSW.Reset(); ACKSW.Start(); //RimLog.Message("Sending state request for " + nextSyncTickValue); //NetDemo.SendStateRequest(nextSyncTickValue, SyncTickData.cliendID); } if (!imInSync) { if (nextCommunicationTick == Verse.Find.TickManager.TicksGame) { imInSync = SyncTickData.FlushSyncTickData(nextProcessionTick + syncRoundLength * syncTickRoundOffset); } } { if (nextProcessionTick == Verse.Find.TickManager.TicksGame) { #if FILE_TRANSFER bool allSyncDataAvailable = SyncTickData.tickFileNames(___ticksGameInt).All(u => System.IO.File.Exists(u + ".sync")); #else #endif //RimLog.Message("Frame " + ___ticksGameInt + " : " + " ::: " + allSyncDataAvailable + "[" + ___ticksGameInt + "] :: " + nextSyncTickValue + " [is synced : ] " + imInSync); Action onA = LocalDB.OnApply; if (cachedData != null) { IsSyncTick = true; //RimLog.Message("Synctick happened at " + ___ticksGameInt); SyncTickData.IsDeserializing = true; //JobTrackerPatch.FlushCData(); shouldReallyTick = true; streamholder.WriteLine("pre-deserialize tick at " + Verse.Find.TickManager.TicksGame, "tickstate"); streamholder.WriteLine("data applied at " + Verse.Find.TickManager.TicksGame, "tickstate"); //lock (LocalDB.OnApply) { Rand.PushState(___ticksGameInt); try { //RimLog.Message("applying at tick " + Verse.Find.TickManager.TicksGame); var cd = cachedData; cachedData = null; ulong i = 0; foreach (var act in RandContextCounter.replacement_seed) { act((ulong)___ticksGameInt + (i++)); } foreach (var a in cd) { a.AcceptResult(); } TickManagerPatch.SetSyncTickValue(nextProcessionTick + syncRoundLength); nextCommunicationTick += syncRoundLength; //Interlocked.Exchange(ref LocalDB.OnApply, null); //LocalDB.clientLocalStorage.ForEach(u => u.Value.AcceptResult()); //nextSyncTickValue = Verse.Find.TickManager.TicksGame + syncRoundLength; } catch (Exception ee) { RimLog.Message(ee.ToString()); } Rand.PopState(); LocalDB.clientLocalStorage.Clear(); } //SyncTickData.Apply(___ticksGameInt); //__instance.DoSingleTick(); imInSync = false; } } } } //ReferenceTranspilerMethod(ref ___ticksGameInt); Rand.PopState(); return(false); }
public static void TryDistributeData(int tickID) { List <SyncTickData> sdl = new List <SyncTickData>(); DateTime dt = DateTime.Now; if (HasFullData(tickID, NetDemo.desiredPlayerCount) /* && playerStateTable[clientID] < tickID*/) { NetDemo.log("dictionary lookup took " + (DateTime.Now - dt).TotalMilliseconds + ", update at " + DateTime.Now); sdl = new List <SyncTickData>(data[tickID]); int? randomV = null; List <string> jobsToVerify = null; desyncReason desyncReason = desyncReason.None; foreach (var __ns in NetDemo.allClients) { foreach (var a in sdl) { { if (!randomV.HasValue) { randomV = a.randomToVerify[0]; } else { NetDemo.log(randomV.Value + " == " + a.randomToVerify[0]); if (randomV.Value != a.randomToVerify[0]) { desyncReason = desyncReason.Rng; } } if (jobsToVerify == null) { jobsToVerify = a.colonistJobsToVerify; } else { if (jobsToVerify.Count != a.colonistJobsToVerify.Count || !jobsToVerify.All(__data => a.colonistJobsToVerify.Any(uu => uu.SequenceEqual(__data)))) { if (jobsToVerify.Count != a.colonistJobsToVerify.Count) { NetDemo.log("JOBS COUNT IS DIFFERENT!" + jobsToVerify.Count + " != " + a.colonistJobsToVerify.Count); } else { string ds = ""; for (int i = 0; i < jobsToVerify.Count; i++) { ds += ("JOBSDUMP : " + jobsToVerify[i] + " != " + a.colonistJobsToVerify[i]) + "\r\n"; } NetDemo.log(ds); } desyncReason = desyncReason.Jobs; //throw new Exception("Session jobs desynced!"); } } } a.DebugLog(); } DateTime _dt = DateTime.Now; switch (desyncReason) { case desyncReason.None: PirateRPC.PirateRPC.SendInvocation(__ns, GetCallback(sdl.ToArray())); break; case desyncReason.Jobs: PirateRPC.PirateRPC.SendInvocation(__ns, uuu => { Messages.Message("Session desynchronized! Reason : different colonist jobs", RimWorld.MessageTypeDefOf.ThreatBig, true); getValuePatch.DumpFramelistData(uuu); }); break; case desyncReason.Rng: NetDemo.log("Session desynchronized! Reason : different control random numbers"); PirateRPC.PirateRPC.SendInvocation(__ns, uuu => { Messages.Message("Session desynchronized! Reason : different control random numbers", RimWorld.MessageTypeDefOf.ThreatBig, true); getValuePatch.DumpFramelistData(uuu); }); break; } NetDemo.log("invocation took " + (DateTime.Now - dt).TotalMilliseconds); } //data.Remove(tickID); } }
public Discovery(NetDemo oNetDemo) { this.m_oNetDemo = oNetDemo; InitializeComponent(); }
public AddDevice(NetDemo oNetDemo) { this.m_oNetDemo = oNetDemo; InitializeComponent(); }
//cycle monitor public CycleMonitor(NetDemo oNetDemo) { InitializeComponent(); m_oNetDemo = oNetDemo; int k = 0; for (int i = 0; i < m_oNetDemo.getDeviceInfoList().Count; i++) { //int correctValue = 0; for (int j = 0; j < m_oNetDemo.getDeviceInfoList()[i].m_channelInfoList.Count; j++) { if (m_oNetDemo.getDeviceInfoList()[i].m_channelInfoList[j].m_devVideoChlInfo.enStatus == (int)NETDEV_CHANNEL_STATUS_E.NETDEV_CHL_STATUS_ONLINE) { if (m_oNetDemo.m_cycleMonitorInfo != null) { if (k < m_oNetDemo.m_cycleMonitorInfo.monitorCount) { ListViewItem oListViewItem = null; if (m_oNetDemo.m_cycleMonitorInfo.channelInfoList[k].channelID == m_oNetDemo.getDeviceInfoList()[i].m_channelInfoList[j].m_devVideoChlInfo.dwChannelID && m_oNetDemo.m_cycleMonitorInfo.channelInfoList[k].devhandle == m_oNetDemo.getDeviceInfoList()[i].m_lpDevHandle) { oListViewItem = new ListViewItem(m_oNetDemo.getDeviceInfoList()[i].m_ip); oListViewItem.SubItems.Add(Convert.ToString(m_oNetDemo.getDeviceInfoList()[i].m_channelInfoList[j].m_devVideoChlInfo.dwChannelID)); this.monitorListView.Items.Add(oListViewItem); oListViewItem.EnsureVisible(); k++; } else { oListViewItem = new ListViewItem(m_oNetDemo.getDeviceInfoList()[i].m_ip); oListViewItem.SubItems.Add(Convert.ToString(m_oNetDemo.getDeviceInfoList()[i].m_channelInfoList[j].m_devVideoChlInfo.dwChannelID)); this.unmonitorListView.Items.Add(oListViewItem); oListViewItem.EnsureVisible(); } } else { ListViewItem oListViewItem = new ListViewItem(m_oNetDemo.getDeviceInfoList()[i].m_ip); oListViewItem.SubItems.Add(Convert.ToString(m_oNetDemo.getDeviceInfoList()[i].m_channelInfoList[j].m_devVideoChlInfo.dwChannelID)); this.unmonitorListView.Items.Add(oListViewItem); oListViewItem.EnsureVisible(); } } else { ListViewItem oListViewItem = new ListViewItem(m_oNetDemo.getDeviceInfoList()[i].m_ip); oListViewItem.SubItems.Add(Convert.ToString(m_oNetDemo.getDeviceInfoList()[i].m_channelInfoList[j].m_devVideoChlInfo.dwChannelID)); this.unmonitorListView.Items.Add(oListViewItem); oListViewItem.EnsureVisible(); } } } } if (m_oNetDemo.m_cycleMonitorInfo != null) { this.cycleMonitorTypeCobBox.SelectedIndex = (int)m_oNetDemo.m_cycleMonitorInfo.monitorType; this.cycleMonitorWinNoCobBox.SelectedIndex = m_oNetDemo.m_cycleMonitorInfo.panelNo; this.monitorIntervalText.Text = Convert.ToString(m_oNetDemo.m_cycleMonitorInfo.intervalTime); this.startMonitorBtn.Enabled = false; this.addAllMonitorBtn.Enabled = false; this.addOneMonitorBtn.Enabled = false; this.delAllMonitorBtn.Enabled = false; this.delOneMonitorBtn.Enabled = false; } else { this.stopMonitorBtn.Enabled = false; } }
public Config(NetDemo oNetDemo) { m_oNetDemo = oNetDemo; m_deviceInfoList = oNetDemo.getDeviceInfoList(); }
public Preset(NetDemo netDemo) { InitializeComponent(); this.m_oNetDemo = netDemo; }
static void Main(string[] args) { int listenPort = 12345;// int.Parse(System.Configuration.ConfigurationManager.AppSettings["listen_port"]); int playercount = 2; bool useNatTraversal = true; try { CooperateRim.TickManagerPatch.syncRoundLength = int.Parse(System.Configuration.ConfigurationManager.AppSettings["round_length_ticks"]); playercount = int.Parse(System.Configuration.ConfigurationManager.AppSettings["player_count"]); useNatTraversal = bool.Parse(System.Configuration.ConfigurationManager.AppSettings["sockopt_nat_traversal"]); NetDemo.SetDesiredPlayerCount(playercount); } catch (Exception ee) { Console.WriteLine(ee.ToString()); Console.WriteLine("Error reading config file. Press any key to exit."); Console.ReadKey(); return; } //UPnP.NAT.Discover(); //UPnP.NAT.ForwardPort(12345, ProtocolType.Tcp, "MyApp (TCP)"); //CRand.set_state(900 << 32); int workers; int completions; ThreadPool.GetMinThreads(out workers, out completions); bool res = ThreadPool.SetMinThreads(4, 4); TcpListener lst = new TcpListener(IPAddress.Any, listenPort); lst.Server.NoDelay = true; if (useNatTraversal) { lst.AllowNatTraversal(useNatTraversal); } lst.Server.ExclusiveAddressUse = true; lst.Start(); AsyncCallback acceptor = null; Console.WriteLine("Player count set to " + playercount); Console.WriteLine("Listen port is " + listenPort); AssemblyName updatedAssemblyName = AssemblyName.GetAssemblyName("CooperateRim.dll"); Console.WriteLine("RimAlong mod version is " + updatedAssemblyName.Version); Console.WriteLine("RimAlong server version 0.0.0.3, codename \"crubmle tree\", ready to rumble!"); CooperateRim.SyncTickData.cliendID = 0; lst.BeginAcceptTcpClient(acceptor = u => { Console.WriteLine("new client"); TcpClient tcc = (u.AsyncState as TcpListener).EndAcceptTcpClient(u); NetworkStream ns = tcc.GetStream(); int clid = CooperateRim.SyncTickData.cliendID; (u.AsyncState as TcpListener).BeginAcceptTcpClient(acceptor, u.AsyncState); if (clid < NetDemo.desiredPlayerCount) { NetDemo.allClients.AddLast(ns); for (; tcc.Connected;) { Thread.Sleep(10); if (ns.DataAvailable) { PirateRPC.PirateRPC.ReceiveInvocation(ns); } } ; } else { for (; !ns.DataAvailable;) { Thread.Sleep(10); if (ns.DataAvailable) { PirateRPC.PirateRPC.ReceiveInvocation(ns); break; } } ; } Console.WriteLine("client lost"); }, lst); for (; ;) { Thread.Sleep(10); } }