選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

96 行
1.8 KiB

  1. use glc::vector::Vector3f;
  2. use serde::{Deserialize, Serialize};
  3. use specs::{
  4. error::NoError,
  5. saveload::{ConvertSaveload, Marker},
  6. Component, Entity, HashMapStorage,
  7. };
  8. #[derive(Clone, Debug, Default, Serialize, Deserialize)]
  9. pub struct Player {
  10. index: usize,
  11. color: Vector3f,
  12. }
  13. #[derive(Copy, Clone, Debug)]
  14. pub struct Owned {
  15. owner: Entity,
  16. }
  17. #[derive(Serialize, Deserialize)]
  18. pub struct OwnedData<M> {
  19. pub owner: M,
  20. }
  21. impl Player {
  22. #[inline]
  23. pub fn new(color: Vector3f) -> Self {
  24. Self {
  25. index: next_index(),
  26. color,
  27. }
  28. }
  29. #[inline]
  30. pub fn index(&self) -> usize {
  31. self.index
  32. }
  33. #[inline]
  34. pub fn color(&self) -> &Vector3f {
  35. &self.color
  36. }
  37. }
  38. impl Component for Player {
  39. type Storage = HashMapStorage<Self>;
  40. }
  41. impl Owned {
  42. pub fn new(owner: Entity) -> Self {
  43. Self { owner }
  44. }
  45. pub fn owner(&self) -> Entity {
  46. self.owner
  47. }
  48. }
  49. impl Component for Owned {
  50. type Storage = HashMapStorage<Self>;
  51. }
  52. impl<M> ConvertSaveload<M> for Owned
  53. where
  54. for<'de> M: Marker + Serialize + Deserialize<'de>,
  55. {
  56. type Data = OwnedData<M>;
  57. type Error = NoError;
  58. fn convert_into<F>(&self, mut ids: F) -> Result<Self::Data, Self::Error>
  59. where
  60. F: FnMut(Entity) -> Option<M>,
  61. {
  62. let owner = ids(self.owner).unwrap();
  63. Ok(OwnedData { owner })
  64. }
  65. fn convert_from<F>(data: Self::Data, mut ids: F) -> Result<Self, Self::Error>
  66. where
  67. F: FnMut(M) -> Option<Entity>,
  68. {
  69. let owner = ids(data.owner).unwrap();
  70. Ok(Owned { owner })
  71. }
  72. }
  73. fn next_index() -> usize {
  74. use std::sync::atomic::{AtomicUsize, Ordering};
  75. static NEXT_INDEX: AtomicUsize = AtomicUsize::new(0);
  76. NEXT_INDEX.fetch_add(1, Ordering::Relaxed)
  77. }