/// <summary> /// Push clients /// </summary> public void PushClients() { Trace.TraceInformation("{0}: -- Starting PUSH of patients to CR --", this.m_context.JobId); List <Int32> unsyncedChildren = new List <int>(); // Get the last sync to be completed using (SyncData dao = new SyncData()) { // Last modified filter var lastSync = dao.GetLastSync(); DateTime?lastModifiedFilter = lastSync == null ? null : (DateTime?)lastSync.StartTime; foreach (var id in dao.GetUnsyncedChildrenId()) { this.m_waitThread.QueueUserWorkItem(this.PushPatientsAsync, id); } } // Wait for the worker threads to finish this.m_waitThread.WaitOne(); if (this.m_errorState) { throw new InvalidOperationException("Sync resulted in error state"); } }
private static void WorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { SyncData.SetSunc(false); new ClassPrintCheck(RepositoryCheck.DocumentProductCheck, false); RepositoryCheck.DocumentProductCheck = null; CassieService.OpenProductsCheck(); Pro = null; Ndevis = -1; Nfact = -1; Check = null; Devis = false; ModePro = false; RepositoryDiscount.RestoreDiscount(); CheckService.DiscountCalc(); FunctionsService.WriteTotal(); var de = ClassEtcFun.FindWindow("_W_Message"); if (de != null) { de.Close(); } var mw = ClassEtcFun.FindWindow("MainWindow_"); if (mw != null) { mw.IsEnabled = true; } }
/// <summary> /// Convert bytes to object and get a list of the field values /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data"> Byte data </param> /// <returns></returns> public static List <object> ConvertByteToObject <T>(List <byte> data) { List <object> objectList = new List <object>(); PropertyInfo[] fields = typeof(T).GetProperties(); int currentIndex = 0; foreach (PropertyInfo field in fields) { SyncData meta = (SyncData)field.GetCustomAttribute(typeof(SyncData)); if (meta != null) { // Check the type and convert it switch (Type.GetTypeCode(field.PropertyType)) { case TypeCode.Boolean: objectList.Add(ConvertByteToBool(ref data, ref currentIndex)); break; case TypeCode.Int32: objectList.Add(ConvertByteToInt(ref data, ref currentIndex)); break; case TypeCode.UInt16: objectList.Add(ConvertByteToUShort(ref data, ref currentIndex)); break; case TypeCode.Single: objectList.Add(ConvertByteToFloat(ref data, ref currentIndex)); break; case TypeCode.String: if (meta.GetDataType() == SyncData.TypeOfData.ip) { objectList.Add(ConvertByteToIp(ref data, ref currentIndex)); } else { objectList.Add(ConvertByteToString(ref data, ref currentIndex)); } break; case TypeCode.Byte: currentIndex++; objectList.Add(data[currentIndex - 1]); break; default: switch (field.PropertyType.Name) { case nameof(Vector2): objectList.Add(ConvertByteToVector2(ref data, ref currentIndex)); break; } break; } } } return(objectList); }
public void RecvNetSync(ProtocolBase protocol) { //获取数值 ProtocolBytes proto = (ProtocolBytes)protocol; int start = 0; string protoName = proto.GetString(start, ref start); if (!protoName.Equals(sync_id + "NetSyncController")) { return; } string player_id = proto.GetString(start, ref start); if (player_id == GameMgr.instance.id)//丢弃自己发的信息 { return; } string _sync_id = proto.GetString(start, ref start); if (_sync_id != sync_id)//不是该物体要同步信息 { return; } //sync_scripts SyncData data = proto.GetSyncData(start, ref start); for (int i = 0; i < sync_scripts.Count; i++) { // SyncData data = proto.GetSyncData(start, ref start); Component temp = sync_scripts[i]; (temp as NetSyncInterface).RecvData(data); } }
void SendNetSync() { if (!GameMgr.instance)//GameMgr.instance没被初始化,则此时是离线状态 { return; } //消息 ProtocolBytes proto = new ProtocolBytes(); proto.AddString("BroadCast"); proto.AddString(sync_id + "NetSyncController"); //sync_id proto.AddString(sync_id); //sync_scripts for (int i = 0; i < sync_scripts.Count; i++) { //移除禁用脚本 if (((MonoBehaviour)sync_scripts[i]).enabled == false) { sync_scripts.Remove(sync_scripts[i]); } Component temp = sync_scripts[i]; SyncData data = (temp as NetSyncInterface).SendData(); //加入空检测 if (data == null) { continue; } proto.AddSyncData(data); } NetMgr.srvConn.Send(proto); }
public void SendSyncData(Player player) { SyncData data = new SyncData(); data.positions = new Vector2Int[players.Count]; data.scores = new int[players.Count]; PlayerControls[] sortedPlayers = players.Where(p => !p.isDead).OrderBy(p => p.photonView.Owner.ActorNumber).ToArray(); for (int i = 0; i < sortedPlayers.Length; i++) { data.positions[i] = sortedPlayers[i].gamePosition; data.scores[i] = sortedPlayers[i].score; } data.mapData = cells; RaiseEventOptions options = new RaiseEventOptions { TargetActors = new[] { player.ActorNumber } }; SendOptions sendOptions = new SendOptions { Reliability = true }; PhotonNetwork.RaiseEvent(43, data, options, sendOptions); }
public static void ReputationCheck(SyncData receivedData) { var stringSplit = receivedData.ChatMessage.Split('.'); if (stringSplit.Length != 4) { return; } var npcFaction = MyAPIGateway.Session.Factions.TryGetFactionByTag(stringSplit[3]); if (npcFaction == null) { return; } var myFaction = MyAPIGateway.Session.Factions.TryGetPlayerFaction(receivedData.PlayerId); int rep = 0; if (myFaction != null) { rep = MyAPIGateway.Session.Factions.GetReputationBetweenFactions(myFaction.FactionId, npcFaction.FactionId); } else { rep = MyAPIGateway.Session.Factions.GetReputationBetweenPlayerAndFaction(receivedData.PlayerId, npcFaction.FactionId); } MyVisualScriptLogicProvider.ShowNotification("Reputation To Faction: " + rep.ToString(), 5000, "White", receivedData.PlayerId); }
public void ProcessReceivedData(byte[] formatDataBytes) { SyncData data = new SyncData(); int srcOffset = 0; int pathByteLength = BitConverter.ToInt32(formatDataBytes, 0); srcOffset += 4; byte[] relatePathBytes = new byte[pathByteLength]; Buffer.BlockCopy(formatDataBytes, srcOffset, relatePathBytes, 0, pathByteLength); string relatePath = System.Text.Encoding.Default.GetString(relatePathBytes); srcOffset += pathByteLength; int dataBytesLength = BitConverter.ToInt32(formatDataBytes, srcOffset); srcOffset += 4; byte[] dataBytes = new byte[dataBytesLength]; Buffer.BlockCopy(formatDataBytes, srcOffset, dataBytes, 0, dataBytesLength); data.RelativePath = relatePath; data.Data = dataBytes; if (data.RelativePath == "over") { GameEvents.TriggerCheckEvent(eGameEventTypes.DataReceiverSyncOver); } else { SaveData(data); } }
private void SyncWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { SyncData data = (e.Result as SyncData); StringBuilder debugDump = new StringBuilder(); if (Sharlayan.MemoryHandler.Instance.IsAttached) { if (Sharlayan.Reader.CanGetActors()) { ActorResult actors = Sharlayan.Reader.GetActors(); foreach (KeyValuePair <uint, long> kvp in data.idTimestamp) { if (actors.CurrentPCs.ContainsKey(kvp.Key)) { ActorItem item = actors.CurrentPCs[kvp.Key]; debugDump.AppendLine(string.Format("{0} MS {1}", item.Name, kvp.Value)); } } } } onMemoryCheck.Invoke(this, false); //MessageBox.Show(this.Parent, debugDump.ToString()); Console.WriteLine(debugDump.ToString()); }
public void SendSyncData(Player player) //передает новому игроку текущее состояние на поле { SyncData data = new SyncData(); data.positions = new Vector2Int[players.Count]; data.scores = new int[players.Count]; PlayerControls[] sortedplayers = players.Where(p => !p.isDead).OrderBy(p => p.photonView.Owner.ActorNumber).ToArray(); for (int i = 0; i < sortedplayers.Length; i++) { data.positions[i] = sortedplayers[i].GamePosition; data.scores[i] = sortedplayers[i].Score; } data.mapData = new BitArray(height * width); for (int i = 0; i < cells.GetLength(0); i++) { for (int j = 0; j < cells.GetLength(1); j++) { data.mapData.Set(i + j * cells.GetLength(0), cells[i, j].activeSelf); } } RaiseEventOptions options = new RaiseEventOptions { TargetActors = new[] { player.ActorNumber } }; SendOptions sendOptions = new SendOptions { Reliability = true }; PhotonNetwork.RaiseEvent(43, data, options, sendOptions); }
public static void MESChatCommand(string messageText, ref bool sendToOthers) { var thisPlayer = MyAPIGateway.Session.LocalHumanPlayer; bool isAdmin = false; if (thisPlayer == null) { return; } if (thisPlayer.PromoteLevel == MyPromoteLevel.Admin || thisPlayer.PromoteLevel == MyPromoteLevel.Owner) { isAdmin = true; } if (isAdmin == false) { MyVisualScriptLogicProvider.ShowNotification("Access Denied. Spawner Chat Commands Only Available To Admin Players.", 5000, "Red", thisPlayer.IdentityId); return; } if (messageText.StartsWith("/MES.") == true) { sendToOthers = false; var syncData = new SyncData(); syncData.Instruction = "MESChatMsg"; syncData.PlayerId = thisPlayer.IdentityId; syncData.SteamUserId = thisPlayer.SteamUserId; syncData.ChatMessage = messageText; syncData.PlayerPosition = thisPlayer.GetPosition(); var sendData = MyAPIGateway.Utilities.SerializeToBinary <SyncData>(syncData); var sendMsg = MyAPIGateway.Multiplayer.SendMessageToServer(8877, sendData); } }
private IEnumerator OnSyncDataReceived(SyncData data) { PlayerControls[] sortedplayers; do { yield return(null); sortedplayers = players. Where(p => !p.isDead). Where(p => !p.photonView.IsMine). OrderBy(p => p.photonView.Owner.ActorNumber). ToArray(); } while (sortedplayers.Length != data.positions.Length); for (int i = 0; i < sortedplayers.Length; i++) { sortedplayers[i].GamePosition = data.positions[i]; sortedplayers[i].Score = data.scores[i]; sortedplayers[i].transform.position = (Vector2)sortedplayers[i].GamePosition; } for (int i = 0; i < cells.GetLength(0); i++) { for (int j = 0; j < cells.GetLength(1); j++) { bool cellActive = data.mapData.Get(i + j * cells.GetLength(0)); if (!cellActive) { cells[i, j].SetActive(false); } } } }
public static void open_form_sinh_vien_call(CallInfor ip_call_info) { try { SinhVien v_obj_sinhvien = new SinhVien(); SyncData v_ws_scm = new SyncData(); string v_str_search = HelpUtils.gen_string_call_scm_get_sinh_vien_ws(ip_call_info.mobile_phone, "", "", "", "10", "TOPICA"); DataSet v_ds = v_ws_scm.TOS_search_info_hoc_vien(v_str_search); v_obj_sinhvien.get_sinh_vien_by_ds(v_ds); // // Nếu ko tìm được học viên thì Số điện thoại sẽ được bảo toàn, tránh bị Null // if (v_obj_sinhvien.Dien_thoai == null) { v_obj_sinhvien.Dien_thoai = ip_call_info.mobile_phone; } //f200_sinh_vien_goi_den v_f200 = new f200_sinh_vien_goi_den(); // v_f200.display(v_obj_sinhvien, ip_call_info.call_id); string v_str_thong_tin_goi_vao = ""; if (v_obj_sinhvien.Ho_ten != "") { v_str_thong_tin_goi_vao += "Họ tên: " + v_obj_sinhvien.Ho_ten + "; "; } if (v_obj_sinhvien.Dien_thoai != "") { v_str_thong_tin_goi_vao += "ĐT: " + v_obj_sinhvien.Dien_thoai; } // HelpUtils.ghi_log_he_thong(LOG_TRUY_CAP.HOC_VIEN_GOI_DEN, v_str_thong_tin_goi_vao, "Gọi vào", f002_main_form.m_str_stationId); } catch (Exception v_e) { CSystemLog_100.ExceptionHandle(v_e); } }
public void ApplySync(ServiceType serviceType, SyncData syncData) { Dictionary <ulong, Dictionary <uint, Action <byte[]> > > serviceDict; if (mTargetBindings.TryGetValue((int)serviceType, out serviceDict)) { var __list4 = syncData.Datas; var __listCount4 = __list4.Count; for (int __i4 = 0; __i4 < __listCount4; ++__i4) { var data = __list4[__i4]; { Dictionary <uint, Action <byte[]> > dict; if (serviceDict.TryGetValue(data.CharacterId, out dict)) { Action <byte[]> action; if (dict.TryGetValue(data.Id, out action)) { action(data.Data); } } } } } }
static SqlPreCommand Schema_Synchronizing(Replacements replacements) { bool any = Database.Query <EntityHelpEntity>().Any() || Database.Query <OperationHelpEntity>().Any() || Database.Query <QueryHelpEntity>().Any() || Database.Query <NamespaceHelpEntity>().Any() || Database.Query <AppendixHelpEntity>().Any(); if (!(any && replacements.Interactive && SafeConsole.Ask("Synchronize Help content?"))) { return(null); } SyncData data = new SyncData { Namespaces = AllTypes().Select(a => a.Namespace).ToHashSet(), Appendices = Database.Query <AppendixHelpEntity>().Select(a => a.UniqueName).ToHashSet(), StringDistance = new StringDistance() }; var ns = SynchronizeNamespace(replacements, data); var appendix = SynchronizeAppendix(replacements, data); var types = SynchronizeTypes(replacements, data); var queries = SynchronizeQueries(replacements, data); var operations = SynchronizeOperations(replacements, data); return(SqlPreCommand.Combine(Spacing.Double, ns, appendix, types, queries)); }
public static bool TryParse(string s, out IData result) { result = null; if (string.IsNullOrEmpty(s)) { return(false); } var items = s.Split(' '); if (items.Length != 2) { return(false); } DateTime syncTime; if (!DateTime.TryParseExact(items[0], Constants.SyncFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out syncTime)) { return(false); } result = new SyncData() { Timestamp = syncTime, Version = items[1] }; return(true); }
public static void SaveToDb(string path, XDocument document) { var fileName = Path.GetFileName(path); if (SyncData.IsConnect) { var worker = new BackgroundWorker(); worker.DoWork += (s, e) => { SyncData.SetSunc(true); var xmlFile = GetFromDb(fileName, Config.User); if (xmlFile == null) { InsertToDb(new XmlFile(Guid.NewGuid(), fileName, DateTime.Now, true, Config.User, document.ToString(), Config.IdEstablishment)); } else { xmlFile.Upd = true; xmlFile.FileName = fileName; xmlFile.Date = DateTime.Now; xmlFile.Data = document.ToString(); UpdateFromDb(xmlFile); } }; worker.RunWorkerCompleted += (s, e) => SyncData.SetSunc(false); worker.RunWorkerAsync(); } }
private async Task UpdateDatabase(SyncData syncData) { using (var db = new TodoistContext()) { await _userRepository.SaveUser(syncData.User); var items = syncData.Items; foreach (var dbItem in items) { if (db.Items.Any(i => i.Id == dbItem.Id)) { if (string.IsNullOrWhiteSpace(dbItem.Content)) { db.Items.Remove(dbItem); } else { db.Items.Update(dbItem); } } else { db.Items.Add(dbItem); } } await db.SaveChangesAsync(); } }
public bool UpdateSyncData(string id, SyncData syncData) { _logService.Debug(string.Format("<-{0}->:ThreadID={1}", "UpdateSyncData", System.Threading.Thread.GetDomainID().ToString())); if (ContainsScreen(id)) { SyncData configSyncData = null; try { configSyncData = _syncInfoTable[id].SyncDatas.FirstOrDefault(d => d.SyncType == syncData.SyncType); } catch (Exception ex) { _logService.Error(string.Format("ExistCatch:<-{0}->:{1},\nThreadID={2}", "UpdateSyncData", "_syncInfoTable[id].SyncDatas.FirstOrDefault error,info:" + ex.ToString(), System.Threading.Thread.GetDomainID().ToString())); return(false); } if (configSyncData == null) { _logService.Error(string.Format("<-{0}->:{1}", "UpdateSyncData", "无指定的更新项.")); return(false); } _syncInfoTable[id].SyncDatas.Remove(configSyncData); _syncInfoTable[id].SyncDatas.Add(syncData); return(true); } else { _logService.Error(string.Format("<-{0}->:{1}", "UpdateSyncData", "无指定的更新项.")); return(false); } }
/// <summary> /// Create a synchronization context /// </summary> public static SynchronizationContext CreateContext() { try { Trace.TraceInformation("Create Synchrnoization Job Data"); // Register using (var dao = new SyncData()) { // Sync context var retVal = new SynchronizationContext() { JobId = dao.CreateSynchronizationJob(Process.GetCurrentProcess().Id), StartTime = DateTime.Now }; Trace.TraceInformation("DB: Registered sync job id #{0}", retVal.JobId); dao.Commit(); return(retVal); } } catch (Exception e) { Trace.TraceError(e.ToString()); return(null); } finally { } }
public void RemoveSyncData(string id, SyncData syncData) { if (ContainsScreen(id)) { _syncInfoTable[id].SyncDatas.Remove(syncData); } }
public void AddSyncData(string id, SyncData syncData) { if (ContainsScreen(id)) { var data = _syncInfoTable[id].SyncDatas.Find(s => s.SyncType == syncData.SyncType); if (data == null) { _syncInfoTable[id].SyncDatas.Add(syncData); } else { _logService.Debug(string.Format("<-{0}->:ThreadID={1}", "AddSyncData", System.Threading.Thread.GetDomainID().ToString())); UpdateSyncData(id, syncData); } } else { var syncInformation = new SyncInformation(); syncInformation.Sn = id; syncInformation.SyncDatas = new List <SyncData>() { syncData }; _syncInfoTable.Add(id, syncInformation); } }
public void RecvData(SyncData data) { int notnull = (int)data.Get(typeof(int)); //时间 delta = Time.time - lastRecvInfoTime; foreach (var ai in AI_List) { string id = data.GetString(); if (AI_List.ContainsKey(id)) { //无预测同步 //AI_List[id].transform.position = (Vector3)data.Get(typeof(Vector3)); //AI_List[id].transform.eulerAngles = (Vector3)data.Get(typeof(Vector3)); //预测同步 Vector3 nPosition = (Vector3)data.Get(typeof(Vector3)); Vector3 nRotation = (Vector3)data.Get(typeof(Vector3)); //Debug.Log("RecvData" + id); NetForecastInfo(id, nPosition, nRotation); } else { data.Get(typeof(Vector3)); data.Get(typeof(Vector3)); } } lastRecvInfoTime = Time.time; }
public void Send(SyncData syncData) { if (syncData != null) { sendStack.Add(syncData); } }
private IEnumerator OnSyncDataRecived(SyncData data) { PlayerControls[] sortedPlayers; do { yield return(null); sortedPlayers = players.Where(p => !p.isDead).Where(p => !p.photonView.IsMine).OrderBy(p => p.photonView.Owner.ActorNumber).ToArray(); } while (sortedPlayers.Length != data.positions.Length); for (int i = 0; i < sortedPlayers.Length; i++) { sortedPlayers[i].gamePosition = data.positions[i]; sortedPlayers[i].score = data.scores[i]; sortedPlayers[i].transform.position = (Vector2)sortedPlayers[i].gamePosition; } for (int x = 0; x < cells.GetLength(0); x++) { for (int y = 0; y < cells.GetLength(1); y++) { bool cellActive = data.mapData[x, y]; if (!cellActive) { SetCell(new Vector2Int(x, y), false); } } } }
/// <summary> /// Returns if properties can be sent to clients. /// </summary> /// <param name="data"></param> /// <param name="useReliable"></param> /// <returns></returns> private bool CanSendProperties(SyncData data, ref bool useReliable) { bool dataMatches = SyncDataMatchesObject(data); //Send if data doesn't match. if (!dataMatches) { /* Unset ReliableSent so that it will fire * once object has settled, assuming not using a reliable * transport. */ _reliableSent = false; return(true); } //If data matches. else { //If using unreliable, but reliable isn't sent yet. if (!_reliable && !_reliableSent) { useReliable = true; _reliableSent = true; return(true); } //Either using reliable or reliable already sent. else { return(false); } } }
public SyncData SendData() { SyncData data = new SyncData(); data.Add(1); return(data); }
static SqlPreCommand?SynchronizeNamespace(Replacements replacements, SyncData data) { var entities = Database.Query <NamespaceHelpEntity>().ToList(); if (entities.IsEmpty()) { return(null); } var current = entities.Select(a => a.Name).ToHashSet(); replacements.AskForReplacements(current, data.Namespaces, "namespaces"); var table = Schema.Current.Table <NamespaceHelpEntity>(); using (replacements.WithReplacedDatabaseName()) return(entities.Select(e => { e.Name = replacements.TryGetC("namespaces")?.TryGetC(e.Name) ?? e.Name; if (!data.Namespaces.Contains(e.Name)) { return table.DeleteSqlSync(e, n => n.Name == e.Name); } e.Description = SynchronizeContent(e.Description, replacements, data); return table.UpdateSqlSync(e, n => n.Name == e.Name); }).Combine(Spacing.Simple)); }
public SyncEvent(object sender, SyncData data, ServiceType type) { Type = EventType.Sync; Sender = sender; SyncData = data; ServiceType = type; }
private static void AssignActionBySZRule(SyncData syncData, SyncRule syncRule) { if (syncData.SCS.HasFlag(SyncConflictState.BiggerInSource)) { if (syncRule.CompareOperationArgument.Contains(">")) { if (syncRule.Action == "Dlt") { syncData.SAS = SyncActionState.Delete; syncData.WasTriggeredBySyncRule = true; } else if (syncRule.Action == "Skp") { syncData.SAS = SyncActionState.Skip; syncData.WasTriggeredBySyncRule = true; } else if (syncRule.Action == "Shr") { syncData.SAS = SyncActionState.Share; syncData.SD = SyncDirection.Source; syncData.WasTriggeredBySyncRule = true; } else if (syncRule.Action == "Cpy") { syncData.SAS = SyncActionState.Copy; syncData.SD = SyncDirection.Source; syncData.WasTriggeredBySyncRule = true; } } } else if (syncData.SCS.HasFlag(SyncConflictState.SmallerInSource)) { if (syncRule.CompareOperationArgument.Contains("<")) { if (syncRule.Action == "Dlt") { syncData.SAS = SyncActionState.Delete; syncData.WasTriggeredBySyncRule = true; } else if (syncRule.Action == "Skp") { syncData.SAS = SyncActionState.Skip; syncData.WasTriggeredBySyncRule = true; } else if (syncRule.Action == "Shr") { syncData.SAS = SyncActionState.Share; syncData.SD = SyncDirection.Target; syncData.WasTriggeredBySyncRule = true; } else if (syncRule.Action == "Cpy") { syncData.SAS = SyncActionState.Copy; syncData.SD = SyncDirection.Target; syncData.WasTriggeredBySyncRule = true; } } } }
public void SetSyncData(Vector3[] data, Quaternion[] rotation, float[] time, float syncTime, int id) { if (data.Length == 0) return; for (int i = 0; i < data.Length; i++) syncData.Enqueue(new SyncData(){ position = data[i], rotation = rotation[i], time = time[i] }); if (lastSyncData.time == -1) { lastSyncData = syncData.Dequeue(); this.enabled = true; rb.isKinematic = false; rb.useGravity = false; rb.constraints = RigidbodyConstraints.FreezeRotation; if (syncData.Count == 0) return; } timeSinceLastDataSync = 0; estimatedTimeUntilNextSync = syncTime * 1.2f; originalNeededTime = time[time.Length-1] - Mathf.Lerp(lastSyncData.time, syncData.Peek().time, currentSyncLerpAlpha); timePerSyncPoint = estimatedTimeUntilNextSync / originalNeededTime * (syncData.Peek().time - lastSyncData.time); if (id <= lastID) Debug.LogError("Data out of order!"); lastID = id; }
private SyncData GetMatch(SyncDatas servicedatas, SyncData local) { return servicedatas.Find(service => { if (service.FriendlyName == local.FriendlyName && service.IntHash == local.IntHash) return true; else return false; }); }
internal override void BuildClockSubTreeFromTimeline( Timeline timeline, bool hasControllableRoot) { // This is not currently necessary //base.BuildClockSubTreeFromTimeline(timeline); // Only TimelineGroup has children TimelineGroup timelineGroup = timeline as TimelineGroup; // Only a TimelineGroup should have allocated a ClockGroup. Debug.Assert(timelineGroup != null); // Create a clock for each of the children of the timeline TimelineCollection timelineChildren = timelineGroup.Children; if (timelineChildren != null && timelineChildren.Count > 0) { Clock childClock; // Create a collection for the children of the clock _children = new List<Clock>(); // Create clocks for the children for (int index = 0; index < timelineChildren.Count; index++) { childClock = AllocateClock(timelineChildren[index], hasControllableRoot); childClock._parent = this; // We connect the child to the subtree before calling BuildClockSubtreeFromTimeline childClock.BuildClockSubTreeFromTimeline(timelineChildren[index], hasControllableRoot); _children.Add(childClock); childClock._childIndex = index; } // If we have SlipBehavior, check if we have any childen with which to slip. if (_timeline is ParallelTimeline && ((ParallelTimeline)_timeline).SlipBehavior == SlipBehavior.Slip) { // Verify that we only use SlipBehavior in supported scenarios if (!IsRoot || (_timeline.RepeatBehavior.HasDuration) || (_timeline.AutoReverse == true) || (_timeline.AccelerationRatio > 0) || (_timeline.DecelerationRatio > 0)) { throw new NotSupportedException(SR.Get(SRID.Timing_SlipBehavior_SlipOnlyOnSimpleTimelines)); } for (int index = 0; index < _children.Count; index++) { Clock child = _children[index]; if (child.CanSlip) { Duration duration = child.ResolvedDuration; // A [....] clock with duration of zero or no begin time has no effect, so do skip it if ((!duration.HasTimeSpan || duration.TimeSpan > TimeSpan.Zero) && child._timeline.BeginTime.HasValue) { _syncData = new SyncData(child); child._syncData = null; // The child will no longer self-[....] } break; // We only want the first child with CanSlip } } } } }
void UpdateSyncPos() { if (lastSyncData.time == -1) return; timeSinceLastDataSync += Time.deltaTime; currentSyncLerpAlpha += 1/timePerSyncPoint * Time.deltaTime; while (currentSyncLerpAlpha > 1 && syncData.Count > 0) { currentSyncLerpAlpha -= 1; lastSyncData = syncData.Dequeue(); if (syncData.Count > 0) { float oldTimePerSyncPoint = timePerSyncPoint; timePerSyncPoint = estimatedTimeUntilNextSync / originalNeededTime * (syncData.Peek().time - lastSyncData.time); currentSyncLerpAlpha *= oldTimePerSyncPoint / timePerSyncPoint; } else timePerSyncPoint = 999; } if (syncData.Count == 0) { Debug.LogWarning("Reached final point: timeSinceLastDataSync " + timeSinceLastDataSync + " / estimatedTimeUntilNextSync " + estimatedTimeUntilNextSync); currentSyncLerpAlpha = 0; tr.position = lastSyncData.position; tr.rotation = lastSyncData.rotation; rb.velocity = Vector3.zero; return; } // tr.position = Vector3.Lerp(lastSyncData.position, syncData.Peek().position, currentSyncLerpAlpha); rb.MoveRotation( Quaternion.Slerp(lastSyncData.rotation, syncData.Peek().rotation, currentSyncLerpAlpha) ); targetSyncPosition = Vector3.Lerp(lastSyncData.position, syncData.Peek().position, currentSyncLerpAlpha); rb.velocity = (targetSyncPosition - tr.position) / Time.deltaTime; }
void Awake() { tr = transform; rb = GetComponent<Rigidbody>(); lastSyncData = new SyncData(){time = -1}; this.enabled = false; }
internal virtual void BuildClockSubTreeFromTimeline( Timeline timeline, bool hasControllableRoot) { SetFlag(ClockFlags.CanSlip, GetCanSlip()); // Set the CanSlip flag // Here we preview the clock's own slip-ability, hence ClockGroups should return false // at this stage, because their children are not yet added by the time of this call. if (CanSlip && (IsRoot || _timeline.BeginTime.HasValue)) { ResolveDuration(); // A [....] clock with duration of zero or no begin time has no effect, so do skip it if (!_resolvedDuration.HasTimeSpan || _resolvedDuration.TimeSpan > TimeSpan.Zero) { // Verify that we only use SlipBehavior in supported scenarios if ((_timeline.AutoReverse == true) || (_timeline.AccelerationRatio > 0) || (_timeline.DecelerationRatio > 0)) { throw new NotSupportedException(SR.Get(SRID.Timing_CanSlipOnlyOnSimpleTimelines)); } _syncData = new SyncData(this); // CanSlip clocks keep themselves synced HasDescendantsWithUnresolvedDuration = !HasResolvedDuration; // Keep track of when our duration is resolved Clock current = _parent; // Traverse up the parent chain and verify that no unsupported behavior is specified while (current != null) { Debug.Assert(!current.IsTimeManager); // We should not yet be connected to the TimeManager if (current._timeline.AutoReverse || current._timeline.AccelerationRatio > 0 || current._timeline.DecelerationRatio > 0) { throw new System.InvalidOperationException(SR.Get(SRID.Timing_SlipBehavior_SyncOnlyWithSimpleParents)); } current.SetFlag(ClockFlags.CanGrow, true); // Propagate the slippage tracking up the tree if (!HasResolvedDuration) // Let the parents know that we have not yet unresolved duration { current.HasDescendantsWithUnresolvedDuration = true; } current._currentIterationBeginTime = current._beginTime; current = current._parent; } } } }