cube_coords.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. '''
  2. Created on 8 nov. 2016
  3. Cubic coordinates are used in some algorythms about hexagonal grids
  4. @author: olinox
  5. '''
  6. def cv_cube_off(xu, yu, zu):
  7. """convert cubic coordinates (xu, yu, zu) in standards coordinates (x, y) [offset]"""
  8. if not all(isinstance(c, int) for c in [xu, yu, zu]):
  9. raise TypeError("!err: xu, yu et zu doivent etre des entiers")
  10. y = int( xu + ( zu - (zu & 1) ) / 2 )
  11. x = zu
  12. return (x, y)
  13. def cv_off_cube(x, y):
  14. """converts standards coordinates (x, y) [offset] in cubic coordinates (xu, yu, zu)"""
  15. if not all(isinstance(c, int) for c in [x, y]):
  16. raise TypeError("!err: x et y doivent etre des entiers")
  17. zu = x
  18. xu = int( y - ( x - (x & 1) ) / 2 )
  19. yu = int( -xu -zu )
  20. return (xu, yu, zu)
  21. def cube_round(x, y, z):
  22. """returns the nearest cell (in cubic coords)
  23. x, y, z can be floating numbers, no problem."""
  24. rx, ry, rz = round(x), round(y), round(z)
  25. x_diff, y_diff, z_diff = abs(rx - x), abs(ry - y), abs(rz - z)
  26. if x_diff > y_diff and x_diff > z_diff:
  27. rx = -ry-rz
  28. elif y_diff > z_diff:
  29. ry = -rx-rz
  30. else:
  31. rz = -rx-ry
  32. return (rx, ry, rz)
  33. def hex_distance_cube(xa, ya, za, xb, yb, zb):
  34. """returns the manhattan distance between the two cells"""
  35. return max(abs(xa - xb), abs(ya - yb), abs(za - zb))
  36. def distance_off(xa, ya, xb, yb):
  37. """ distance between A and B (offset coordinates)"""
  38. # 10 times quicker if no conversion...
  39. xua, yua, zua = cv_off_cube(xa, ya)
  40. xub, yub, zub = cv_off_cube(xb, yb)
  41. return max(abs(xua - xub), abs(yua - yub), abs(zua - zub))