PlayerPackage.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace Island.StandardLib.Storage
  6. {
  7. public class PlayerPackage : IStorable
  8. {
  9. public static RunDevice Device { get; private set; }
  10. static Dictionary<int, AbstractItemBehavior> ItemBehaviors;
  11. static AbstractController Controller;
  12. public static void DefineItemBehaviors(AbstractController controller, RunDevice device, params AbstractItemBehavior[] behaviors)
  13. {
  14. Device = device;
  15. Controller = controller;
  16. if (ItemBehaviors != null)
  17. throw new Exception("ItemBehavior is already defined.");
  18. ItemBehaviors = new Dictionary<int, AbstractItemBehavior>();
  19. foreach (AbstractItemBehavior behavior in behaviors)
  20. {
  21. if (ItemBehaviors.ContainsKey(behavior.Id))
  22. throw new Exception($"Redefined ItemBehavior, Id = {behavior.Id}");
  23. ItemBehaviors.Add(behavior.Id, behavior);
  24. }
  25. }
  26. public static AbstractItemBehavior GetItemBehavior(int id)
  27. {
  28. if (ItemBehaviors == null)
  29. throw new Exception("ItemBehavior is undefined. Use DefineItemBehaviors(...) to set behaviors first.");
  30. if (ItemBehaviors.TryGetValue(id, out AbstractItemBehavior behavior))
  31. return behavior;
  32. throw new Exception($"GetItemBehavior() Use undefined item behavior Id = {id}");
  33. }
  34. public class ItemData : IStorable
  35. {
  36. public int DataType;
  37. public byte[] Data;
  38. public MultData DataVisitor
  39. {
  40. get => new MultData(Data);
  41. set => Data = value.Data;
  42. }
  43. public ItemData()
  44. {
  45. DataType = 0;
  46. Data = new byte[0];
  47. }
  48. public ItemData(int dataType, MultData data)
  49. {
  50. DataType = dataType;
  51. Data = data.Data;
  52. }
  53. public ItemData(object data, int iStorageType = 10)
  54. {
  55. if (data is MultData)
  56. {
  57. DataVisitor = (MultData)data;
  58. DataType = 7;
  59. }
  60. else if (data is byte[])
  61. {
  62. DataVisitor = new MultData((byte[])data);
  63. DataType = 7;
  64. }
  65. else if (data is int)
  66. {
  67. DataVisitor = new MultData((int)data);
  68. DataType = 1;
  69. }
  70. else if (data is float)
  71. {
  72. DataVisitor = new MultData((float)data);
  73. DataType = 2;
  74. }
  75. else if (data is string)
  76. {
  77. DataVisitor = new MultData((string)data);
  78. DataType = 0;
  79. }
  80. else if (data is long)
  81. {
  82. DataVisitor = new MultData((long)data);
  83. DataType = 3;
  84. }
  85. else if (data is uint)
  86. {
  87. DataVisitor = new MultData((uint)data);
  88. DataType = 5;
  89. }
  90. else if (data is ulong)
  91. {
  92. DataVisitor = new MultData((ulong)data);
  93. DataType = 6;
  94. }
  95. else if (data is double)
  96. {
  97. DataVisitor = new MultData((double)data);
  98. DataType = 4;
  99. }
  100. else if (data is IStorable)
  101. {
  102. DataVisitor = new MultData((IStorable)data);
  103. DataType = iStorageType;
  104. }
  105. else throw new InvalidCastException();
  106. }
  107. public bool IsString => DataType == 0;
  108. public bool IsInt => DataType == 1;
  109. public bool IsFloat => DataType == 2;
  110. public bool IsLong => DataType == 3;
  111. public bool IsDouble => DataType == 4;
  112. public bool IsUInt => DataType == 5;
  113. public bool IsULong => DataType == 6;
  114. public bool IsByteArray => DataType == 7;
  115. public bool IsIStorable => DataType >= 10;
  116. public T As<T>() where T : IStorable, new()
  117. {
  118. DataStorage ds = new DataStorage(Data);
  119. T t = new T();
  120. t.ReadFromData(ds);
  121. return t;
  122. }
  123. public void SetData<T>(T data) where T : IStorable, new()
  124. {
  125. DataStorage ds = new DataStorage();
  126. data.WriteToData(ds);
  127. Data = ds.Bytes;
  128. }
  129. public void ReadFromData(DataStorage data)
  130. {
  131. data.ReadUncheck(out DataType);
  132. Data = data.Read();
  133. }
  134. public void WriteToData(DataStorage data)
  135. {
  136. data.WriteUncheck(DataType);
  137. data.Write(Data);
  138. }
  139. }
  140. public class Item : IStorable
  141. {
  142. public Item() : this(0, 0) { }
  143. public Item(int typeId, int instanceId, int stackCount = 1, StorableFixedArray<ItemData> data = null)
  144. {
  145. Data = data ?? new StorableFixedArray<ItemData>();
  146. TypeId = typeId;
  147. InstanceId = instanceId;
  148. StackCount = stackCount;
  149. }
  150. public int TypeId;
  151. public int InstanceId;
  152. public int StackCount;
  153. public StorableFixedArray<ItemData> Data;
  154. public ItemData this[int index] => Data[index];
  155. public int Length => Data.Length;
  156. public void ConsumeOne(ConnectionPlayerBase who, PlayerPackage package)
  157. {
  158. StackCount--;
  159. ServerSetModify(who, package);
  160. }
  161. public void ServerSetModify(ConnectionPlayerBase who, PlayerPackage package)
  162. {
  163. if (Device == RunDevice.Client) throw new Exception("SetModify only can use in Server mode.");
  164. if (StackCount <= 0)
  165. {
  166. lock (package.objects) package.objects.Remove(InstanceId);
  167. Controller.OnServerSendDeleteCommand(who, InstanceId);
  168. }
  169. else Controller.OnServerSendModifyCommand(who, this);
  170. }
  171. internal void ClientApplyChange(Item item)
  172. {
  173. TypeId = item.TypeId;
  174. StackCount = item.StackCount;
  175. Data = item.Data;
  176. }
  177. public bool CanUse => GetItemBehavior(TypeId).CanUse(this);
  178. public void ServerUse(ConnectionPlayerBase who)
  179. {
  180. if (!CanUse) return;
  181. GetItemBehavior(TypeId).ServerUse(who, this);
  182. }
  183. public void ClientUse()
  184. {
  185. if (!CanUse) return;
  186. GetItemBehavior(TypeId).ClientUse(this);
  187. Controller.OnClientSendUseCommand(InstanceId);
  188. }
  189. public void WriteToData(DataStorage data)
  190. {
  191. data.WriteUncheck(TypeId);
  192. data.WriteUncheck(InstanceId);
  193. data.WriteUncheck(StackCount);
  194. data.Write(Data);
  195. }
  196. public void ReadFromData(DataStorage data)
  197. {
  198. data.ReadUncheck(out TypeId);
  199. data.ReadUncheck(out InstanceId);
  200. data.ReadUncheck(out StackCount);
  201. data.Read(out Data);
  202. }
  203. }
  204. public void OnServerReceiveUseCommand(ConnectionPlayerBase who, int instanceId)
  205. {
  206. Item item = FindItem(instanceId);
  207. if (item == null)
  208. Logger.Log(LogLevel.Error, $"Player {who.Nick} trying to use a nonexists item. InstanceId {instanceId}");
  209. else item.ServerUse(who);
  210. }
  211. public abstract class AbstractItemBehavior
  212. {
  213. public abstract int Id { get; }
  214. public abstract void ServerUse(ConnectionPlayerBase who, Item item);
  215. public abstract void ClientUse(Item item);
  216. public abstract bool CanUse(Item item);
  217. public abstract int CanStack(Item root, Item append);
  218. }
  219. public abstract class AbstractUnstackableItemBehavior : AbstractItemBehavior
  220. {
  221. public override int CanStack(Item root, Item append) => 0;
  222. }
  223. public abstract class AbstractStackableItemBehavior : AbstractItemBehavior
  224. {
  225. public abstract int MaxStackSize { get; }
  226. protected virtual bool CompareStackCondition(Item root, Item append)
  227. {
  228. return root.Data.GetBytes().ByteEquals(append.Data.GetBytes());
  229. }
  230. public override int CanStack(Item root, Item append)
  231. {
  232. if (!CompareStackCondition(root, append)) return 0;
  233. return MaxStackSize - root.StackCount;
  234. }
  235. }
  236. public abstract class AbstractController
  237. {
  238. public abstract void OnServerSendModifyCommand(ConnectionPlayerBase who, Item changedItem);
  239. public abstract void OnServerSendDeleteCommand(ConnectionPlayerBase who, int itemInstanceId);
  240. public abstract void OnServerSendChangeMaxItemSizeCommand(ConnectionPlayerBase who, int newMaxItemSizeValue);
  241. public abstract void OnClientSendUseCommand(int itemInstanceId);
  242. }
  243. public PlayerPackage() : this(30) { }
  244. public PlayerPackage(int maxItemSize)
  245. {
  246. if (ItemBehaviors == null)
  247. throw new Exception("ItemBehavior is undefined. Use DefineItemBehaviors(...) to set behaviors first.");
  248. objects = new StorableDictionary<SInt, Item>();
  249. idAllocator = 0;
  250. this.maxItemSize = maxItemSize;
  251. }
  252. public StorableDictionary<SInt, Item> objects;
  253. int maxItemSize;
  254. int idAllocator;
  255. public void SetMaxItemSize(int newValue, ConnectionPlayerBase who = null)
  256. {
  257. if (Device == RunDevice.Server)
  258. {
  259. if (maxItemSize == newValue) return;
  260. if (maxItemSize > newValue) throw new ArgumentException("MaxItemSize: new value must be upper than current value.");
  261. maxItemSize = newValue;
  262. Controller.OnServerSendChangeMaxItemSizeCommand(who, newValue);
  263. }
  264. else
  265. {
  266. maxItemSize = newValue;
  267. }
  268. }
  269. public int MaxItemSize => maxItemSize;
  270. public int ItemSpace
  271. {
  272. get
  273. {
  274. lock (objects)
  275. return objects.Count;
  276. }
  277. }
  278. public int EmptySpace => maxItemSize - ItemSpace;
  279. public int CreateItem(ConnectionPlayerBase who, int typeId, int stackCount = 1, StorableFixedArray<ItemData> data = null)
  280. {
  281. if (Device == RunDevice.Client) throw new Exception("CreateItem only can use in Server mode.");
  282. Item thisObject = new Item(typeId, -1, stackCount, data == null ? null : data.MemoryCopy());
  283. lock (objects)
  284. {
  285. foreach (var t in objects)
  286. {
  287. if (t.Value.TypeId == thisObject.TypeId)
  288. {
  289. int canStackCount = GetItemBehavior(t.Value.TypeId).CanStack(t.Value, thisObject);
  290. canStackCount = canStackCount <= thisObject.StackCount ? canStackCount : thisObject.StackCount;
  291. if (canStackCount > 0)
  292. {
  293. t.Value.StackCount += canStackCount;
  294. if (who != null)
  295. t.Value.ServerSetModify(who, this);
  296. thisObject.StackCount -= canStackCount;
  297. }
  298. if (thisObject.StackCount == 0)
  299. {
  300. thisObject = null;
  301. break;
  302. }
  303. }
  304. }
  305. if (thisObject != null)
  306. {
  307. int singleStk = GetItemBehavior(typeId).CanStack(new Item(typeId, 0, 0, data), new Item(typeId, 0, thisObject.StackCount, data));
  308. do
  309. {
  310. if (objects.Count >= maxItemSize)
  311. return thisObject.StackCount;
  312. int curStack = thisObject.StackCount > singleStk ? singleStk : thisObject.StackCount;
  313. Item curItem = new Item(typeId, idAllocator++, curStack, data);
  314. objects.Add(curItem.InstanceId, curItem);
  315. if (who != null)
  316. curItem.ServerSetModify(who, this);
  317. thisObject.StackCount -= curStack;
  318. }
  319. while (thisObject.StackCount > 0);
  320. }
  321. }
  322. return 0;
  323. }
  324. public Item FindItem(int instanceId)
  325. {
  326. if (objects.TryGetValue(instanceId, out Item item))
  327. return item;
  328. return null;
  329. }
  330. public int CreateItem(ConnectionPlayerBase who, Item copyItem)
  331. {
  332. return CreateItem(who, copyItem.TypeId, copyItem.StackCount, copyItem.Data);
  333. }
  334. public void DeleteItemWithInstance(ConnectionPlayerBase who, int itemInstanceId, int stackCount = 1)
  335. {
  336. if (Device == RunDevice.Client) throw new Exception("DeleteItem only can use in Server mode.");
  337. lock (objects)
  338. {
  339. if (objects.TryGetValue(itemInstanceId, out Item it))
  340. {
  341. if (it.StackCount > stackCount)
  342. {
  343. it.StackCount -= stackCount;
  344. it.ServerSetModify(who, this);
  345. }
  346. else if (it.StackCount == stackCount)
  347. {
  348. objects.Remove(itemInstanceId);
  349. Controller.OnServerSendDeleteCommand(who, itemInstanceId);
  350. }
  351. else throw new Exception($"Trying delete InstanceId = {itemInstanceId} with StackCount = {stackCount}, no such stack count.");
  352. }
  353. else throw new Exception($"The InstanceId = {itemInstanceId} is not founded.");
  354. }
  355. }
  356. public void DeleteItemWithType(ConnectionPlayerBase who, int typeId, int stackCount = 1, Func<Item, bool> checker = null)
  357. {
  358. if (Device == RunDevice.Client) throw new Exception("DeleteItem only can use in Server mode.");
  359. lock (objects)
  360. {
  361. List<int> preDeletes = new List<int>();
  362. foreach (var obj in objects)
  363. {
  364. if (obj.Value.TypeId == typeId)
  365. {
  366. if (checker != null)
  367. {
  368. if (!checker(obj.Value))
  369. continue;
  370. }
  371. if (obj.Value.StackCount > stackCount)
  372. {
  373. obj.Value.StackCount -= stackCount;
  374. stackCount = 0;
  375. if (who != null)
  376. obj.Value.ServerSetModify(who, this);
  377. break;
  378. }
  379. else
  380. {
  381. stackCount -= obj.Value.StackCount;
  382. preDeletes.Add(obj.Key);
  383. if (who != null)
  384. Controller.OnServerSendDeleteCommand(who, obj.Key);
  385. if (stackCount == 0) break;
  386. }
  387. }
  388. }
  389. if (stackCount != 0)
  390. throw new Exception("DeleteItem: FATAL ERROR: Count is not enough, but still maybe reduce some stack count, that already caught item lost.");
  391. for (int i = 0; i < preDeletes.Count; i++)
  392. objects.Remove(preDeletes[i]);
  393. }
  394. }
  395. public bool CheckItems(int typeId, int stackCount = 1, Func<Item, bool> checker = null)
  396. {
  397. lock (objects)
  398. {
  399. foreach (var obj in objects)
  400. {
  401. if (obj.Value.TypeId == typeId)
  402. {
  403. if (checker != null)
  404. {
  405. if (!checker(obj.Value))
  406. continue;
  407. }
  408. if (obj.Value.StackCount > stackCount)
  409. {
  410. stackCount = 0;
  411. break;
  412. }
  413. else
  414. {
  415. stackCount -= obj.Value.StackCount;
  416. if (stackCount == 0) break;
  417. }
  418. }
  419. }
  420. return stackCount == 0;
  421. }
  422. }
  423. public class ItemRequest
  424. {
  425. public struct ItemQueryInfo
  426. {
  427. public ItemQueryInfo(int typeId, int stackCount = 1, Func<Item, bool> checker = null)
  428. {
  429. TypeId = typeId;
  430. StackCount = stackCount;
  431. Checker = checker;
  432. }
  433. public int TypeId { get; private set; }
  434. public int StackCount { get; private set; }
  435. public Func<Item, bool> Checker { get; private set; }
  436. }
  437. ItemQueryInfo[] Requests;
  438. public ItemRequest(params ItemQueryInfo[] infos) => Requests = infos;
  439. public bool CheckIsEnough(PlayerPackage package)
  440. {
  441. bool isEnough = true;
  442. lock (package.objects)
  443. {
  444. for (int i = 0; i < Requests.Length; i++)
  445. isEnough &= package.CheckItems(Requests[i].TypeId, Requests[i].StackCount, Requests[i].Checker);
  446. }
  447. return isEnough;
  448. }
  449. public bool Consume(ConnectionPlayerBase who, PlayerPackage package)
  450. {
  451. lock (package.objects)
  452. {
  453. if (CheckIsEnough(package))
  454. {
  455. for (int i = 0; i < Requests.Length; i++)
  456. package.DeleteItemWithType(who, Requests[i].TypeId, Requests[i].StackCount, Requests[i].Checker);
  457. return true;
  458. }
  459. return false;
  460. }
  461. }
  462. }
  463. public void OnClientReceivedModify(Item changedItem, out Item added)
  464. {
  465. lock (objects)
  466. {
  467. if (objects.TryGetValue(changedItem.InstanceId, out Item item))
  468. {
  469. item.ClientApplyChange(changedItem);
  470. added = null;
  471. }
  472. else
  473. {
  474. objects.Add(changedItem.InstanceId, changedItem);
  475. added = changedItem;
  476. }
  477. }
  478. }
  479. public void OnClientReceivedDelete(int itemInstanceId)
  480. {
  481. lock (objects)
  482. {
  483. if (objects.ContainsKey(itemInstanceId))
  484. objects.Remove(itemInstanceId);
  485. }
  486. }
  487. public void ReadFromData(DataStorage data)
  488. {
  489. data.Read(out idAllocator);
  490. data.Read(out objects);
  491. data.ReadUncheck(out maxItemSize);
  492. }
  493. public void WriteToData(DataStorage data)
  494. {
  495. data.Write(idAllocator);
  496. data.Write(objects);
  497. data.WriteUncheck(maxItemSize);
  498. }
  499. }
  500. }