image.py 2.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. # coding: utf-8
  2. import typing
  3. from PIL import Image
  4. from synergine2.config import Config
  5. from synergine2_cocos2d.util import PathManager
  6. from synergine2_xyz.exception import UnknownAnimationIndex
  7. from synergine2_xyz.exception import UnknownAnimation
  8. if typing.TYPE_CHECKING:
  9. from synergine2_cocos2d.actor import Actor
  10. class ImageCache(object):
  11. def __init__(self) -> None:
  12. self.cache = {}
  13. class AnimationImageCache(object):
  14. def __init__(self) -> None:
  15. self.cache = {}
  16. def add(
  17. self,
  18. animation_name: str,
  19. image: Image.Image,
  20. ) -> None:
  21. self.cache.setdefault(animation_name, []).append(image)
  22. def get(
  23. self,
  24. animation_name: str,
  25. image_position: int,
  26. ) -> Image.Image:
  27. try:
  28. return self.cache[animation_name][image_position]
  29. except KeyError:
  30. raise Exception('TODO')
  31. except IndexError:
  32. raise UnknownAnimationIndex(
  33. 'Unknown animation index "{}" for animation "{}"'.format(
  34. image_position,
  35. animation_name,
  36. ),
  37. )
  38. def get_animation_images(self, animation_name: str) -> typing.List[Image.Image]:
  39. try:
  40. return self.cache[animation_name]
  41. except KeyError:
  42. raise UnknownAnimation(
  43. 'Unknown animation "{}"'.format(
  44. animation_name,
  45. ),
  46. )
  47. class ImageCacheManager(object):
  48. def __init__(
  49. self,
  50. actor: 'Actor',
  51. config: Config,
  52. ) -> None:
  53. self.config = config
  54. self.actor = actor
  55. self.path_manager = PathManager(config.resolve('global.include_path.graphics'))
  56. self.animation_cache = AnimationImageCache()
  57. def build(self) -> None:
  58. self.build_animation_cache()
  59. def build_animation_cache(self) -> None:
  60. cache_dir = self.config.resolve('global.cache_dir_path')
  61. animation_images = self.actor.animation_image_paths.items()
  62. for animation_name, animation_image_paths in animation_images:
  63. for i, animation_image_path in enumerate(animation_image_paths):
  64. final_image_path = self.path_manager.path(animation_image_path)
  65. final_image = Image.open(final_image_path)
  66. for appliable_image in self.actor.get_animation_appliable_images(
  67. animation_name,
  68. i,
  69. ):
  70. final_image.paste(
  71. appliable_image,
  72. (0, 0),
  73. appliable_image,
  74. )
  75. self.animation_cache.add(animation_name, final_image)