models.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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
  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.utils.encoding import python_2_unicode_compatible
  11. from .tasks import generate_tiles
  12. EARTH_RADIUS = 6371009
  13. class Point(models.Model):
  14. """Geographical point, with altitude."""
  15. latitude = models.FloatField(verbose_name="latitude", help_text="In degrees",
  16. validators=[MinValueValidator(-90),
  17. MaxValueValidator(90)])
  18. longitude = models.FloatField(verbose_name="longitude", help_text="In degrees",
  19. validators=[MinValueValidator(-180),
  20. MaxValueValidator(180)])
  21. altitude = models.FloatField(verbose_name="altitude", help_text="In meters",
  22. validators=[MinValueValidator(0.)])
  23. @property
  24. def latitude_rad(self):
  25. return radians(self.latitude)
  26. @property
  27. def longitude_rad(self):
  28. return radians(self.longitude)
  29. @property
  30. def altitude_abs(self):
  31. """Absolute distance to the center of Earth (in a spherical model)"""
  32. return EARTH_RADIUS + self.altitude
  33. def great_angle(self, other):
  34. """Returns the great angle, in radians, between the two given points. The
  35. great angle is the angle formed by the two points when viewed from
  36. the center of the Earth.
  37. """
  38. lon_delta = other.longitude_rad - self.longitude_rad
  39. a = (cos(other.latitude_rad) * sin(lon_delta)) ** 2 \
  40. + (cos(self.latitude_rad) * sin(other.latitude_rad) \
  41. - sin(self.latitude_rad) * cos(other.latitude_rad) * cos(lon_delta)) ** 2
  42. b = sin(self.latitude_rad) * sin(other.latitude_rad) \
  43. + cos(self.latitude_rad) * cos(other.latitude_rad) * cos(lon_delta)
  44. angle = atan2(sqrt(a), b)
  45. return angle
  46. def great_circle_distance(self, other):
  47. """Returns the great circle distance between two points, without taking
  48. into account their altitude. Don't use this to compute
  49. line-of-sight distance, see [line_distance] instead.
  50. """
  51. return EARTH_RADIUS * self.great_angle(other)
  52. def line_distance(self, other):
  53. """Distance of the straight line between two points on Earth, in meters.
  54. Note that this is only useful because we are considering
  55. line-of-sight links, where straight-line distance is the relevant
  56. distance. For arbitrary points on Earth, great-circle distance
  57. would most likely be preferred.
  58. """
  59. delta_lon = other.longitude_rad - self.longitude_rad
  60. # Cosine of the angle between the two points on their great circle.
  61. cos_angle = sin(self.latitude_rad) * sin(other.latitude_rad) \
  62. + cos(self.latitude_rad) * cos(other.latitude_rad) * cos(delta_lon)
  63. # Al-Kashi formula
  64. return sqrt(self.altitude_abs ** 2 \
  65. + other.altitude_abs ** 2 \
  66. - 2 * self.altitude_abs * other.altitude_abs * cos_angle)
  67. def bearing(self, other):
  68. """Bearing, in degrees, between this point and another point."""
  69. delta_lon = other.longitude_rad - self.longitude_rad
  70. y = sin(delta_lon) * cos(other.latitude_rad)
  71. x = cos(self.latitude_rad) * sin(other.latitude_rad) \
  72. - sin(self.latitude_rad) * cos(other.latitude_rad) * cos(delta_lon)
  73. return degrees(atan2(y, x))
  74. def elevation(self, other):
  75. """Elevation, in degrees, between this point and another point."""
  76. d = self.line_distance(other)
  77. sin_elev = (other.altitude_abs ** 2 - self.altitude_abs ** 2 - d ** 2) \
  78. / (2 * self.altitude_abs * d)
  79. return degrees(asin(sin_elev))
  80. class Meta:
  81. abstract = True
  82. @python_2_unicode_compatible
  83. class ReferencePoint(Point):
  84. """Reference point, to be used"""
  85. name = models.CharField(verbose_name="name", max_length=255,
  86. help_text="Name of the point")
  87. def __str__(self):
  88. return "Reference point : " + self.name
  89. @python_2_unicode_compatible
  90. class Panorama(ReferencePoint):
  91. loop = models.BooleanField(default=False, verbose_name="360° panorama",
  92. help_text="Whether the panorama loops around the edges")
  93. image = models.ImageField(verbose_name="image", upload_to="pano",
  94. width_field="image_width",
  95. height_field="image_height")
  96. image_width = models.PositiveIntegerField(default=0)
  97. image_height = models.PositiveIntegerField(default=0)
  98. # Set of references, i.e. reference points with information on how
  99. # they relate to this panorama.
  100. references = models.ManyToManyField(ReferencePoint, through='Reference',
  101. related_name="referenced_panorama")
  102. def tiles_dir(self):
  103. return os.path.join(settings.MEDIA_ROOT, settings.PANORAMA_TILES_DIR,
  104. str(self.pk))
  105. def tiles_url(self):
  106. return os.path.join(settings.MEDIA_URL, settings.PANORAMA_TILES_DIR,
  107. str(self.pk))
  108. def generate_tiles(self):
  109. try:
  110. os.makedirs(self.tiles_dir())
  111. except OSError:
  112. pass
  113. generate_tiles.delay(self.image.path, self.tiles_dir())
  114. def __str__(self):
  115. return "Panorama : " + self.name
  116. class Reference(models.Model):
  117. """A reference is made of a Panorama, a Reference Point, and the position
  118. (x, y) of the reference point inside the image. With enough
  119. references, the panorama is calibrated. That is, we can build a
  120. mapping between pixels of the image and directions in 3D space, which
  121. are represented by (azimuth, elevation) couples."""
  122. # Components of the ManyToMany relation
  123. reference_point = models.ForeignKey(ReferencePoint, related_name="refpoint_references")
  124. panorama = models.ForeignKey(Panorama, related_name="panorama_references")
  125. # Position of the reference point in the panorama image
  126. x = models.PositiveIntegerField()
  127. y = models.PositiveIntegerField()
  128. class Meta:
  129. # It makes no sense to have multiple references of the same
  130. # reference point on a given panorama.
  131. unique_together = (("reference_point", "panorama"),)
  132. def clean(self):
  133. # Check that the reference point and the panorama are different
  134. # (remember that panoramas can *also* be seen as reference points)
  135. if self.panorama.pk == self.reference_point.pk:
  136. raise ValidationError("A panorama can't reference itself.")
  137. # Check than the position is within the bounds of the image.
  138. w = self.panorama.image_width
  139. h = self.panorama.image_height
  140. if self.x >= w or self.y >= h:
  141. raise ValidationError("Position ({x}, {y}) is outside the bounds "
  142. "of the image ({width}, {height}).".format(
  143. x=self.x,
  144. y=self.y,
  145. width=w,
  146. height=h))