xyz.py 5.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. # coding: utf-8
  2. import typing
  3. from math import acos
  4. from math import degrees
  5. from math import sqrt
  6. from synergine2.exceptions import SynergineException
  7. from synergine2.share import shared
  8. from synergine2.simulation import Subject
  9. """
  10. Positions are exprimed as tuple: (x, y, z) Considering start point at top left:
  11. Z
  12. #
  13. #
  14. #
  15. #-------------> X
  16. |.
  17. | .
  18. | .
  19. |
  20. Y
  21. """
  22. COLLECTION_XYZ = 'COLLECTION_XYZ'
  23. NORTH = 11
  24. NORTH_EST = 12
  25. EST = 15
  26. SOUTH_EST = 18
  27. SOUTH = 17
  28. SOUTH_WEST = 16
  29. WEST = 13
  30. NORTH_WEST = 10
  31. DIRECTIONS = (
  32. NORTH,
  33. NORTH_EST,
  34. EST,
  35. SOUTH_EST,
  36. SOUTH,
  37. SOUTH_WEST,
  38. WEST,
  39. NORTH_WEST,
  40. )
  41. DIRECTION_FROM_NORTH_DEGREES = {
  42. (0, 22.5): NORTH,
  43. (22.5, 67): NORTH_EST,
  44. (67, 112.5): EST,
  45. (112.5, 157.5): SOUTH_EST,
  46. (157.5, 202.5): SOUTH,
  47. (202.5, 247.5): SOUTH_WEST,
  48. (247.5, 292.5): WEST,
  49. (292.5, 337.5): NORTH_WEST,
  50. (337.5, 360): NORTH,
  51. (337.5, 0): NORTH
  52. }
  53. DIRECTION_SLIGHTLY = {
  54. NORTH: (NORTH_WEST, NORTH, NORTH_EST),
  55. NORTH_EST: (NORTH, NORTH_EST, EST),
  56. EST: (NORTH_EST, EST, SOUTH_EST),
  57. SOUTH_EST: (EST, SOUTH_EST, SOUTH),
  58. SOUTH: (SOUTH_EST, SOUTH, SOUTH_WEST),
  59. SOUTH_WEST: (SOUTH, SOUTH_WEST, WEST),
  60. WEST: (SOUTH_WEST, WEST, NORTH_WEST),
  61. NORTH_WEST: (WEST, NORTH_WEST, NORTH),
  62. }
  63. DIRECTION_MODIFIERS = {
  64. NORTH_WEST: (-1, -1, 0),
  65. NORTH: (0, -1, 0),
  66. NORTH_EST: (1, -1, 0),
  67. WEST: (-1, 0, 0),
  68. EST: (1, 0, 0),
  69. SOUTH_WEST: (-1, 1, 0),
  70. SOUTH: (0, 1, 0),
  71. SOUTH_EST: (1, 1, 0),
  72. }
  73. class XYZException(SynergineException):
  74. pass
  75. class PositionNotPossible(XYZException):
  76. pass
  77. def get_degree_from_north(a, b):
  78. if a == b:
  79. return 0
  80. ax, ay = a[0], a[1]
  81. bx, by = b[0], b[1]
  82. Dx, Dy = ax, ay - 1
  83. ab = sqrt((bx - ax) ** 2 + (by - ay) ** 2)
  84. aD = sqrt((Dx - ax) ** 2 + (Dy - ay) ** 2)
  85. Db = sqrt((bx - Dx) ** 2 + (by - Dy) ** 2)
  86. degs = degrees(acos((ab ** 2 + aD ** 2 - Db ** 2) / (2 * ab * aD)))
  87. if bx < ax:
  88. return 360 - degs
  89. return degs
  90. class XYZSubjectMixinMetaClass(type):
  91. def __init__(cls, name, parents, attribs):
  92. super().__init__(name, parents, attribs)
  93. collections = getattr(cls, "collections", [])
  94. if COLLECTION_XYZ not in collections:
  95. collections.append(COLLECTION_XYZ)
  96. class XYZSubjectMixin(object, metaclass=XYZSubjectMixinMetaClass):
  97. position = shared.create(['{id}', 'counter'], (0, 0, 0))
  98. def __init__(self, *args, **kwargs):
  99. """
  100. :param position: tuple with (x, y, z)
  101. """
  102. position = None
  103. try:
  104. position = kwargs.pop('position')
  105. except KeyError:
  106. pass
  107. self.previous_direction = None # TODO: shared
  108. super().__init__(*args, **kwargs)
  109. if position:
  110. self.position = position
  111. class ProximityMixin(object):
  112. distance = 1
  113. feel_collections = [COLLECTION_XYZ]
  114. direction_round_decimals = 0
  115. distance_round_decimals = 2
  116. def have_to_check_position_is_possible(self) -> bool:
  117. return True
  118. def get_for_position(
  119. self,
  120. position,
  121. simulation: 'XYZSimulation',
  122. exclude_subject: Subject=None,
  123. ):
  124. subjects = []
  125. for feel_collection in self.feel_collections:
  126. # TODO: Optimiser en calculant directement les positions alentours et
  127. # en regardant si elles sont occupés dans subjects.xyz par un subject
  128. # etant dans fell_collection
  129. for subject_id in simulation.collections.get(feel_collection, []):
  130. subject = simulation.get_or_create_subject(subject_id)
  131. if subject.id == exclude_subject.id:
  132. continue
  133. if self.have_to_check_position_is_possible() and not simulation.is_possible_position(subject.position):
  134. continue
  135. distance = round(
  136. self.get_distance_of(
  137. position=position,
  138. subject=subject,
  139. ),
  140. self.distance_round_decimals,
  141. )
  142. if distance <= self.distance and self.acceptable_subject(subject):
  143. direction = round(
  144. get_degree_from_north(
  145. position,
  146. subject.position,
  147. ),
  148. self.direction_round_decimals,
  149. )
  150. subjects.append({
  151. 'subject_id': subject.id,
  152. 'direction': direction,
  153. 'distance': distance,
  154. })
  155. return subjects
  156. @classmethod
  157. def get_distance_of(cls, position, subject: XYZSubjectMixin):
  158. from synergine2_xyz.utils import get_distance_between_points # cyclic import
  159. return get_distance_between_points(
  160. position,
  161. subject.position,
  162. )
  163. def acceptable_subject(self, subject: Subject) -> bool:
  164. return True
  165. def get_direction_from_north_degree(degree: float):
  166. for range, direction in DIRECTION_FROM_NORTH_DEGREES.items():
  167. if range[0] <= degree <= range[1]:
  168. return direction
  169. raise Exception('Degree {} out of range ({})'.format(
  170. degree,
  171. DIRECTION_FROM_NORTH_DEGREES,
  172. ))
  173. def get_neighbor_positions(position: typing.Tuple[int, int]) -> typing.List[typing.Tuple[int, int]]:
  174. neighbors = []
  175. for modifier_x, modifier_y, modifier_z in DIRECTION_MODIFIERS.values():
  176. neighbors.append((position[0] + modifier_x, position[1] + modifier_y))
  177. return neighbors