models.py 13 KB

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