image.py 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. # coding: utf-8
  2. import io
  3. import typing
  4. from PIL import Image
  5. from synergine2.config import Config
  6. from synergine2_cocos2d.actor import Actor
  7. from synergine2_cocos2d.util import PathManager
  8. from opencombat.exception import UnknownAnimationIndex
  9. class ImageCache(object):
  10. def __init__(self) -> None:
  11. self.cache = {}
  12. class FiringCache(ImageCache):
  13. def add(
  14. self,
  15. mode: str,
  16. weapon: str,
  17. image: Image.Image,
  18. ) -> None:
  19. self.cache.setdefault(mode, {}).setdefault(weapon, []).append(image)
  20. def get(
  21. self,
  22. mode: str,
  23. weapon: str,
  24. position: int,
  25. ) -> Image.Image:
  26. try:
  27. return self.cache[mode][weapon][position]
  28. except KeyError:
  29. raise Exception('TODO')
  30. except IndexError:
  31. raise UnknownAnimationIndex(
  32. 'Unknown animation index "{}" for mode "{}" and weapon "{}"'.format(
  33. position,
  34. mode,
  35. weapon,
  36. ),
  37. )
  38. class ImageCache(object):
  39. # FIXME: Move into synergine
  40. def __init__(
  41. self,
  42. actor: Actor,
  43. config: Config,
  44. ) -> None:
  45. self.config = config
  46. self.actor = actor
  47. def build(self) -> None:
  48. pass
  49. class TileImageCache(ImageCache):
  50. def __init__(
  51. self,
  52. actor: Actor,
  53. config: Config,
  54. ) -> None:
  55. super().__init__(actor, config)
  56. self.firing_cache = FiringCache()
  57. from opencombat.gui.actor import BaseActor
  58. self.actor = typing.cast(BaseActor, self.actor)
  59. self.path_manager = PathManager(
  60. self.config.resolve('global.include_path.graphics'),
  61. )
  62. def build(self) -> None:
  63. super().build()
  64. self.build_firing()
  65. def build_firing(self) -> None:
  66. for mode in self.actor.get_modes():
  67. mode_image_path = self.actor.default_image_path # FIXME !
  68. mode_image = Image.open(self.path_manager.path(mode_image_path))
  69. for weapon in self.actor.weapons:
  70. images = self.actor.weapon_image_applier.get_firing_image(
  71. mode=mode,
  72. weapon_type=weapon,
  73. )
  74. for position in range(len(images)):
  75. position_image = images[position]
  76. final_image = mode_image.copy()
  77. final_image.paste(
  78. position_image,
  79. (0, 0),
  80. position_image,
  81. )
  82. self.firing_cache.add(mode, weapon, final_image)