DdsImagePlugin.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. """
  2. A Pillow loader for .dds files (S3TC-compressed aka DXTC)
  3. Jerome Leclanche <jerome@leclan.ch>
  4. Documentation:
  5. https://web.archive.org/web/20170802060935/http://oss.sgi.com/projects/ogl-sample/registry/EXT/texture_compression_s3tc.txt
  6. The contents of this file are hereby released in the public domain (CC0)
  7. Full text of the CC0 license:
  8. https://creativecommons.org/publicdomain/zero/1.0/
  9. """
  10. import struct
  11. from io import BytesIO
  12. from . import Image, ImageFile, ImagePalette
  13. from ._binary import o32le as o32
  14. # Magic ("DDS ")
  15. DDS_MAGIC = 0x20534444
  16. # DDS flags
  17. DDSD_CAPS = 0x1
  18. DDSD_HEIGHT = 0x2
  19. DDSD_WIDTH = 0x4
  20. DDSD_PITCH = 0x8
  21. DDSD_PIXELFORMAT = 0x1000
  22. DDSD_MIPMAPCOUNT = 0x20000
  23. DDSD_LINEARSIZE = 0x80000
  24. DDSD_DEPTH = 0x800000
  25. # DDS caps
  26. DDSCAPS_COMPLEX = 0x8
  27. DDSCAPS_TEXTURE = 0x1000
  28. DDSCAPS_MIPMAP = 0x400000
  29. DDSCAPS2_CUBEMAP = 0x200
  30. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400
  31. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800
  32. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000
  33. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000
  34. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000
  35. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000
  36. DDSCAPS2_VOLUME = 0x200000
  37. # Pixel Format
  38. DDPF_ALPHAPIXELS = 0x1
  39. DDPF_ALPHA = 0x2
  40. DDPF_FOURCC = 0x4
  41. DDPF_PALETTEINDEXED8 = 0x20
  42. DDPF_RGB = 0x40
  43. DDPF_LUMINANCE = 0x20000
  44. # dds.h
  45. DDS_FOURCC = DDPF_FOURCC
  46. DDS_RGB = DDPF_RGB
  47. DDS_RGBA = DDPF_RGB | DDPF_ALPHAPIXELS
  48. DDS_LUMINANCE = DDPF_LUMINANCE
  49. DDS_LUMINANCEA = DDPF_LUMINANCE | DDPF_ALPHAPIXELS
  50. DDS_ALPHA = DDPF_ALPHA
  51. DDS_PAL8 = DDPF_PALETTEINDEXED8
  52. DDS_HEADER_FLAGS_TEXTURE = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT
  53. DDS_HEADER_FLAGS_MIPMAP = DDSD_MIPMAPCOUNT
  54. DDS_HEADER_FLAGS_VOLUME = DDSD_DEPTH
  55. DDS_HEADER_FLAGS_PITCH = DDSD_PITCH
  56. DDS_HEADER_FLAGS_LINEARSIZE = DDSD_LINEARSIZE
  57. DDS_HEIGHT = DDSD_HEIGHT
  58. DDS_WIDTH = DDSD_WIDTH
  59. DDS_SURFACE_FLAGS_TEXTURE = DDSCAPS_TEXTURE
  60. DDS_SURFACE_FLAGS_MIPMAP = DDSCAPS_COMPLEX | DDSCAPS_MIPMAP
  61. DDS_SURFACE_FLAGS_CUBEMAP = DDSCAPS_COMPLEX
  62. DDS_CUBEMAP_POSITIVEX = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEX
  63. DDS_CUBEMAP_NEGATIVEX = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEX
  64. DDS_CUBEMAP_POSITIVEY = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEY
  65. DDS_CUBEMAP_NEGATIVEY = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEY
  66. DDS_CUBEMAP_POSITIVEZ = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZ
  67. DDS_CUBEMAP_NEGATIVEZ = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ
  68. # DXT1
  69. DXT1_FOURCC = 0x31545844
  70. # DXT3
  71. DXT3_FOURCC = 0x33545844
  72. # DXT5
  73. DXT5_FOURCC = 0x35545844
  74. # dxgiformat.h
  75. DXGI_FORMAT_R8G8B8A8_TYPELESS = 27
  76. DXGI_FORMAT_R8G8B8A8_UNORM = 28
  77. DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 29
  78. DXGI_FORMAT_BC5_TYPELESS = 82
  79. DXGI_FORMAT_BC5_UNORM = 83
  80. DXGI_FORMAT_BC5_SNORM = 84
  81. DXGI_FORMAT_BC6H_UF16 = 95
  82. DXGI_FORMAT_BC6H_SF16 = 96
  83. DXGI_FORMAT_BC7_TYPELESS = 97
  84. DXGI_FORMAT_BC7_UNORM = 98
  85. DXGI_FORMAT_BC7_UNORM_SRGB = 99
  86. class DdsImageFile(ImageFile.ImageFile):
  87. format = "DDS"
  88. format_description = "DirectDraw Surface"
  89. def _open(self):
  90. if not _accept(self.fp.read(4)):
  91. msg = "not a DDS file"
  92. raise SyntaxError(msg)
  93. (header_size,) = struct.unpack("<I", self.fp.read(4))
  94. if header_size != 124:
  95. msg = f"Unsupported header size {repr(header_size)}"
  96. raise OSError(msg)
  97. header_bytes = self.fp.read(header_size - 4)
  98. if len(header_bytes) != 120:
  99. msg = f"Incomplete header: {len(header_bytes)} bytes"
  100. raise OSError(msg)
  101. header = BytesIO(header_bytes)
  102. flags, height, width = struct.unpack("<3I", header.read(12))
  103. self._size = (width, height)
  104. self._mode = "RGBA"
  105. pitch, depth, mipmaps = struct.unpack("<3I", header.read(12))
  106. struct.unpack("<11I", header.read(44)) # reserved
  107. # pixel format
  108. pfsize, pfflags = struct.unpack("<2I", header.read(8))
  109. fourcc = header.read(4)
  110. (bitcount,) = struct.unpack("<I", header.read(4))
  111. masks = struct.unpack("<4I", header.read(16))
  112. if pfflags & DDPF_LUMINANCE:
  113. # Texture contains uncompressed L or LA data
  114. if pfflags & DDPF_ALPHAPIXELS:
  115. self._mode = "LA"
  116. else:
  117. self._mode = "L"
  118. self.tile = [("raw", (0, 0) + self.size, 0, (self.mode, 0, 1))]
  119. elif pfflags & DDPF_RGB:
  120. # Texture contains uncompressed RGB data
  121. masks = {mask: ["R", "G", "B", "A"][i] for i, mask in enumerate(masks)}
  122. rawmode = ""
  123. if pfflags & DDPF_ALPHAPIXELS:
  124. rawmode += masks[0xFF000000]
  125. else:
  126. self._mode = "RGB"
  127. rawmode += masks[0xFF0000] + masks[0xFF00] + masks[0xFF]
  128. self.tile = [("raw", (0, 0) + self.size, 0, (rawmode[::-1], 0, 1))]
  129. elif pfflags & DDPF_PALETTEINDEXED8:
  130. self._mode = "P"
  131. self.palette = ImagePalette.raw("RGBA", self.fp.read(1024))
  132. self.tile = [("raw", (0, 0) + self.size, 0, "L")]
  133. else:
  134. data_start = header_size + 4
  135. n = 0
  136. if fourcc == b"DXT1":
  137. self.pixel_format = "DXT1"
  138. n = 1
  139. elif fourcc == b"DXT3":
  140. self.pixel_format = "DXT3"
  141. n = 2
  142. elif fourcc == b"DXT5":
  143. self.pixel_format = "DXT5"
  144. n = 3
  145. elif fourcc == b"ATI1":
  146. self.pixel_format = "BC4"
  147. n = 4
  148. self._mode = "L"
  149. elif fourcc in (b"ATI2", b"BC5U"):
  150. self.pixel_format = "BC5"
  151. n = 5
  152. self._mode = "RGB"
  153. elif fourcc == b"BC5S":
  154. self.pixel_format = "BC5S"
  155. n = 5
  156. self._mode = "RGB"
  157. elif fourcc == b"DX10":
  158. data_start += 20
  159. # ignoring flags which pertain to volume textures and cubemaps
  160. (dxgi_format,) = struct.unpack("<I", self.fp.read(4))
  161. self.fp.read(16)
  162. if dxgi_format in (DXGI_FORMAT_BC5_TYPELESS, DXGI_FORMAT_BC5_UNORM):
  163. self.pixel_format = "BC5"
  164. n = 5
  165. self._mode = "RGB"
  166. elif dxgi_format == DXGI_FORMAT_BC5_SNORM:
  167. self.pixel_format = "BC5S"
  168. n = 5
  169. self._mode = "RGB"
  170. elif dxgi_format == DXGI_FORMAT_BC6H_UF16:
  171. self.pixel_format = "BC6H"
  172. n = 6
  173. self._mode = "RGB"
  174. elif dxgi_format == DXGI_FORMAT_BC6H_SF16:
  175. self.pixel_format = "BC6HS"
  176. n = 6
  177. self._mode = "RGB"
  178. elif dxgi_format in (DXGI_FORMAT_BC7_TYPELESS, DXGI_FORMAT_BC7_UNORM):
  179. self.pixel_format = "BC7"
  180. n = 7
  181. elif dxgi_format == DXGI_FORMAT_BC7_UNORM_SRGB:
  182. self.pixel_format = "BC7"
  183. self.info["gamma"] = 1 / 2.2
  184. n = 7
  185. elif dxgi_format in (
  186. DXGI_FORMAT_R8G8B8A8_TYPELESS,
  187. DXGI_FORMAT_R8G8B8A8_UNORM,
  188. DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
  189. ):
  190. self.tile = [("raw", (0, 0) + self.size, 0, ("RGBA", 0, 1))]
  191. if dxgi_format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
  192. self.info["gamma"] = 1 / 2.2
  193. return
  194. else:
  195. msg = f"Unimplemented DXGI format {dxgi_format}"
  196. raise NotImplementedError(msg)
  197. else:
  198. msg = f"Unimplemented pixel format {repr(fourcc)}"
  199. raise NotImplementedError(msg)
  200. self.tile = [
  201. ("bcn", (0, 0) + self.size, data_start, (n, self.pixel_format))
  202. ]
  203. def load_seek(self, pos):
  204. pass
  205. def _save(im, fp, filename):
  206. if im.mode not in ("RGB", "RGBA", "L", "LA"):
  207. msg = f"cannot write mode {im.mode} as DDS"
  208. raise OSError(msg)
  209. rawmode = im.mode
  210. masks = [0xFF0000, 0xFF00, 0xFF]
  211. if im.mode in ("L", "LA"):
  212. pixel_flags = DDPF_LUMINANCE
  213. else:
  214. pixel_flags = DDPF_RGB
  215. rawmode = rawmode[::-1]
  216. if im.mode in ("LA", "RGBA"):
  217. pixel_flags |= DDPF_ALPHAPIXELS
  218. masks.append(0xFF000000)
  219. bitcount = len(masks) * 8
  220. while len(masks) < 4:
  221. masks.append(0)
  222. fp.write(
  223. o32(DDS_MAGIC)
  224. + o32(124) # header size
  225. + o32(
  226. DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PITCH | DDSD_PIXELFORMAT
  227. ) # flags
  228. + o32(im.height)
  229. + o32(im.width)
  230. + o32((im.width * bitcount + 7) // 8) # pitch
  231. + o32(0) # depth
  232. + o32(0) # mipmaps
  233. + o32(0) * 11 # reserved
  234. + o32(32) # pfsize
  235. + o32(pixel_flags) # pfflags
  236. + o32(0) # fourcc
  237. + o32(bitcount) # bitcount
  238. + b"".join(o32(mask) for mask in masks) # rgbabitmask
  239. + o32(DDSCAPS_TEXTURE) # dwCaps
  240. + o32(0) # dwCaps2
  241. + o32(0) # dwCaps3
  242. + o32(0) # dwCaps4
  243. + o32(0) # dwReserved2
  244. )
  245. if im.mode == "RGBA":
  246. r, g, b, a = im.split()
  247. im = Image.merge("RGBA", (a, r, g, b))
  248. ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, 1))])
  249. def _accept(prefix):
  250. return prefix[:4] == b"DDS "
  251. Image.register_open(DdsImageFile.format, DdsImageFile, _accept)
  252. Image.register_save(DdsImageFile.format, _save)
  253. Image.register_extension(DdsImageFile.format, ".dds")