ZoneLayer.cs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  1. using CommonAI.RTS;
  2. using CommonAI.Zone;
  3. using CommonAI.Zone.Attributes;
  4. using CommonAI.Zone.Helper;
  5. using CommonAI.Zone.ZoneEditor;
  6. using CommonLang;
  7. using CommonLang.Concurrent;
  8. using CommonLang.Log;
  9. using CommonLang.Protocol;
  10. using System;
  11. using System.Collections.Generic;
  12. namespace CommonAI.ZoneClient
  13. {
  14. public interface ILayerClient
  15. {
  16. void SendAction(CommonAI.Zone.Action action);
  17. //为战斗场景添加
  18. void BattleReady(bool bok);
  19. }
  20. /// <summary>
  21. /// 客户端同步模式
  22. /// </summary>
  23. public enum SyncMode : byte
  24. {
  25. /// <summary>
  26. /// 服务端强同步
  27. /// </summary>
  28. ForceByServer = 0,
  29. /// <summary>
  30. /// 移动直接在客户端处理,技能在客户端预处理,(伤害数字由服务端同步)
  31. /// </summary>
  32. MoveByClient_PreSkillByClient = 2,
  33. }
  34. // ---------------------------------------------------------------------------------------------
  35. public partial class ZoneLayer : GameEntity
  36. {
  37. private static AtomicInteger s_alloc_object_count = new AtomicInteger(0);
  38. private static AtomicInteger s_active_object_count = new AtomicInteger(0);
  39. /// <summary>
  40. /// 未释放实例数量
  41. /// </summary>
  42. public static int ActiveZoneLayerCount { get { return s_active_object_count.Value; } }
  43. /// <summary>
  44. /// 分配实例数量
  45. /// </summary>
  46. public static int AllocZoneLayerCount { get { return s_alloc_object_count.Value; } }
  47. /// <summary>
  48. /// 超出此同步范围,立即将坐标修正
  49. /// </summary>
  50. public float AsyncUnitPosModifyMaxRange { get; private set; }
  51. /// <summary>
  52. /// 是否主角做异步位置同步(即客户端先模拟假象)
  53. /// </summary>
  54. public SyncMode ActorSyncMode { get; set; }
  55. /// <summary>
  56. /// 服务器时间,从游戏开始到现在多少毫秒
  57. /// </summary>
  58. public long ServerTimeMS { get { return mRemotePassTimeMS; } }
  59. /// <summary>
  60. /// 是否为Short,双字节同步单位,场景必须小于255
  61. /// </summary>
  62. public bool IsHalfSync { get; private set; }
  63. /// <summary>
  64. /// 是否实时同步Z坐标,如果不实时同步Z坐标,那么客户端本地计算Z
  65. /// </summary>
  66. public bool IsSyncZ { get; private set; }
  67. /// <summary>
  68. /// 当前客户端更新Interval
  69. /// </summary>
  70. public int CurrentIntervalMS { get; private set; }
  71. /// <summary>
  72. /// 当前客户端Ping值
  73. /// </summary>
  74. public int CurrentPing { get; private set; }
  75. /// <summary>
  76. /// 服务端资源版本号
  77. /// </summary>
  78. public string ServerResourceVersion { get; private set; }
  79. /// <summary>
  80. /// 本地资源版本号
  81. /// </summary>
  82. public string ClientResourceVersion { get { return Templates.ResourceVersion; } }
  83. private Logger log = LoggerFactory.GetLogger("ZoneClient");
  84. private long mRemotePassTimeMS = 0;
  85. private SceneData mData;
  86. private ZoneInfo mTerrainDataSrc;
  87. //private SyncMessageQueue<IMessage> mSyncMessageQueue = new SyncMessageQueue<IMessage>();
  88. private List<IMessage> mSyncMessageQueue = new List<IMessage>();
  89. private HashMap<string, object> EnvironmentVarMap = new HashMap<string, object>();
  90. private HashMap<int, object> mListenRequests = new HashMap<int, object>();
  91. private TimeInterval<int> mListenRequestTimeout = new TimeInterval<int>(2000);
  92. private ServerStatusB2C mLastServerStatus;
  93. public float MinStep { get; private set; }
  94. public ILayerClient LayerClient { get; private set; }
  95. public TemplateManager Templates { get; private set; }
  96. public EditorTemplates DataRoot { get; private set; }
  97. public bool IsLoaded { get; private set; }
  98. public ServerStatusB2C ServerStatus { get { return mLastServerStatus; } }
  99. public ZoneLayer(EditorTemplates dataroot, ILayerClient client)
  100. {
  101. ZoneLayer.s_alloc_object_count++;
  102. ZoneLayer.s_active_object_count++;
  103. this.IsLoaded = false;
  104. this.DataRoot = dataroot;
  105. this.LayerClient = client;
  106. this.ActorSyncMode = SyncMode.ForceByServer;
  107. this.Templates = dataroot?.Templates;
  108. if (Templates == null)
  109. {
  110. log.Error("dataroot cannot set to null");
  111. }
  112. else
  113. {
  114. this.AsyncUnitPosModifyMaxRange = Templates.CFG.CLIENT_UNIT_MOVE_MODIFY_MAX_RANGE;
  115. this.MinStep = MoveHelper.GetDistance(1000 / Templates.CFG.SYSTEM_FPS, Templates.CFG.OBJECT_MOVE_TO_MIN_STEP_SEC);
  116. }
  117. }
  118. //-------------------------------------------------------------------------------------------
  119. ~ZoneLayer()
  120. {
  121. ZoneLayer.s_alloc_object_count--;
  122. }
  123. protected virtual void InitSceneData(ClientEnterScene msg)
  124. {
  125. log.Debug("---------------------------------------InitSceneData---------------------------------");
  126. SceneData sdata;
  127. if (mData == null)
  128. {
  129. sdata = DataRoot.LoadScene(msg.sceneID, false, true);
  130. mData = sdata;
  131. }
  132. else
  133. {
  134. sdata = mData;
  135. }
  136. if (sdata == null)
  137. {
  138. throw new Exception("Can not load scene data : " + msg.sceneID);
  139. }
  140. this.ServerResourceVersion = msg.resVersion;
  141. this.mTerrainDataSrc = sdata.ZoneData;
  142. this.SpaceDivSize = msg.spaceDiv;
  143. if (this.SpaceDivSize > 0)
  144. {
  145. this.mSpaceDiv = new SpaceDivision(
  146. mTerrainDataSrc.TotalWidth,
  147. mTerrainDataSrc.TotalHeight,
  148. SpaceDivSize * mTerrainDataSrc.GridCellW,
  149. SpaceDivSize * mTerrainDataSrc.GridCellH);
  150. }
  151. foreach (var dt in sdata.Units)
  152. {
  153. var zea = new ZoneEditorUnit(dt, this);
  154. mFlags.Add(zea.Name, zea);
  155. }
  156. foreach (var dt in sdata.Items)
  157. {
  158. var zea = new ZoneEditorItem(dt, this);
  159. mFlags.Add(zea.Name, zea);
  160. }
  161. foreach (var dt in sdata.Regions)
  162. {
  163. var zea = new ZoneEditorRegion(dt, this);
  164. mFlags.Add(zea.Name, zea);
  165. }
  166. foreach (var dt in sdata.Points)
  167. {
  168. var zea = new ZoneEditorPoint(dt, this);
  169. mFlags.Add(zea.Name, zea);
  170. }
  171. foreach (var dt in sdata.Decorations)
  172. {
  173. var zed = new ZoneEditorDecoration(dt, this);
  174. mFlags.Add(zed.Name, zed);
  175. }
  176. foreach (var dt in sdata.Areas)
  177. {
  178. var zea = new ZoneEditorArea(dt, this);
  179. mFlags.Add(zea.Name, zea);
  180. }
  181. this.InitTerrain(msg, out this.path_terrain_data, out this.path_finder, out this.path_terrain_area_gen);
  182. foreach (var flag in mFlags.Values)
  183. {
  184. flag.OnInit();
  185. }
  186. foreach (ZoneObject o in mObjectes.Objects) { SwapSpace(o); }
  187. IsLoaded = true;
  188. if (mLayerInit != null)
  189. {
  190. mLayerInit.Invoke(this);
  191. }
  192. }
  193. protected override void Disposing()
  194. {
  195. this.IsLoaded = false;
  196. base.Disposing();
  197. this.clearEvents();
  198. foreach (var o in mObjectes.Objects)
  199. {
  200. o.Dispose();
  201. }
  202. this.mObjectes.Clear();
  203. this.mObjectes = null;
  204. this.mActor = null;
  205. foreach (var f in mFlags.Values)
  206. {
  207. f.Dispose();
  208. }
  209. this.mFlags.Clear();
  210. this.mFlags = null;
  211. this.DataRoot = null;
  212. this.Templates = null;
  213. this.DisposeTerrain();
  214. if (mSpaceDiv != null)
  215. {
  216. this.mSpaceDiv.Dispose();
  217. }
  218. this.mSpaceDiv = null;
  219. this.mData = null;
  220. this.mTerrainDataSrc = null;
  221. if (mTasks != null)
  222. {
  223. this.mTasks.Clear();
  224. }
  225. this.mTasks = null;
  226. if (this.mTimeTasks != null)
  227. {
  228. this.mTimeTasks.Dispose();
  229. }
  230. this.mTimeTasks = null;
  231. if (mSyncMessageQueue != null)
  232. {
  233. mSyncMessageQueue.Clear();
  234. }
  235. EnvironmentVarMap.Clear();
  236. EnvironmentVarMap = null;
  237. mListenRequests.Clear();
  238. mLastServerStatus = null;
  239. ZoneLayer.s_active_object_count--;
  240. }
  241. public SceneData Data
  242. {
  243. get { return mData; }
  244. set
  245. {
  246. mData = value;
  247. }
  248. }
  249. public int SceneID
  250. {
  251. get { return mData.ID; }
  252. }
  253. //当前是否为渡劫场景
  254. public bool IsSceneDujie()
  255. {
  256. return mData != null && mData.ID == 70005;
  257. }
  258. public ZoneInfo Terrain
  259. {
  260. get { return path_terrain_data.Data; }
  261. }
  262. public ZoneInfo TerrainSrc
  263. {
  264. get { return mTerrainDataSrc; }
  265. }
  266. /// <summary>
  267. /// 获得当前服务端可同步环境变量
  268. /// </summary>
  269. /// <param name="key"></param>
  270. /// <returns></returns>
  271. public object GetEnvironmentVar(string key)
  272. {
  273. return EnvironmentVarMap.Get(key);
  274. }
  275. /// <summary>
  276. /// 获得当前服务端可同步环境变量列表
  277. /// </summary>
  278. /// <param name="key"></param>
  279. /// <returns></returns>
  280. public IEnumerable<string> ListEnvironmentVars()
  281. {
  282. return EnvironmentVarMap.Keys;
  283. }
  284. public void BeginUpdate(int intervalMS)
  285. {
  286. try
  287. {
  288. if (IsDesposed) { return; }
  289. mTasks.ProcessMessages(this);
  290. if (intervalMS > 0)
  291. {
  292. //this.mLocalPassTimeMS += intervalMS;
  293. this.CurrentIntervalMS = intervalMS;
  294. this.MinStep = MoveHelper.GetDistance(intervalMS, Templates.CFG.OBJECT_MOVE_TO_MIN_STEP_SEC);
  295. this.mObjectes.ForEachObjectsDoUpdateAI();
  296. }
  297. }
  298. catch(Exception )
  299. {
  300. }
  301. }
  302. public void Update()
  303. {
  304. if (IsDesposed) { return; }
  305. //mSyncMessageQueue.ProcessMessages(doEvent);
  306. if (mSyncMessageQueue != null)
  307. {
  308. var num = mSyncMessageQueue.Count;
  309. for (int i = 0; i < num; i++)
  310. {
  311. doEvent(mSyncMessageQueue[i]);
  312. }
  313. mSyncMessageQueue.RemoveRange(0, num);
  314. }
  315. if (CurrentIntervalMS > 0)
  316. {
  317. updateObjects();
  318. mTimeTasks.Update(CurrentIntervalMS);
  319. }
  320. if (mListenRequestTimeout.Update(CurrentIntervalMS))
  321. {
  322. check_request_timeout();
  323. }
  324. }
  325. private void updateObjects()
  326. {
  327. this.mObjectes.ForEachObjectsDoUpdate();
  328. //this.mObjectes.ForEachObjects((zo) =>
  329. //{
  330. // zo.Update();
  331. // return false;
  332. //});
  333. //this.mObjectes.ForEachObjects((zo) =>
  334. //{
  335. // zo.UpdatePos();
  336. // return false;
  337. //});
  338. }
  339. //-------------------------------------------------------------------------------------------
  340. #region IO
  341. /// <summary>
  342. /// 接收新消息
  343. /// </summary>
  344. /// <param name="msg"></param>
  345. public void ProcessMessage(IMessage _msg)
  346. {
  347. if (_msg is PackEvent)
  348. {
  349. var pack = _msg as PackEvent;
  350. for (int i = 0; i < pack.events.Count; i++)
  351. {
  352. var msg = pack.events[i];
  353. if (msg is Pong)
  354. {
  355. uint ctime = (uint)CUtils.CurrentTimeMS; ;
  356. Pong pong = msg as Pong;
  357. this.CurrentPing = (int)(ctime - pong.ClientTimeDayOfMS);
  358. }
  359. else
  360. {
  361. mSyncMessageQueue.Add(msg);
  362. }
  363. }
  364. }
  365. else
  366. {
  367. mSyncMessageQueue.Add(_msg);
  368. }
  369. }
  370. /// <summary>
  371. /// 发送消息
  372. /// </summary>
  373. /// <param name="action"></param>
  374. public void SendAction(CommonAI.Zone.Action action)
  375. {
  376. if (action is Ping)
  377. {
  378. uint ctime = (uint)CUtils.CurrentTimeMS; ;
  379. Ping ping = action as Ping;
  380. ping.DayOfMS = ctime;
  381. }
  382. LayerClient.SendAction(action);
  383. }
  384. /// <summary>
  385. /// 发送请求
  386. /// </summary>
  387. /// <param name="msg"></param>
  388. /// <param name="handler"></param>
  389. /// <param name="timeout"></param>
  390. /// <param name="timeOutMS"></param>
  391. /// <returns></returns>
  392. internal Request SendRequest(ActorRequest msg, OnResponseHandler handler, OnRequestTimeoutHandler timeout = null, int timeOutMS = 15000)
  393. {
  394. Request req = new Request(this, timeOutMS, msg, handler, timeout);
  395. lock (mListenRequests)
  396. {
  397. mListenRequests.Add(req.MessageID, req);
  398. }
  399. LayerClient.SendAction(msg);
  400. return req;
  401. }
  402. #endregion
  403. //-------------------------------------------------------------------------------------------
  404. #region EVENTS
  405. /// <summary>
  406. /// 客户端模拟服务端的包
  407. /// </summary>
  408. /// <param name="msg"></param>
  409. public void PreQueueEvent(IMessage msg)
  410. {
  411. doEvent(msg);
  412. }
  413. public void clientSendDoEvent(IMessage msg)
  414. {
  415. doEvent(msg);
  416. }
  417. private void doEvent(IMessage msg)
  418. {
  419. try
  420. {
  421. if (msg is ActorResponse)
  422. {
  423. var rsp = msg as ActorResponse;
  424. on_received_response(rsp);
  425. }
  426. if (msg is ObjectEvent)
  427. {
  428. var oe = msg as ObjectEvent;
  429. ZoneObject obj = (oe.object_id == 0) ? Actor : GetObject<ZoneObject>(oe.object_id);
  430. if (obj == null)
  431. {
  432. log.Warn(">not found object(" + oe.object_id + ") @event:" + oe);
  433. return;
  434. }
  435. obj.DoEvent(msg as ObjectEvent);
  436. if (mMessageReceived != null)
  437. {
  438. mMessageReceived.Invoke(this, msg);
  439. }
  440. if (mObjectMessageReceived != null)
  441. {
  442. mObjectMessageReceived.Invoke(this, msg, obj);
  443. }
  444. if (obj.mOnDoEvent != null)
  445. {
  446. obj.mOnDoEvent.Invoke(obj, msg as ObjectEvent);
  447. }
  448. return;
  449. }
  450. else if (msg is ServerStatusB2C)
  451. {
  452. mLastServerStatus = msg as ServerStatusB2C;
  453. }
  454. else
  455. {
  456. if (msg is ClientEnterScene)
  457. {
  458. doClientEnterScene(msg as ClientEnterScene);
  459. }
  460. else if (msg is LockActorEvent)
  461. {
  462. doLockActorEvent(msg as LockActorEvent);
  463. }
  464. else if (msg is SyncObjectsEvent)
  465. {
  466. doSyncUnitsEvent(msg as SyncObjectsEvent);
  467. }
  468. else if (msg is SyncFlagsEvent)
  469. {
  470. doSyncFlagsEvent(msg as SyncFlagsEvent);
  471. }
  472. else if (msg is AddUnitEvent)
  473. {
  474. doAddUnitEvent(msg as AddUnitEvent);
  475. }
  476. else if (msg is AddSpellEvent)
  477. {
  478. doAddSpellEvent(msg as AddSpellEvent);
  479. }
  480. else if (msg is AddItemEvent)
  481. {
  482. doAddItemEvent(msg as AddItemEvent);
  483. }
  484. else if (msg is RemoveObjectEvent)
  485. {
  486. doRemoveObjectEvent(msg as RemoveObjectEvent);
  487. }
  488. else if (msg is SyncPosEvent)
  489. {
  490. doSyncPosEvent(msg as SyncPosEvent);
  491. }
  492. else if (msg is DecorationChangedEvent)
  493. {
  494. doDecorationChanged(msg as DecorationChangedEvent);
  495. }
  496. else if (msg is FlagTagChangedEvent)
  497. {
  498. doFlagTagChanged(msg as FlagTagChangedEvent);
  499. }
  500. else if (msg is SyncEnvironmentVarEvent)
  501. {
  502. doSyncEnvironmentVarEvent(msg as SyncEnvironmentVarEvent);
  503. }
  504. else if (msg is ChangeBGMEvent)
  505. {
  506. doChangeBGMEvent(msg as ChangeBGMEvent);
  507. }
  508. else if (msg is DoScriptEvent)
  509. {
  510. doDoScriptEvent(msg as DoScriptEvent);
  511. }
  512. else if (msg is ScriptCommandEvent)
  513. {
  514. doScriptCommandEvent(msg as ScriptCommandEvent);
  515. }
  516. else if (msg is GameOverEvent)
  517. {
  518. //doZoneEvent(ZoneEvent.GAME_OVER, null, msg);
  519. doGameOver(msg as GameOverEvent);
  520. }
  521. //doZoneEvent(ZoneEvent.MESSAGE, null, msg);
  522. if (mMessageReceived != null)
  523. {
  524. mMessageReceived.Invoke(this, msg);
  525. }
  526. }
  527. }
  528. finally
  529. {
  530. if (msg is Event) (msg as Event).sender = null;
  531. }
  532. }
  533. private void doClientEnterScene(ClientEnterScene msg)
  534. {
  535. this.InitSceneData(msg);
  536. }
  537. private void doLockActorEvent(LockActorEvent msg)
  538. {
  539. //客户端可以主动发送战斗服消息
  540. if(LayerClient != null)
  541. {
  542. LayerClient.BattleReady(true);
  543. }
  544. if (msg.CurrentZoneVars != null)
  545. {
  546. foreach (CommonAI.ZoneClient.ClientStruct.ZoneEnvironmentVar var in msg.CurrentZoneVars)
  547. {
  548. EnvironmentVarMap.Put(var.Key, var.Value);
  549. }
  550. }
  551. if (msg.UnitData != null)
  552. {
  553. SyncUnitInfo syn = msg.UnitData;
  554. ZoneUnit ret = GetObject<ZoneUnit>(syn.ObjectID) as ZoneUnit;
  555. if (ret != null)
  556. {
  557. removeObj(syn.ObjectID);
  558. }
  559. UnitInfo unit = Templates.getUnit(syn.TemplateID);
  560. if (unit != null)
  561. {
  562. unit = unit.Clone() as UnitInfo;
  563. unit.Properties = msg.GameServerProp;
  564. ZoneActor act = TemplateManager.Factory.CreateClientActor(this, unit, msg);
  565. act.Direction = syn.direction;
  566. mActor = act;
  567. if (ret == null)
  568. {
  569. addObj(act);
  570. }
  571. else
  572. {
  573. replaceObj(act);
  574. }
  575. }
  576. else
  577. {
  578. log.Error("TemplateID Not Exist! ID = " + syn.TemplateID);
  579. }
  580. }
  581. }
  582. private void doSyncUnitsEvent(SyncObjectsEvent msg)
  583. {
  584. foreach (var syn in msg.Objects)
  585. {
  586. doSyncObjectInfo(syn);
  587. }
  588. }
  589. private void doSyncFlagsEvent(SyncFlagsEvent msg)
  590. {
  591. foreach (var kv in msg.ChangedTags)
  592. {
  593. var flag = mFlags.Get(kv.Key);
  594. if (flag != null)
  595. {
  596. flag.Tag = kv.Value;
  597. if (mFlagTagChanged != null)
  598. {
  599. mFlagTagChanged.Invoke(this, flag);
  600. }
  601. }
  602. }
  603. foreach (var flag in mFlags.Values)
  604. {
  605. if (flag is ZoneEditorDecoration)
  606. {
  607. ZoneEditorDecoration ed = flag as ZoneEditorDecoration;
  608. bool enable = !msg.ClosedDecorations.Contains(ed.Name);
  609. if (ed.Enable != enable)
  610. {
  611. ed.Enable = enable;
  612. ed.DecorationChanged();
  613. //doZoneEvent(ZoneEvent.DECORATION_CHANGED, ed);
  614. if (mDecorationChanged != null)
  615. {
  616. mDecorationChanged.Invoke(this, ed);
  617. }
  618. }
  619. }
  620. }
  621. }
  622. private ZoneObject doSyncObjectInfo(SyncObjectInfo syn)
  623. {
  624. ZoneObject ret = GetObject<ZoneObject>(syn.ObjectID);
  625. if (ret == null)
  626. {
  627. if (syn is SyncUnitInfo)
  628. {
  629. UnitInfo unit = Templates.getUnit(syn.TemplateID);
  630. if (unit != null)
  631. {
  632. unit = unit.Clone() as UnitInfo;
  633. ret = TemplateManager.Factory.CreateClientUnit(this, unit, syn as SyncUnitInfo, null);
  634. }
  635. }
  636. else if (syn is SyncItemInfo)
  637. {
  638. ItemTemplate item = Templates.getItem(syn.TemplateID);
  639. if (item != null)
  640. {
  641. item = item.Clone() as ItemTemplate;
  642. ret = TemplateManager.Factory.CreateClientItem(this, item, syn as SyncItemInfo, null);
  643. }
  644. }
  645. else if (syn is SyncSpellInfo)
  646. {
  647. SpellTemplate spell = Templates.getSpell(syn.TemplateID);
  648. if (spell != null)
  649. {
  650. spell = spell.Clone() as SpellTemplate;
  651. ret = TemplateManager.Factory.CreateClientSpell(this, spell, syn as SyncSpellInfo, null);
  652. }
  653. }
  654. if (ret != null)
  655. {
  656. addObj(ret);
  657. }
  658. else
  659. {
  660. log.Error(string.Format("SyncObject : Can Not Create Object : {0} as {1}", syn.TemplateID, syn));
  661. return null;
  662. }
  663. }
  664. ret.ForceSyncPos(syn.x, syn.y);
  665. ret.Direction = syn.direction;
  666. return ret;
  667. }
  668. private void doAddUnitEvent(AddUnitEvent e)
  669. {
  670. UnitInfo info = Templates.getUnit(e.Sync.TemplateID);
  671. if (info != null)
  672. {
  673. info = info.Clone() as UnitInfo;
  674. ZoneUnit ret = TemplateManager.Factory.CreateClientUnit(this, info, e.Sync, e);
  675. if (addObj(ret))
  676. {
  677. ret.SyncBuffStatus(e.Sync.CurrentBuffStatus);
  678. }
  679. }
  680. }
  681. private void doAddSpellEvent(AddSpellEvent e)
  682. {
  683. SpellTemplate sp = Templates.getSpell(e.spell_template_id);
  684. if (sp != null)
  685. {
  686. sp = sp.Clone() as SpellTemplate;
  687. var syn = new SyncSpellInfo();
  688. syn.ObjectID = e.spell_id;
  689. syn.x = e.x;
  690. syn.y = e.y;
  691. syn.direction = e.direction;
  692. var ret = TemplateManager.Factory.CreateClientSpell(this, sp, syn, e);
  693. ret.Direction = e.direction;
  694. ret.Sender = GetObject<ZoneObject>(e.sender_unit_id);
  695. if (ret.Sender != null && ret.Sender is ZoneSpell)
  696. {
  697. ret.LaunchHeight = (ret.Sender as ZoneSpell).Z;
  698. }
  699. else
  700. {
  701. ret.LaunchHeight = e.height;
  702. }
  703. ret.Launcher = GetUnit(e.launcher_unit_id);
  704. ret.Target = GetUnit(e.target_obj_id);
  705. ret.TargetPos = e.target_pos;
  706. addObj(ret);
  707. }
  708. else
  709. {
  710. log.Error($"Not found spell template :{e.spell_template_id}");
  711. }
  712. }
  713. private void doAddItemEvent(AddItemEvent e)
  714. {
  715. ItemTemplate item = Templates.getItem(e.Sync.TemplateID);
  716. if (item != null)
  717. {
  718. item = item.Clone() as ItemTemplate;
  719. ZoneItem ret = TemplateManager.Factory.CreateClientItem(this, item, e.Sync, e);
  720. addObj(ret);
  721. }
  722. }
  723. private void doRemoveObjectEvent(RemoveObjectEvent e)
  724. {
  725. removeObj(e.object_id);
  726. }
  727. private void doSyncPosEvent(SyncPosEvent e)
  728. {
  729. bool isDujie = IsSceneDujie();
  730. this.mRemotePassTimeMS = e.PassTimeMS;
  731. this.IsHalfSync = e.IsHalf;
  732. this.IsSyncZ = e.IsSyncZ;
  733. ZoneObject gu;
  734. if (e.units_st != null)
  735. {
  736. for (int i = 0; i < e.units_st.Length; ++i)
  737. {
  738. gu = GetObject<ZoneObject>(e.units_st[i].ID);
  739. if (gu != null)
  740. {
  741. //YXJDebug.logWarning(">>{0}:{1}>syncState{4}-->x:{2},y:{3}", gu.ObjectID, gu.Name, e.units_st[i].UnitMainState, e.units_st[i].UnitSubState, ((ZoneUnit)gu).CurrentState);
  742. if (isDujie && e.units_st[i].UnitMainState == UnitActionStatus.Move)
  743. {
  744. //YXJDebug.logWarning(">({0}/{1})ignore move state@Dujie scene", gu.ObjectID, gu.Name);
  745. }
  746. else
  747. {
  748. gu.SyncPos(ref e.units_st[i]);
  749. }
  750. }
  751. }
  752. }
  753. if (e.units_pos != null)
  754. {
  755. for (int i = 0; i < e.units_pos.Length; ++i)
  756. {
  757. gu = GetObject<ZoneObject>(e.units_pos[i].ID);
  758. if (gu != null)
  759. {
  760. //YXJDebug.logWarning(">>{0}:{1}>syncPos({4}), x:{2},y:{3}", gu.ObjectID, gu.Name, e.units_pos[i].X, e.units_pos[i].Y, ((ZoneUnit)gu).CurrentState);
  761. if (isDujie)
  762. {
  763. //YXJDebug.logWarning(">({0}/{1})ignore syncPos@Dujie scene", gu.ObjectID, gu.Name);
  764. }
  765. else
  766. {
  767. gu.SyncPos(ref e.units_pos[i]);
  768. SwapSpace(gu);
  769. }
  770. }
  771. }
  772. }
  773. }
  774. private void doDecorationChanged(DecorationChangedEvent e)
  775. {
  776. var ed = mFlags.Get(e.Name) as ZoneEditorDecoration;
  777. if (ed != null && ed.Enable != e.Enable)
  778. {
  779. ed.Enable = e.Enable;
  780. ed.DecorationChanged();
  781. if (mDecorationChanged != null)
  782. {
  783. mDecorationChanged.Invoke(this, ed);
  784. }
  785. //doZoneEvent(ZoneEvent.DECORATION_CHANGED, ed, e);
  786. }
  787. }
  788. private void doFlagTagChanged(FlagTagChangedEvent e)
  789. {
  790. var flag = mFlags.Get(e.Name);
  791. if (flag != null && flag.Tag != flag.EditorData.Tag)
  792. {
  793. flag.Tag = e.Tag;
  794. if (mFlagTagChanged != null)
  795. {
  796. mFlagTagChanged.Invoke(this, flag);
  797. }
  798. //doZoneEvent(ZoneEvent.DECORATION_CHANGED, ed, e);
  799. }
  800. }
  801. private void doSyncEnvironmentVarEvent(SyncEnvironmentVarEvent e)
  802. {
  803. EnvironmentVarMap[e.Key] = e.Value;
  804. }
  805. private void doChangeBGMEvent(ChangeBGMEvent e)
  806. {
  807. if (mOnChangeBGM != null)
  808. {
  809. mOnChangeBGM.Invoke(this, e.FileName);
  810. }
  811. }
  812. private void doDoScriptEvent(DoScriptEvent e)
  813. {
  814. if (mOnScriptFile != null)
  815. {
  816. mOnScriptFile.Invoke(this, e.ScriptFileName);
  817. }
  818. }
  819. private void doScriptCommandEvent(ScriptCommandEvent e)
  820. {
  821. if (mOnScriptCommand != null)
  822. {
  823. mOnScriptCommand.Invoke(this, e.message);
  824. }
  825. }
  826. private void doGameOver(GameOverEvent evt)
  827. {
  828. if (mGameOver != null)
  829. {
  830. mGameOver.Invoke(this, evt.WinForce == Actor.Force, evt.message);
  831. }
  832. }
  833. #endregion
  834. //-------------------------------------------------------------------------------------------
  835. // #region EVENT_NOTIFY
  836. //
  837. // private void doZoneEvent(ZoneEvent ze, ZoneLayerObject obj = null, IMessage msg = null)
  838. // {
  839. // switch (ze)
  840. // {
  841. // case ZoneEvent.INIT:
  842. //
  843. // break;
  844. // case ZoneEvent.ADD_OBJ:
  845. //
  846. // break;
  847. // case ZoneEvent.REMOVE_OBJ:
  848. //
  849. // break;
  850. // case ZoneEvent.GAME_OVER:
  851. //
  852. // break;
  853. // case ZoneEvent.MESSAGE:
  854. //
  855. // break;
  856. // case ZoneEvent.OBJECT_EVENT:
  857. //
  858. // break;
  859. // case ZoneEvent.DECORATION_CHANGED:
  860. //
  861. // break;
  862. // }
  863. // }
  864. //
  865. // #endregion
  866. //-------------------------------------------------------------------------------------------
  867. #region OBJECTS
  868. private bool addObj(ZoneObject obj)
  869. {
  870. ZoneObject ret = mObjectes.GetObject<ZoneObject>(obj.ObjectID);
  871. if (ret != null)
  872. {
  873. ret.ForceSyncPos(obj.X, obj.Y);
  874. ret.Direction = obj.Direction;
  875. obj.Dispose();
  876. return false;
  877. }
  878. else
  879. {
  880. mObjectes.Add(obj);
  881. SwapSpace(obj);
  882. obj.OnAdded();
  883. if (mObjectEnter != null)
  884. {
  885. mObjectEnter.Invoke(this, obj);
  886. }
  887. if (obj == mActor)
  888. {
  889. if (mActorAdded != null)
  890. {
  891. mActorAdded.Invoke(this, mActor);
  892. }
  893. mActor.SendReady();
  894. }
  895. return true;
  896. }
  897. }
  898. private void replaceObj(ZoneObject obj)
  899. {
  900. ZoneObject old = mObjectes.RemoveObjectByKey(obj.ObjectID);
  901. if (old != null)
  902. {
  903. old.Dispose();
  904. if (mSpaceDiv != null) mSpaceDiv.ClearSpace(old.mCurrentCellNode);
  905. }
  906. mObjectes.Add(obj);
  907. SwapSpace(obj);
  908. obj.OnAdded();
  909. //doZoneEvent(ZoneEvent.ADD_OBJ, obj, null);
  910. if (mObjectEnter != null)
  911. {
  912. mObjectEnter.Invoke(this, obj as ZoneObject);
  913. }
  914. if (obj == mActor)
  915. {
  916. if (mActorAdded != null)
  917. {
  918. mActorAdded.Invoke(this, mActor);
  919. }
  920. mActor.SendReady();
  921. }
  922. }
  923. private void removeObj(uint objID)
  924. {
  925. ZoneObject ret = mObjectes.RemoveObjectByKey(objID);
  926. if (ret != null)
  927. {
  928. if (mPlayerLeave != null)
  929. {
  930. mPlayerLeave.Invoke(this, ret);
  931. }
  932. ret.Dispose();
  933. if (mSpaceDiv != null) { mSpaceDiv.ClearSpace(ret.mCurrentCellNode); }
  934. //doZoneEvent(ZoneEvent.REMOVE_OBJ, ret, null);
  935. if (mObjectLeave != null)
  936. {
  937. mObjectLeave.Invoke(this, ret);
  938. }
  939. }
  940. }
  941. #endregion
  942. //-------------------------------------------------------------------------------------------
  943. #region REQUEST_RESPONSE
  944. private void check_request_timeout()
  945. {
  946. long curTime = CUtils.CurrentTimeMS;
  947. lock (mListenRequests)
  948. {
  949. if (mListenRequests.Count > 0)
  950. {
  951. using (var removing = ListObjectPool<Request>.AllocAutoRelease())
  952. {
  953. foreach (Request req in mListenRequests.Values)
  954. {
  955. if (req.EndTime < curTime)
  956. {
  957. removing.Add(req);
  958. }
  959. }
  960. if (removing.Count > 0)
  961. {
  962. foreach (Request remove in removing)
  963. {
  964. mListenRequests.RemoveByKey(remove.MessageID);
  965. remove.onTimeout();
  966. }
  967. }
  968. }
  969. }
  970. }
  971. }
  972. private bool on_received_response(ActorResponse rsp)
  973. {
  974. Request request = null;
  975. lock (mListenRequests)
  976. {
  977. request = mListenRequests.RemoveByKey(rsp.MessageID) as Request;
  978. }
  979. if (request != null)
  980. {
  981. request.onRecivedMessage(rsp);
  982. return true;
  983. }
  984. return false;
  985. }
  986. private AtomicInteger MessageIDGen = new AtomicInteger(1);
  987. public class Request
  988. {
  989. internal static Logger log = LoggerFactory.GetLogger("ZoneLayer.Request");
  990. private OnResponseHandler mHandler;
  991. private OnRequestTimeoutHandler mTimeout;
  992. public ZoneLayer Layer { get; private set; }
  993. public int TimeOutMS { get; private set; }
  994. public long EndTime { get; private set; }
  995. public long SendTime { get; private set; }
  996. public int MessageID { get; private set; }
  997. public ActorRequest RequestMessage { get; protected set; }
  998. public ActorResponse ResponseMessage { get; protected set; }
  999. public Request(ZoneLayer client, int timeOutMS, ActorRequest request, OnResponseHandler handler = null, OnRequestTimeoutHandler timeout = null)
  1000. {
  1001. this.Layer = client;
  1002. this.MessageID = request.MessageID = client.MessageIDGen.GetAndIncrement();
  1003. this.RequestMessage = request;
  1004. this.TimeOutMS = timeOutMS;
  1005. this.SendTime = CUtils.CurrentTimeMS;
  1006. this.EndTime = SendTime + timeOutMS;
  1007. this.mHandler = handler;
  1008. this.mTimeout = timeout;
  1009. }
  1010. virtual internal void onRecivedMessage(ActorResponse msg)
  1011. {
  1012. ResponseMessage = msg;
  1013. if (mHandler != null)
  1014. {
  1015. try
  1016. {
  1017. mHandler.Invoke(this);
  1018. }
  1019. catch (Exception err)
  1020. {
  1021. log.Error(err.Message, err);
  1022. }
  1023. }
  1024. mHandler = null;
  1025. mTimeout = null;
  1026. }
  1027. virtual internal void onTimeout()
  1028. {
  1029. if (mTimeout != null)
  1030. {
  1031. try
  1032. {
  1033. mTimeout.Invoke(this);
  1034. }
  1035. catch (Exception err)
  1036. {
  1037. log.Error(err.Message, err);
  1038. }
  1039. }
  1040. mHandler = null;
  1041. mTimeout = null;
  1042. }
  1043. }
  1044. public delegate void OnResponseHandler(Request req);
  1045. public delegate void OnRequestTimeoutHandler(Request req);
  1046. #endregion
  1047. //------------------------------------------------------------------------------------
  1048. #region TIMING_AND_TASK
  1049. private SyncMessageQueueAction<ZoneLayer> mTasks = new SyncMessageQueueAction<ZoneLayer>();
  1050. private TimeTaskQueue mTimeTasks = new TimeTaskQueue();
  1051. private void doTask(Action<ZoneLayer> task)
  1052. {
  1053. task(this);
  1054. }
  1055. /// <summary>
  1056. /// 【线程安全】向主线程排一个任务
  1057. /// </summary>
  1058. /// <param name="task"></param>
  1059. public void QueueTask(Action<ZoneLayer> task)
  1060. {
  1061. mTasks.Enqueue(task);
  1062. }
  1063. /// <summary>
  1064. /// 【线程安全】增加时间任务
  1065. /// </summary>
  1066. /// <param name="intervalMS"></param>
  1067. /// <param name="delayMS"></param>
  1068. /// <param name="repeat"></param>
  1069. /// <param name="handler"></param>
  1070. public TimeTaskMS AddTimeTask(int intervalMS, int delayMS, int repeat, TickHandler handler)
  1071. {
  1072. return mTimeTasks.AddTimeTask(intervalMS, delayMS, repeat, handler);
  1073. }
  1074. /// <summary>
  1075. /// 【线程安全】增加延时回调方法
  1076. /// </summary>
  1077. /// <param name="delayMS"></param>
  1078. /// <param name="handler"></param>
  1079. public TimeTaskMS AddTimeDelayMS(int delayMS, TickHandler handler)
  1080. {
  1081. return mTimeTasks.AddTimeDelayMS(delayMS, handler);
  1082. }
  1083. /// <summary>
  1084. /// 【线程安全】增加定时回调方法
  1085. /// </summary>
  1086. /// <param name="intervalMS"></param>
  1087. /// <param name="handler"></param>
  1088. public TimeTaskMS AddTimePeriodicMS(int intervalMS, TickHandler handler)
  1089. {
  1090. return mTimeTasks.AddTimePeriodicMS(intervalMS, handler);
  1091. }
  1092. #endregion
  1093. //-------------------------------------------------------------------------------------------
  1094. #region EVENTS
  1095. public delegate void OnInitHandler(ZoneLayer layer);
  1096. public delegate void OnActorAddedHandler(ZoneLayer layer, ZoneActor actor);
  1097. public delegate void OnObjectEnterHandler(ZoneLayer layer, ZoneObject obj);
  1098. public delegate void OnObjectLeaveHandler(ZoneLayer layer, ZoneObject obj);
  1099. public delegate void OnPlayerLevelHandler(ZoneLayer layer, ZoneObject obj);
  1100. public delegate void OnDecorationChangedHandler(ZoneLayer layer, ZoneEditorDecoration ed);
  1101. public delegate void OnFlagTagChangedHandler(ZoneLayer layer, ZoneFlag flag);
  1102. public delegate void OnMessageReceivedHandler(ZoneLayer layer, IMessage msg);
  1103. public delegate void OnObjectMessageReceivedHandler(ZoneLayer layer, IMessage msg, ZoneObject obj);
  1104. public delegate void OnGameOverHandler(ZoneLayer layer, bool isWin, string msg);
  1105. public delegate void OnScriptCommandHandler(ZoneLayer layer, string msg);
  1106. public delegate void OnScriptFileHandler(ZoneLayer layer, string filename);
  1107. public delegate void OnChangeBGMHandler(ZoneLayer layer, string filename);
  1108. /* 只要不加 event 就不会报错 */
  1109. private OnInitHandler mLayerInit;
  1110. private OnActorAddedHandler mActorAdded;
  1111. private OnObjectEnterHandler mObjectEnter;
  1112. private OnObjectLeaveHandler mObjectLeave;
  1113. private OnDecorationChangedHandler mDecorationChanged;
  1114. private OnFlagTagChangedHandler mFlagTagChanged;
  1115. private OnMessageReceivedHandler mMessageReceived;
  1116. private OnObjectMessageReceivedHandler mObjectMessageReceived;
  1117. //本地外部临时数据(用于跨服战),由于先断数据层,再清渲染层会导致外部临时数据清理的时候出错
  1118. private OnPlayerLevelHandler mPlayerLeave;
  1119. private OnGameOverHandler mGameOver;
  1120. private OnScriptCommandHandler mOnScriptCommand;
  1121. private OnScriptFileHandler mOnScriptFile;
  1122. private OnChangeBGMHandler mOnChangeBGM;
  1123. [EventTriggerDescAttribute("客户端场景初始化时触发")]
  1124. public event OnInitHandler LayerInit { add { mLayerInit += value; } remove { mLayerInit -= value; } }
  1125. [EventTriggerDescAttribute("主角被添加时触发")]
  1126. public event OnActorAddedHandler ActorAdded { add { mActorAdded += value; } remove { mActorAdded -= value; } }
  1127. [EventTriggerDescAttribute("单位进入场景")]
  1128. public event OnObjectEnterHandler ObjectEnter { add { mObjectEnter += value; } remove { mObjectEnter -= value; } }
  1129. [EventTriggerDescAttribute("玩家离开场景")]
  1130. public event OnPlayerLevelHandler PlayerLeave { add { mPlayerLeave += value; } remove { mPlayerLeave -= value; } }
  1131. [EventTriggerDescAttribute("单位离开场景")]
  1132. public event OnObjectLeaveHandler ObjectLeave { add { mObjectLeave += value; } remove { mObjectLeave -= value; } }
  1133. [EventTriggerDescAttribute("空气墙变化时触发")]
  1134. public event OnDecorationChangedHandler DecorationChanged { add { mDecorationChanged += value; } remove { mDecorationChanged -= value; } }
  1135. [EventTriggerDescAttribute("Flag Tag 变化时触发")]
  1136. public event OnFlagTagChangedHandler FlagTagChanged { add { mFlagTagChanged += value; } remove { mFlagTagChanged -= value; } }
  1137. [EventTriggerDescAttribute("接收网络消息")]
  1138. public event OnMessageReceivedHandler MessageReceived { add { mMessageReceived += value; } remove { mMessageReceived -= value; } }
  1139. [EventTriggerDescAttribute("接收Object网络消息")]
  1140. public event OnObjectMessageReceivedHandler ObjectMessageReceived { add { mObjectMessageReceived += value; } remove { mObjectMessageReceived -= value; } }
  1141. [EventTriggerDescAttribute("BGM发生变化时触发")]
  1142. public event OnChangeBGMHandler OnChangeBGM { add { mOnChangeBGM += value; } remove { mOnChangeBGM -= value; } }
  1143. [EventTriggerDescAttribute("游戏结束")]
  1144. public event OnGameOverHandler GameOver { add { mGameOver += value; } remove { mGameOver -= value; } }
  1145. [EventTriggerDescAttribute("服务端通知客户端执行指定脚本代码")]
  1146. public event OnScriptCommandHandler OnScriptCommand { add { mOnScriptCommand += value; } remove { mOnScriptCommand -= value; } }
  1147. [EventTriggerDescAttribute("服务端通知客户端执行指定脚本文件")]
  1148. public event OnScriptFileHandler OnScriptFile { add { mOnScriptFile += value; } remove { mOnScriptFile -= value; } }
  1149. private void clearEvents()
  1150. {
  1151. this.mLayerInit = null;
  1152. this.mActorAdded = null;
  1153. this.mObjectEnter = null;
  1154. this.mObjectLeave = null;
  1155. this.mDecorationChanged = null;
  1156. this.mFlagTagChanged = null;
  1157. this.mMessageReceived = null;
  1158. this.mObjectMessageReceived = null;
  1159. this.mGameOver = null;
  1160. this.mOnScriptCommand = null;
  1161. this.mOnScriptFile = null;
  1162. this.mOnChangeBGM = null;
  1163. this.mPlayerLeave = null;
  1164. }
  1165. #endregion
  1166. }
  1167. }