forked from kbengine/kbengine_unity3d_plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKBEngine.cs
2482 lines (2005 loc) · 68 KB
/
KBEngine.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
namespace KBEngine
{
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Text.RegularExpressions;
using MessageID = System.UInt16;
using MessageLength = System.UInt16;
/*
这是KBEngine插件的核心模块
包括网络创建、持久化协议、entities的管理、以及引起对外可调用接口。
一些可以参考的地方:
http://www.kbengine.org/docs/programming/clientsdkprogramming.html
http://www.kbengine.org/docs/programming/kbe_message_format.html
http://www.kbengine.org/cn/docs/programming/clientsdkprogramming.html
http://www.kbengine.org/cn/docs/programming/kbe_message_format.html
*/
public class KBEngineApp
{
public static KBEngineApp app = null;
private NetworkInterface _networkInterface = null;
KBEngineArgs _args = null;
// 客户端的类别
// http://www.kbengine.org/docs/programming/clientsdkprogramming.html
// http://www.kbengine.org/cn/docs/programming/clientsdkprogramming.html
public enum CLIENT_TYPE
{
// Mobile(Phone, Pad)
CLIENT_TYPE_MOBILE = 1,
// Windows/Linux/Mac Application program
// Contains the Python-scripts, entitydefs parsing and check entitydefs-MD5, Native
CLIENT_TYPE_PC = 2,
// Web,HTML5,Flash
// not contain Python-scripts and entitydefs analysis, can be imported protocol from network
CLIENT_TYPE_BROWSER = 3,
// bots(Contains the Python-scripts, entitydefs parsing and check entitydefs-MD5, Native)
CLIENT_TYPE_BOTS = 4,
// Mini-Client
// Allowing does not contain Python-scripts and entitydefs analysis, can be imported protocol from network
CLIENT_TYPE_MINI = 5,
};
public string username = "kbengine";
public string password = "123456";
// 是否正在加载本地消息协议
private static bool loadingLocalMessages_ = false;
// 消息协议是否已经导入了
private static bool loginappMessageImported_ = false;
private static bool baseappMessageImported_ = false;
private static bool entitydefImported_ = false;
private static bool isImportServerErrorsDescr_ = false;
// 服务端分配的baseapp地址
public string baseappIP = "";
public UInt16 baseappPort = 0;
// 当前状态
public string currserver = "";
public string currstate = "";
// 服务端下行以及客户端上行用于登录时处理的账号绑定的二进制信息
// 该信息由用户自己进行扩展
private byte[] _serverdatas = new byte[0];
private byte[] _clientdatas = new byte[0];
// 通信协议加密,blowfish协议
private byte[] _encryptedKey = new byte[0];
// 服务端与客户端的版本号以及协议MD5
public string serverVersion = "";
public string clientVersion = "0.6.1";
public string serverScriptVersion = "";
public string clientScriptVersion = "0.1.0";
public string serverProtocolMD5 = "";
public string serverEntitydefMD5 = "";
// 持久化插件信息, 例如:从服务端导入的协议可以持久化到本地,下次登录版本不发生改变
// 可以直接从本地加载来提供登录速度
private PersistentInofs _persistentInofs = null;
// 当前玩家的实体id与实体类别
public UInt64 entity_uuid = 0;
public Int32 entity_id = 0;
public string entity_type = "";
// 当前玩家最后一次同步到服务端的位置与朝向与服务端最后一次同步过来的位置
private Vector3 _entityLastLocalPos = new Vector3(0f, 0f, 0f);
private Vector3 _entityLastLocalDir = new Vector3(0f, 0f, 0f);
private Vector3 _entityServerPos = new Vector3(0f, 0f, 0f);
// space的数据,具体看API手册关于spaceData
// https://github.com/kbengine/kbengine/tree/master/docs/api
private Dictionary<string, string> _spacedatas = new Dictionary<string, string>();
// 所有实体都保存于这里, 请参看API手册关于entities部分
// https://github.com/kbengine/kbengine/tree/master/docs/api
public Dictionary<Int32, Entity> entities = new Dictionary<Int32, Entity>();
// 在玩家AOI范围小于256个实体时我们可以通过一字节索引来找到entity
private List<Int32> _entityIDAliasIDList = new List<Int32>();
private Dictionary<Int32, MemoryStream> _bufferedCreateEntityMessage = new Dictionary<Int32, MemoryStream>();
// 描述服务端返回的错误信息
public struct ServerErr
{
public string name;
public string descr;
public UInt16 id;
}
// 所有服务端错误码对应的错误描述
public static Dictionary<UInt16, ServerErr> serverErrs = new Dictionary<UInt16, ServerErr>();
private System.DateTime _lastticktime = System.DateTime.Now;
private System.DateTime _lastUpdateToServerTime = System.DateTime.Now;
// 玩家当前所在空间的id, 以及空间对应的资源
public UInt32 spaceID = 0;
public string spaceResPath = "";
public bool isLoadedGeometry = false;
// entityDef管理模块
public static EntityDef entityDef = new EntityDef();
// 按照标准,每个客户端部分都应该包含这个属性
public const string component = "client";
public KBEngineApp(KBEngineArgs args)
{
if (app != null)
throw new Exception("Only one instance of KBEngineApp!");
app = this;
initialize(args);
}
public virtual bool initialize(KBEngineArgs args)
{
_args = args;
initNetwork();
// 注册事件
installEvents();
// 允许持久化KBE(例如:协议,entitydef等)
if(args.persistentDataPath != "")
_persistentInofs = new PersistentInofs(args.persistentDataPath);
return true;
}
void initNetwork()
{
Message.bindFixedMessage();
_networkInterface = new NetworkInterface();
}
void installEvents()
{
Event.registerIn("createAccount", this, "createAccount");
Event.registerIn("login", this, "login");
Event.registerIn("relogin_baseapp", this, "relogin_baseapp");
Event.registerIn("_closeNetwork", this, "_closeNetwork");
}
public KBEngineArgs getInitArgs()
{
return _args;
}
public virtual void destroy()
{
Dbg.WARNING_MSG("KBEngine::destroy()");
reset();
KBEngine.Event.deregisterIn(this);
resetMessages();
KBEngineApp.app = null;
}
public NetworkInterface networkInterface()
{
return _networkInterface;
}
public byte[] serverdatas()
{
return _serverdatas;
}
public void entityServerPos(Vector3 pos)
{
_entityServerPos = pos;
}
public void resetMessages()
{
loadingLocalMessages_ = false;
loginappMessageImported_ = false;
baseappMessageImported_ = false;
entitydefImported_ = false;
isImportServerErrorsDescr_ = false;
serverErrs.Clear ();
Message.clear ();
EntityDef.clear ();
Entity.clear();
Dbg.DEBUG_MSG("KBEngine::resetMessages()");
}
public virtual void reset()
{
KBEngine.Event.clearFiredEvents();
clearEntities(true);
currserver = "";
currstate = "";
_serverdatas = new byte[0];
serverVersion = "";
serverScriptVersion = "";
entity_uuid = 0;
entity_id = 0;
entity_type = "";
_entityIDAliasIDList.Clear();
_bufferedCreateEntityMessage.Clear();
_lastticktime = System.DateTime.Now;
_lastUpdateToServerTime = System.DateTime.Now;
spaceID = 0;
spaceResPath = "";
isLoadedGeometry = false;
_networkInterface.reset();
_networkInterface = new NetworkInterface();
_spacedatas.Clear();
}
public static bool validEmail(string strEmail)
{
return Regex.IsMatch(strEmail, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)
|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}
/*
插件的主循环处理函数
*/
public virtual void process()
{
// 处理网络
_networkInterface.process();
// 处理外层抛入的事件
Event.processInEvents();
// 向服务端发送心跳以及同步角色信息到服务端
sendTick();
}
/*
当前玩家entity
*/
public Entity player()
{
Entity e;
if(entities.TryGetValue(entity_id, out e))
return e;
return null;
}
public void _closeNetwork(NetworkInterface networkInterface)
{
networkInterface.close();
}
/*
向服务端发送心跳以及同步角色信息到服务端
*/
public void sendTick()
{
if(!_networkInterface.valid())
return;
if(!loginappMessageImported_ && !baseappMessageImported_)
return;
TimeSpan span = DateTime.Now - _lastticktime;
// 更新玩家的位置与朝向到服务端
updatePlayerToServer();
if(span.Seconds > 15)
{
Message Loginapp_onClientActiveTickMsg = null;
Message Baseapp_onClientActiveTickMsg = null;
Message.messages.TryGetValue("Loginapp_onClientActiveTick", out Loginapp_onClientActiveTickMsg);
Message.messages.TryGetValue("Baseapp_onClientActiveTick", out Baseapp_onClientActiveTickMsg);
if(currserver == "loginapp")
{
if(Loginapp_onClientActiveTickMsg != null)
{
Bundle bundle = new Bundle();
bundle.newMessage(Message.messages["Loginapp_onClientActiveTick"]);
bundle.send(_networkInterface);
}
}
else
{
if(Baseapp_onClientActiveTickMsg != null)
{
Bundle bundle = new Bundle();
bundle.newMessage(Message.messages["Baseapp_onClientActiveTick"]);
bundle.send(_networkInterface);
}
}
_lastticktime = System.DateTime.Now;
}
}
/*
与服务端握手,与任何一个进程连接之后应该第一时间进行握手
*/
public void hello()
{
Bundle bundle = new Bundle();
if(currserver == "loginapp")
bundle.newMessage(Message.messages["Loginapp_hello"]);
else
bundle.newMessage(Message.messages["Baseapp_hello"]);
bundle.writeString(clientVersion);
bundle.writeString(clientScriptVersion);
bundle.writeBlob(_encryptedKey);
bundle.send(_networkInterface);
}
/*
握手之后服务端的回调
*/
public void Client_onHelloCB(MemoryStream stream)
{
serverVersion = stream.readString();
serverScriptVersion = stream.readString();
serverProtocolMD5 = stream.readString();
serverEntitydefMD5 = stream.readString();
Int32 ctype = stream.readInt32();
Dbg.DEBUG_MSG("KBEngine::Client_onHelloCB: verInfo(" + serverVersion
+ "), scriptVersion("+ serverScriptVersion + "), srvProtocolMD5("+ serverProtocolMD5
+ "), srvEntitydefMD5("+ serverEntitydefMD5 + "), + ctype(" + ctype + ")!");
onServerDigest();
if(currserver == "baseapp")
{
onLogin_baseapp();
}
else
{
onLogin_loginapp();
}
}
/*
引擎版本不匹配
*/
public void Client_onVersionNotMatch(MemoryStream stream)
{
serverVersion = stream.readString();
Dbg.ERROR_MSG("Client_onVersionNotMatch: verInfo=" + clientVersion + "(server: " + serverVersion + ")");
Event.fireAll("onVersionNotMatch", new object[]{clientVersion, serverVersion});
if(_persistentInofs != null)
_persistentInofs.onVersionNotMatch(clientVersion, serverVersion);
}
/*
脚本版本不匹配
*/
public void Client_onScriptVersionNotMatch(MemoryStream stream)
{
serverScriptVersion = stream.readString();
Dbg.ERROR_MSG("Client_onScriptVersionNotMatch: verInfo=" + clientScriptVersion + "(server: " + serverScriptVersion + ")");
Event.fireAll("onScriptVersionNotMatch", new object[]{clientScriptVersion, serverScriptVersion});
if(_persistentInofs != null)
_persistentInofs.onScriptVersionNotMatch(clientScriptVersion, serverScriptVersion);
}
/*
被服务端踢出
*/
public void Client_onKicked(UInt16 failedcode)
{
Dbg.DEBUG_MSG("Client_onKicked: failedcode=" + failedcode);
Event.fireAll("onKicked", new object[]{failedcode});
}
/*
服务端错误描述导入了
*/
public void Client_onImportServerErrorsDescr(MemoryStream stream)
{
byte[] datas = new byte[stream.wpos - stream.rpos];
Array.Copy(stream.data(), stream.rpos, datas, 0, stream.wpos - stream.rpos);
onImportServerErrorsDescr (stream);
if(_persistentInofs != null)
_persistentInofs.onImportServerErrorsDescr(datas);
}
/*
服务端错误描述导入了
*/
public void onImportServerErrorsDescr(MemoryStream stream)
{
UInt16 size = stream.readUint16();
while(size > 0)
{
size -= 1;
ServerErr e;
e.id = stream.readUint16();
e.name = System.Text.Encoding.UTF8.GetString(stream.readBlob());
e.descr = System.Text.Encoding.UTF8.GetString(stream.readBlob());
serverErrs.Add(e.id, e);
//Dbg.DEBUG_MSG("Client_onImportServerErrorsDescr: id=" + e.id + ", name=" + e.name + ", descr=" + e.descr);
}
}
/*
登录到服务端,必须登录完成loginapp与网关(baseapp),登录流程才算完毕
*/
public void login(string username, string password, byte[] datas)
{
KBEngineApp.app.username = username;
KBEngineApp.app.password = password;
KBEngineApp.app._clientdatas = datas;
KBEngineApp.app.login_loginapp(true);
}
/*
登录到服务端(loginapp), 登录成功后还必须登录到网关(baseapp)登录流程才算完毕
*/
public void login_loginapp(bool noconnect)
{
if(noconnect)
{
reset();
_networkInterface.connectTo(_args.ip, _args.port, onConnectTo_loginapp_callback, null);
}
else
{
Dbg.DEBUG_MSG("KBEngine::login_loginapp(): send login! username=" + username);
Bundle bundle = new Bundle();
bundle.newMessage(Message.messages["Loginapp_login"]);
bundle.writeInt8((sbyte)_args.clientType); // clientType
bundle.writeBlob(KBEngineApp.app._clientdatas);
bundle.writeString(username);
bundle.writeString(password);
bundle.send(_networkInterface);
}
}
private void onConnectTo_loginapp_callback(string ip, int port, bool success, object userData)
{
if(!success)
{
Dbg.ERROR_MSG(string.Format("KBEngine::login_loginapp(): connect {0}:{1} is error!", ip, port));
return;
}
currserver = "loginapp";
currstate = "login";
Dbg.DEBUG_MSG(string.Format("KBEngine::login_loginapp(): connect {0}:{1} is success!", ip, port));
hello();
}
private void onLogin_loginapp()
{
if(!loginappMessageImported_)
{
var bundle = new Bundle();
bundle.newMessage(Message.messages["Loginapp_importClientMessages"]);
bundle.send(_networkInterface);
Dbg.DEBUG_MSG("KBEngine::onLogin_loginapp: send importClientMessages ...");
Event.fireAll("Loginapp_importClientMessages", new object[]{});
}
else
{
onImportClientMessagesCompleted();
}
}
/*
登录到服务端,登录到网关(baseapp)
*/
public void login_baseapp(bool noconnect)
{
if(noconnect)
{
Event.fireAll("login_baseapp", new object[]{});
_networkInterface.reset();
_networkInterface = new NetworkInterface();
_networkInterface.connectTo(baseappIP, baseappPort, onConnectTo_baseapp_callback, null);
}
else
{
Bundle bundle = new Bundle();
bundle.newMessage(Message.messages["Baseapp_loginGateway"]);
bundle.writeString(username);
bundle.writeString(password);
bundle.send(_networkInterface);
}
}
private void onConnectTo_baseapp_callback(string ip, int port, bool success, object userData)
{
if(!success)
{
Dbg.ERROR_MSG(string.Format("KBEngine::login_baseapp(): connect {0}:{1} is error!", ip, port));
return;
}
currserver = "baseapp";
currstate = "";
Dbg.DEBUG_MSG(string.Format("KBEngine::login_baseapp(): connect {0}:{1} is successfully!", ip, port));
hello();
}
private void onLogin_baseapp()
{
if(!baseappMessageImported_)
{
var bundle = new Bundle();
bundle.newMessage(Message.messages["Baseapp_importClientMessages"]);
bundle.send(_networkInterface);
Dbg.DEBUG_MSG("KBEngine::onLogin_baseapp: send importClientMessages ...");
Event.fireAll("Baseapp_importClientMessages", new object[]{});
}
else
{
onImportClientMessagesCompleted();
}
}
/*
重登录到网关(baseapp)
一些移动类应用容易掉线,可以使用该功能快速的重新与服务端建立通信
*/
public void relogin_baseapp()
{
Event.fireAll("onRelogin_baseapp", new object[]{});
_networkInterface.connectTo(baseappIP, baseappPort, onReConnectTo_baseapp_callback, null);
}
private void onReConnectTo_baseapp_callback(string ip, int port, bool success, object userData)
{
if(!success)
{
Dbg.ERROR_MSG(string.Format("KBEngine::relogin_baseapp(): connect {0}:{1} is error!", ip, port));
return;
}
Dbg.DEBUG_MSG(string.Format("KBEngine::relogin_baseapp(): connect {0}:{1} is successfully!", ip, port));
Bundle bundle = new Bundle();
bundle.newMessage(Message.messages["Baseapp_reLoginGateway"]);
bundle.writeString(username);
bundle.writeString(password);
bundle.writeUint64(entity_uuid);
bundle.writeInt32(entity_id);
bundle.send(_networkInterface);
}
/*
从二进制流导入消息协议
*/
public bool importMessagesFromMemoryStream(byte[] loginapp_clientMessages, byte[] baseapp_clientMessages, byte[] entitydefMessages, byte[] serverErrorsDescr)
{
resetMessages();
loadingLocalMessages_ = true;
MemoryStream stream = new MemoryStream();
stream.append(loginapp_clientMessages, (UInt32)0, (UInt32)loginapp_clientMessages.Length);
currserver = "loginapp";
onImportClientMessages(stream);
stream = new MemoryStream();
stream.append(baseapp_clientMessages, (UInt32)0, (UInt32)baseapp_clientMessages.Length);
currserver = "baseapp";
onImportClientMessages(stream);
currserver = "loginapp";
stream = new MemoryStream();
stream.append(serverErrorsDescr, (UInt32)0, (UInt32)serverErrorsDescr.Length);
onImportServerErrorsDescr(stream);
stream = new MemoryStream();
stream.append(entitydefMessages, (UInt32)0, (UInt32)entitydefMessages.Length);
onImportClientEntityDef(stream);
loadingLocalMessages_ = false;
loginappMessageImported_ = true;
baseappMessageImported_ = true;
entitydefImported_ = true;
isImportServerErrorsDescr_ = true;
currserver = "";
Dbg.DEBUG_MSG("KBEngine::importMessagesFromMemoryStream(): is successfully!");
return true;
}
/*
从二进制流导入消息协议完毕了
*/
private void onImportClientMessagesCompleted()
{
Dbg.DEBUG_MSG("KBEngine::onImportClientMessagesCompleted: successfully! currserver=" +
currserver + ", currstate=" + currstate);
if(currserver == "loginapp")
{
if(!isImportServerErrorsDescr_ && !loadingLocalMessages_)
{
Dbg.DEBUG_MSG("KBEngine::onImportClientMessagesCompleted(): send importServerErrorsDescr!");
isImportServerErrorsDescr_ = true;
Bundle bundle = new Bundle();
bundle.newMessage(Message.messages["Loginapp_importServerErrorsDescr"]);
bundle.send(_networkInterface);
}
if(currstate == "login")
{
login_loginapp(false);
}
else if(currstate == "autoimport")
{
}
else if(currstate == "resetpassword")
{
resetpassword_loginapp(false);
}
else if(currstate == "createAccount")
{
createAccount_loginapp(false);
}
else{
}
loginappMessageImported_ = true;
}
else
{
baseappMessageImported_ = true;
if(!entitydefImported_ && !loadingLocalMessages_)
{
Dbg.DEBUG_MSG("KBEngine::onImportClientMessagesCompleted: send importEntityDef(" + entitydefImported_ + ") ...");
Bundle bundle = new Bundle();
bundle.newMessage(Message.messages["Baseapp_importClientEntityDef"]);
bundle.send(_networkInterface);
Event.fireAll("Baseapp_importClientEntityDef", new object[]{});
}
else
{
onImportEntityDefCompleted();
}
}
}
/*
从二进制流创建entitydef支持的数据类型
*/
public void createDataTypeFromStream(MemoryStream stream, bool canprint)
{
UInt16 utype = stream.readUint16();
string name = stream.readString();
string valname = stream.readString();
//if(canprint)
// Dbg.DEBUG_MSG("KBEngine::Client_onImportClientEntityDef: importAlias(" + name + ":" + valname + ")!");
if(valname == "FIXED_DICT")
{
KBEDATATYPE_FIXED_DICT datatype = new KBEDATATYPE_FIXED_DICT();
Byte keysize = stream.readUint8();
datatype.implementedBy = stream.readString();
while(keysize > 0)
{
keysize--;
string keyname = stream.readString();
UInt16 keyutype = stream.readUint16();
datatype.dicttype[keyname] = keyutype;
};
EntityDef.datatypes[name] = datatype;
}
else if(valname == "ARRAY")
{
UInt16 uitemtype = stream.readUint16();
KBEDATATYPE_ARRAY datatype = new KBEDATATYPE_ARRAY();
datatype.vtype = uitemtype;
EntityDef.datatypes[name] = datatype;
}
else
{
KBEDATATYPE_BASE val = null;
EntityDef.datatypes.TryGetValue(valname, out val);
EntityDef.datatypes[name] = val;
}
EntityDef.iddatatypes[utype] = EntityDef.datatypes[name];
EntityDef.datatype2id[name] = EntityDef.datatype2id[valname];
}
public void Client_onImportClientEntityDef(MemoryStream stream)
{
byte[] datas = new byte[stream.wpos - stream.rpos];
Array.Copy (stream.data (), stream.rpos, datas, 0, stream.wpos - stream.rpos);
onImportClientEntityDef (stream);
if(_persistentInofs != null)
_persistentInofs.onImportClientEntityDef(datas);
}
public void onImportClientEntityDef(MemoryStream stream)
{
UInt16 aliassize = stream.readUint16();
Dbg.DEBUG_MSG("KBEngine::Client_onImportClientEntityDef: importAlias(size=" + aliassize + ")!");
while(aliassize > 0)
{
aliassize--;
createDataTypeFromStream(stream, true);
};
foreach(string datatype in EntityDef.datatypes.Keys)
{
if(EntityDef.datatypes[datatype] != null)
{
EntityDef.datatypes[datatype].bind();
}
}
while(stream.length() > 0)
{
string scriptmethod_name = stream.readString();
UInt16 scriptUtype = stream.readUint16();
UInt16 propertysize = stream.readUint16();
UInt16 methodsize = stream.readUint16();
UInt16 base_methodsize = stream.readUint16();
UInt16 cell_methodsize = stream.readUint16();
Dbg.DEBUG_MSG("KBEngine::Client_onImportClientEntityDef: import(" + scriptmethod_name + "), propertys(" + propertysize + "), " +
"clientMethods(" + methodsize + "), baseMethods(" + base_methodsize + "), cellMethods(" + cell_methodsize + ")!");
ScriptModule module = new ScriptModule(scriptmethod_name);
EntityDef.moduledefs[scriptmethod_name] = module;
EntityDef.idmoduledefs[scriptUtype] = module;
Type Class = module.script;
while(propertysize > 0)
{
propertysize--;
UInt16 properUtype = stream.readUint16();
UInt32 properFlags = stream.readUint32();
Int16 ialiasID = stream.readInt16();
string name = stream.readString();
string defaultValStr = stream.readString();
KBEDATATYPE_BASE utype = EntityDef.iddatatypes[stream.readUint16()];
System.Reflection.MethodInfo setmethod = null;
if(Class != null)
{
try{
setmethod = Class.GetMethod("set_" + name);
}
catch (Exception e)
{
string err = "KBEngine::Client_onImportClientEntityDef: " +
scriptmethod_name + ".set_" + name + ", error=" + e.ToString();
throw new Exception(err);
}
}
Property savedata = new Property();
savedata.name = name;
savedata.utype = utype;
savedata.properUtype = properUtype;
savedata.aliasID = ialiasID;
savedata.defaultValStr = defaultValStr;
savedata.setmethod = setmethod;
savedata.val = savedata.utype.parseDefaultValStr(savedata.defaultValStr);
module.propertys[name] = savedata;
if(ialiasID >= 0)
{
module.usePropertyDescrAlias = true;
module.idpropertys[(UInt16)ialiasID] = savedata;
}
else
{
module.usePropertyDescrAlias = false;
module.idpropertys[properUtype] = savedata;
}
//Dbg.DEBUG_MSG("KBEngine::Client_onImportClientEntityDef: add(" + scriptmethod_name + "), property(" + name + "/" + properUtype + ").");
};
while(methodsize > 0)
{
methodsize--;
UInt16 methodUtype = stream.readUint16();
Int16 ialiasID = stream.readInt16();
string name = stream.readString();
Byte argssize = stream.readUint8();
List<KBEDATATYPE_BASE> args = new List<KBEDATATYPE_BASE>();
while(argssize > 0)
{
argssize--;
args.Add(EntityDef.iddatatypes[stream.readUint16()]);
};
Method savedata = new Method();
savedata.name = name;
savedata.methodUtype = methodUtype;
savedata.aliasID = ialiasID;
savedata.args = args;
if(Class != null)
{
try{
savedata.handler = Class.GetMethod(name);
}
catch (Exception e)
{
string err = "KBEngine::Client_onImportClientEntityDef: " + scriptmethod_name + "." + name + ", error=" + e.ToString();
throw new Exception(err);
}
}
module.methods[name] = savedata;
if(ialiasID >= 0)
{
module.useMethodDescrAlias = true;
module.idmethods[(UInt16)ialiasID] = savedata;
}
else
{
module.useMethodDescrAlias = false;
module.idmethods[methodUtype] = savedata;
}
//Dbg.DEBUG_MSG("KBEngine::Client_onImportClientEntityDef: add(" + scriptmethod_name + "), method(" + name + ").");
};
while(base_methodsize > 0)
{
base_methodsize--;
UInt16 methodUtype = stream.readUint16();
Int16 ialiasID = stream.readInt16();
string name = stream.readString();
Byte argssize = stream.readUint8();
List<KBEDATATYPE_BASE> args = new List<KBEDATATYPE_BASE>();
while(argssize > 0)
{
argssize--;
args.Add(EntityDef.iddatatypes[stream.readUint16()]);
};
Method savedata = new Method();
savedata.name = name;
savedata.methodUtype = methodUtype;
savedata.aliasID = ialiasID;
savedata.args = args;
module.base_methods[name] = savedata;
module.idbase_methods[methodUtype] = savedata;
//Dbg.DEBUG_MSG("KBEngine::Client_onImportClientEntityDef: add(" + scriptmethod_name + "), base_method(" + name + ").");
};
while(cell_methodsize > 0)
{
cell_methodsize--;
UInt16 methodUtype = stream.readUint16();
Int16 ialiasID = stream.readInt16();
string name = stream.readString();
Byte argssize = stream.readUint8();
List<KBEDATATYPE_BASE> args = new List<KBEDATATYPE_BASE>();
while(argssize > 0)
{
argssize--;
args.Add(EntityDef.iddatatypes[stream.readUint16()]);
};
Method savedata = new Method();
savedata.name = name;
savedata.methodUtype = methodUtype;
savedata.aliasID = ialiasID;
savedata.args = args;
module.cell_methods[name] = savedata;
module.idcell_methods[methodUtype] = savedata;
//Dbg.DEBUG_MSG("KBEngine::Client_onImportClientEntityDef: add(" + scriptmethod_name + "), cell_method(" + name + ").");
};
if(module.script == null)
{
Dbg.ERROR_MSG("KBEngine::Client_onImportClientEntityDef: module(" + scriptmethod_name + ") not found!");
}
foreach(string name in module.methods.Keys)
{
// Method infos = module.methods[name];
if(module.script != null && module.script.GetMethod(name) == null)
{
Dbg.WARNING_MSG(scriptmethod_name + "(" + module.script + "):: method(" + name + ") no implement!");
}
};
}
onImportEntityDefCompleted();
}
private void onImportEntityDefCompleted()
{
Dbg.DEBUG_MSG("KBEngine::onImportEntityDefCompleted: successfully!");
entitydefImported_ = true;
if(!loadingLocalMessages_)
login_baseapp(false);
}
/*
通过错误id得到错误描述
*/
public string serverErr(UInt16 id)
{
ServerErr e;
if(!serverErrs.TryGetValue(id, out e))
{
return "";
}