models.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals, division, print_function
  3. import os
  4. from math import radians, degrees, sin, cos, asin, atan2, sqrt, ceil
  5. from django.db import models
  6. from django.conf import settings
  7. from django.core.exceptions import ValidationError
  8. from django.core.validators import MinValueValidator, MaxValueValidator
  9. from django.core.urlresolvers import reverse
  10. from django.utils.encoding import python_2_unicode_compatible
  11. from django.utils.translation import ugettext_lazy as _
  12. from .tasks import generate_tiles
  13. from .utils import makedirs, path_exists
  14. EARTH_RADIUS = 6371009
  15. class Point(models.Model):
  16. """Geographical point, with altitude."""
  17. latitude = models.FloatField(verbose_name=_("latitude"), help_text=_("In degrees"),
  18. validators=[MinValueValidator(-90),
  19. MaxValueValidator(90)])
  20. longitude = models.FloatField(verbose_name=_("longitude"), help_text=_("In degrees"),
  21. validators=[MinValueValidator(-180),
  22. MaxValueValidator(180)])
  23. altitude = models.FloatField(verbose_name=_("altitude"), help_text=_("In meters"),
  24. validators=[MinValueValidator(0.)])
  25. @property
  26. def latitude_rad(self):
  27. return radians(self.latitude)
  28. @property
  29. def longitude_rad(self):
  30. return radians(self.longitude)
  31. @property
  32. def altitude_abs(self):
  33. """Absolute distance to the center of Earth (in a spherical model)"""
  34. return EARTH_RADIUS + self.altitude
  35. def great_angle(self, other):
  36. """Returns the great angle, in radians, between the two given points. The
  37. great angle is the angle formed by the two points when viewed from
  38. the center of the Earth.
  39. """
  40. lon_delta = other.longitude_rad - self.longitude_rad
  41. a = (cos(other.latitude_rad) * sin(lon_delta)) ** 2 \
  42. + (cos(self.latitude_rad) * sin(other.latitude_rad) \
  43. - sin(self.latitude_rad) * cos(other.latitude_rad) * cos(lon_delta)) ** 2
  44. b = sin(self.latitude_rad) * sin(other.latitude_rad) \
  45. + cos(self.latitude_rad) * cos(other.latitude_rad) * cos(lon_delta)
  46. angle = atan2(sqrt(a), b)
  47. return angle
  48. def great_circle_distance(self, other):
  49. """Returns the great circle distance between two points, without taking
  50. into account their altitude. Don't use this to compute
  51. line-of-sight distance, see [line_distance] instead.
  52. """
  53. return EARTH_RADIUS * self.great_angle(other)
  54. def line_distance(self, other):
  55. """Distance of the straight line between two points on Earth, in meters.
  56. Note that this is only useful because we are considering
  57. line-of-sight links, where straight-line distance is the relevant
  58. distance. For arbitrary points on Earth, great-circle distance
  59. would most likely be preferred.
  60. """
  61. delta_lon = other.longitude_rad - self.longitude_rad
  62. # Cosine of the angle between the two points on their great circle.
  63. cos_angle = sin(self.latitude_rad) * sin(other.latitude_rad) \
  64. + cos(self.latitude_rad) * cos(other.latitude_rad) * cos(delta_lon)
  65. # Al-Kashi formula
  66. return sqrt(self.altitude_abs ** 2 \
  67. + other.altitude_abs ** 2 \
  68. - 2 * self.altitude_abs * other.altitude_abs * cos_angle)
  69. def bearing(self, other):
  70. """Bearing, in degrees, between this point and another point."""
  71. delta_lon = other.longitude_rad - self.longitude_rad
  72. y = sin(delta_lon) * cos(other.latitude_rad)
  73. x = cos(self.latitude_rad) * sin(other.latitude_rad) \
  74. - sin(self.latitude_rad) * cos(other.latitude_rad) * cos(delta_lon)
  75. return degrees(atan2(y, x))
  76. def elevation(self, other):
  77. """Elevation, in degrees, between this point and another point."""
  78. d = self.line_distance(other)
  79. sin_elev = (other.altitude_abs ** 2 - self.altitude_abs ** 2 - d ** 2) \
  80. / (2 * self.altitude_abs * d)
  81. return degrees(asin(sin_elev))
  82. class Meta:
  83. abstract = True
  84. @python_2_unicode_compatible
  85. class ReferencePoint(Point):
  86. """Reference point, to be used"""
  87. name = models.CharField(verbose_name=_("name"), max_length=255,
  88. help_text=_("Name of the point"))
  89. KIND_OTHER = 'other'
  90. KIND_SUBSCRIBER = 'subscriber'
  91. KIND_WAITING = 'waiting'
  92. KIND_CHOICES = (
  93. (KIND_WAITING, _('waiting')),
  94. (KIND_SUBSCRIBER, _('subscriber')),
  95. (KIND_OTHER, _('other')),
  96. )
  97. kind = models.CharField(verbose_name=_('kind'), max_length=255,
  98. choices=KIND_CHOICES, default=KIND_WAITING)
  99. def __str__(self):
  100. return self.name
  101. class Meta:
  102. verbose_name = _("reference point")
  103. verbose_name_plural = _("reference points")
  104. class Panorama(ReferencePoint):
  105. loop = models.BooleanField(default=False, verbose_name=_("360° panorama"),
  106. help_text=_("Whether the panorama loops around the edges"))
  107. image = models.ImageField(verbose_name=_("image"), upload_to="pano",
  108. width_field="image_width",
  109. height_field="image_height")
  110. image_width = models.PositiveIntegerField(default=0, verbose_name=_("image width"))
  111. image_height = models.PositiveIntegerField(default=0, verbose_name=_("image height"))
  112. antenne_cap_min = models.PositiveIntegerField(default=0, verbose_name=_("antenna_cap_min"))
  113. antenne_cap_max = models.PositiveIntegerField(default=0, verbose_name=_("antenna_cap_max"))
  114. # Set of references, i.e. reference points with information on how
  115. # they relate to this panorama.
  116. references = models.ManyToManyField(ReferencePoint, through='Reference',
  117. related_name="referenced_panorama",
  118. verbose_name=_("references"))
  119. def tiles_dir(self):
  120. return os.path.join(settings.MEDIA_ROOT, settings.PANORAMA_TILES_DIR,
  121. str(self.pk))
  122. def tiles_url(self):
  123. return os.path.join(settings.MEDIA_URL, settings.PANORAMA_TILES_DIR,
  124. str(self.pk))
  125. def has_tiles(self):
  126. return path_exists(self.tiles_dir()) and len(os.listdir(self.tiles_dir())) > 0
  127. has_tiles.boolean = True
  128. has_tiles.short_description = _("Tiles available?")
  129. def delete_tiles(self):
  130. """Delete all tiles and the tiles dir"""
  131. # If the directory doesn't exist, do nothing
  132. if not path_exists(self.tiles_dir()):
  133. return
  134. # Delete all tiles
  135. for filename in os.listdir(self.tiles_dir()):
  136. os.unlink(os.path.join(self.tiles_dir(), filename))
  137. os.rmdir(self.tiles_dir())
  138. def generate_tiles(self):
  139. makedirs(self.tiles_dir(), exist_ok=True)
  140. generate_tiles.delay(self.image.path, self.tiles_dir())
  141. def get_absolute_url(self, cap=None, ele=None, zoom=None):
  142. base_url = reverse('panorama:view_pano', args=[str(self.pk)])
  143. # Add parameters to point to the given direction, interpreted by
  144. # the js frontend
  145. if zoom is None:
  146. zoom = 0
  147. if not None in (zoom, cap, ele):
  148. return base_url + "#zoom={}/cap={}/ele={}".format(zoom, cap, ele)
  149. else:
  150. return base_url
  151. def tiles_data(self):
  152. """Hack to feed the current js code with tiles data (we should use the
  153. JSON API instead, and get rid of this function)"""
  154. data = dict()
  155. for zoomlevel in range(9):
  156. width = self.image_width >> zoomlevel
  157. height = self.image_height >> zoomlevel
  158. d = dict()
  159. d["tile_width"] = d["tile_height"] = 256
  160. # Python3-style division
  161. d["ntiles_x"] = int(ceil(width / 256))
  162. d["ntiles_y"] = int(ceil(height / 256))
  163. d["last_tile_width"] = width % 256
  164. d["last_tile_height"] = height % 256
  165. data[zoomlevel] = d
  166. return data
  167. def refpoints_data(self):
  168. """Similar hack, returns all reference points around the panorama."""
  169. def get_url(refpoint):
  170. """If the refpoint is also a panorama, returns its canonical URL"""
  171. if hasattr(refpoint, "panorama"):
  172. # Point towards the current panorama
  173. return refpoint.panorama.get_absolute_url(refpoint.bearing(self),
  174. refpoint.elevation(self))
  175. else:
  176. return ""
  177. refpoints = [refpoint for refpoint in ReferencePoint.objects.all()
  178. if self.great_circle_distance(refpoint) <= settings.PANORAMA_MAX_DISTANCE and refpoint.pk != self.pk]
  179. refpoints.sort(key=lambda r: self.line_distance(r))
  180. return enumerate([{"id": r.pk,
  181. "name": r.name,
  182. "url": get_url(r),
  183. "cap": self.bearing(r),
  184. "elevation": self.elevation(r),
  185. "distance": self.line_distance(r) / 1000}
  186. for r in refpoints])
  187. def references_data(self):
  188. """Similar hack, returns all references currently associated to the
  189. panorama."""
  190. return [{"id": r.pk,
  191. "name": r.reference_point.name,
  192. # Adapt to js-based coordinates (x between 0 and 1, y
  193. # between -0.5 and 0.5)
  194. "x": r.x / r.panorama.image_width,
  195. "y": (r.y / r.panorama.image_height) - 0.5,
  196. "cap": self.bearing(r.reference_point),
  197. "elevation": self.elevation(r.reference_point)}
  198. for r in self.panorama_references.all()]
  199. def is_visible(self, point):
  200. """Return True if the Panorama can see the point."""
  201. if self.great_circle_distance(point) > settings.PANORAMA_MAX_DISTANCE:
  202. return False
  203. if self.loop:
  204. return True
  205. cap = self.bearing(point) % 360
  206. cap_min = self.cap_min()
  207. cap_max = self.cap_max()
  208. # Not enough references
  209. if cap_min is None or cap_max is None:
  210. return False
  211. if cap_min < cap_max:
  212. # Nominal case
  213. return cap_min <= cap <= cap_max
  214. else:
  215. return cap_min <= cap or cap <= cap_max
  216. def cap_min(self):
  217. return self._cap_minmax(True)
  218. def cap_max(self):
  219. return self._cap_minmax(False)
  220. def _cap_minmax(self, ismin=True):
  221. """Return the cap on the border of the image.
  222. :param ismin: True if the min cap should be processed False if it is the
  223. max.
  224. @return None if the image is looping or if the image have less than two
  225. references.
  226. """
  227. if self.loop:
  228. return None
  229. it = self.panorama_references.order_by(
  230. 'x' if ismin else '-x').iterator()
  231. try:
  232. ref1 = next(it)
  233. ref2 = next(it)
  234. except StopIteration:
  235. return None
  236. cap1 = self.bearing(ref1.reference_point)
  237. cap2 = self.bearing(ref2.reference_point)
  238. target_x = 0 if ismin else self.image_width
  239. # For circulary issues
  240. if ismin and cap2 < cap1:
  241. cap2 += 360
  242. if (not ismin) and cap1 < cap2:
  243. cap1 += 360
  244. target_cap = cap1 + (target_x - ref1.x) * (cap2 - cap1) / \
  245. (ref2.x - ref1.x)
  246. return target_cap % 360
  247. class Meta:
  248. verbose_name = _("panorama")
  249. verbose_name_plural = _("panoramas")
  250. @python_2_unicode_compatible
  251. class Reference(models.Model):
  252. """A reference is made of a Panorama, a Reference Point, and the position
  253. (x, y) of the reference point inside the image. With enough
  254. references, the panorama is calibrated. That is, we can build a
  255. mapping between pixels of the image and directions in 3D space, which
  256. are represented by (azimuth, elevation) couples."""
  257. # Components of the ManyToMany relation
  258. reference_point = models.ForeignKey(ReferencePoint, related_name="refpoint_references",
  259. verbose_name=_("reference point"))
  260. panorama = models.ForeignKey(Panorama, related_name="panorama_references",
  261. verbose_name=_("panorama"))
  262. # Position of the reference point in the panorama image
  263. x = models.PositiveIntegerField()
  264. y = models.PositiveIntegerField()
  265. class Meta:
  266. # It makes no sense to have multiple references of the same
  267. # reference point on a given panorama.
  268. unique_together = (("reference_point", "panorama"),)
  269. verbose_name = _("reference")
  270. verbose_name_plural = _("references")
  271. def clean(self):
  272. # Check that the reference point and the panorama are different
  273. # (remember that panoramas can *also* be seen as reference points)
  274. if self.panorama.pk == self.reference_point.pk:
  275. raise ValidationError(_("A panorama can't reference itself."))
  276. # Check than the position is within the bounds of the image.
  277. w = self.panorama.image_width
  278. h = self.panorama.image_height
  279. if self.x >= w or self.y >= h:
  280. raise ValidationError(_("Position {xy} is outside the bounds "
  281. "of the image ({width}, {height}).").format(
  282. xy=(self.x, self.y),
  283. width=w,
  284. height=h))
  285. def __str__(self):
  286. return _('{refpoint} at {xy} in {pano}').format(
  287. pano=self.panorama.name,
  288. xy=(self.x, self.y),
  289. refpoint=self.reference_point.name,
  290. )