convert_image.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. #!/usr/bin/python3
  2. # Copyright (C) 2009-2020, Panagiotis Christopoulos Charitos and contributors.
  3. # All rights reserved.
  4. # Code licensed under the BSD License.
  5. # http://www.anki3d.org/LICENSE
  6. import argparse
  7. import subprocess
  8. import re
  9. import os
  10. import struct
  11. import copy
  12. import tempfile
  13. import shutil
  14. from PIL import Image
  15. from ctypes import Structure, sizeof, c_int, c_char, c_byte, c_uint
  16. from io import BytesIO
  17. class CStruct(Structure):
  18. """ C structure """
  19. def to_bytearray(self):
  20. s = BytesIO()
  21. s.write(self)
  22. s.seek(0)
  23. return s.read()
  24. def from_bytearray(self, bin):
  25. s = BytesIO(bin)
  26. s.seek(0)
  27. s.readinto(self)
  28. class Config:
  29. in_files = []
  30. out_file = ""
  31. fast = False
  32. type = 0
  33. normal = False
  34. convert_path = ""
  35. no_alpha = False
  36. compressed_formats = 0
  37. store_uncompressed = True
  38. to_linear_rgb = False
  39. tmp_dir = ""
  40. #
  41. # AnKi texture
  42. #
  43. # Texture type
  44. TT_NONE = 0
  45. TT_2D = 1
  46. TT_CUBE = 2
  47. TT_3D = 3
  48. TT_2D_ARRAY = 4
  49. # Color format
  50. CF_NONE = 0
  51. CF_RGB8 = 1
  52. CF_RGBA8 = 2
  53. # Data compression
  54. DC_NONE = 0
  55. DC_RAW = 1 << 0
  56. DC_S3TC = 1 << 1
  57. DC_ETC2 = 1 << 2
  58. # Texture filtering
  59. TF_DEFAULT = 0
  60. TF_LINEAR = 1
  61. TF_NEAREST = 2
  62. #
  63. # DDS
  64. #
  65. # dwFlags of DDSURFACEDESC2
  66. DDSD_CAPS = 0x00000001
  67. DDSD_HEIGHT = 0x00000002
  68. DDSD_WIDTH = 0x00000004
  69. DDSD_PITCH = 0x00000008
  70. DDSD_PIXELFORMAT = 0x00001000
  71. DDSD_MIPMAPCOUNT = 0x00020000
  72. DDSD_LINEARSIZE = 0x00080000
  73. DDSD_DEPTH = 0x00800000
  74. # ddpfPixelFormat of DDSURFACEDESC2
  75. DDPF_ALPHAPIXELS = 0x00000001
  76. DDPF_FOURCC = 0x00000004
  77. DDPF_RGB = 0x00000040
  78. # dwCaps1 of DDSCAPS2
  79. DDSCAPS_COMPLEX = 0x00000008
  80. DDSCAPS_TEXTURE = 0x00001000
  81. DDSCAPS_MIPMAP = 0x00400000
  82. # dwCaps2 of DDSCAPS2
  83. DDSCAPS2_CUBEMAP = 0x00000200
  84. DDSCAPS2_CUBEMAP_POSITIVEX = 0x00000400
  85. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x00000800
  86. DDSCAPS2_CUBEMAP_POSITIVEY = 0x00001000
  87. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x00002000
  88. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x00004000
  89. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x00008000
  90. DDSCAPS2_VOLUME = 0x00200000
  91. class DdsHeader(CStruct):
  92. """ The header of a dds file """
  93. _fields_ = (
  94. ('dwMagic', c_char * 4),
  95. ('dwSize', c_int),
  96. ('dwFlags', c_int),
  97. ('dwHeight', c_int),
  98. ('dwWidth', c_int),
  99. ('dwPitchOrLinearSize', c_int),
  100. ('dwDepth', c_int),
  101. ('dwMipMapCount', c_int),
  102. ('dwReserved1', c_char * 44),
  103. # Pixel format
  104. ('dwSize', c_int),
  105. ('dwFlags', c_int),
  106. ('dwFourCC', c_char * 4),
  107. ('dwRGBBitCount', c_int),
  108. ('dwRBitMask', c_int),
  109. ('dwGBitMask', c_int),
  110. ('dwBBitMask', c_int),
  111. ('dwRGBAlphaBitMask', c_int),
  112. ('dwCaps1', c_int),
  113. ('dwCaps2', c_int),
  114. ('dwCapsReserved', c_char * 8),
  115. ('dwReserved2', c_int))
  116. #
  117. # ETC2
  118. #
  119. class PkmHeader:
  120. """ The header of a pkm file """
  121. _fields = [("magic", "6s"), ("type", "H"), ("width", "H"), ("height", "H"), ("origWidth", "H"), ("origHeight", "H")]
  122. def __init__(self, buff):
  123. buff_format = self.get_format()
  124. items = struct.unpack(buff_format, buff)
  125. for field, value in map(None, self._fields, items):
  126. setattr(self, field[0], value)
  127. @classmethod
  128. def get_format(cls):
  129. return ">" + "".join([f[1] for f in cls._fields])
  130. @classmethod
  131. def get_size(cls):
  132. return struct.calcsize(cls.get_format())
  133. #
  134. # Functions
  135. #
  136. def printi(s):
  137. print("[I] %s" % s)
  138. def printw(s):
  139. print("[W] %s" % s)
  140. def is_power2(num):
  141. """ Returns true if a number is a power of two """
  142. return num != 0 and ((num & (num - 1)) == 0)
  143. def get_base_fname(path):
  144. """ From path/to/a/file.ext return the "file" """
  145. return os.path.splitext(os.path.basename(path))[0]
  146. def parse_commandline():
  147. """ Parse the command line arguments """
  148. parser = argparse.ArgumentParser(description = "This program converts a single image or a number " \
  149. "of images (for 3D and 2DArray textures) to AnKi texture format. " \
  150. "It requires 4 different applications/executables to " \
  151. "operate: convert, identify, nvcompress and etcpack. These " \
  152. "applications should be in PATH except the convert where you " \
  153. "need to define the executable explicitly",
  154. formatter_class = argparse.ArgumentDefaultsHelpFormatter)
  155. parser.add_argument(
  156. "-i", "--input", nargs="+", required=True, help="specify the image(s) to convert. Seperate with space")
  157. parser.add_argument("-o", "--output", required=True, help="specify output AnKi image.")
  158. parser.add_argument(
  159. "-t",
  160. "--type",
  161. default="2D",
  162. choices=["2D", "3D", "2DArray"],
  163. help="type of the image (2D or cube or 3D or 2DArray)")
  164. parser.add_argument("-f", "--fast", type=int, default=0, help="run the fast version of the converters")
  165. parser.add_argument("-n", "--normal", type=int, default=0, help="assume the texture is normal")
  166. parser.add_argument(
  167. "-c",
  168. "--convert-path",
  169. default="/usr/bin/convert",
  170. help="the executable where convert tool is located. Stupid etcpack cannot get it from PATH")
  171. parser.add_argument("--no-alpha", type=int, default=0, help="remove alpha channel")
  172. parser.add_argument("--store-uncompressed", type=int, default=0, help="store or not uncompressed data")
  173. parser.add_argument("--store-etc", type=int, default=0, help="store or not etc compressed data")
  174. parser.add_argument("--store-s3tc", type=int, default=1, help="store or not S3TC compressed data")
  175. parser.add_argument(
  176. "--to-linear-rgb",
  177. type=int,
  178. default=0,
  179. help="assume the input textures are sRGB. If this option is true then convert them to linear RGB")
  180. parser.add_argument(
  181. "--filter",
  182. default="default",
  183. choices=["default", "linear", "nearest"],
  184. help="texture filtering. Can be: default, linear, nearest")
  185. parser.add_argument("--mip-count", type=int, default=0xFFFF, help="Max number of mipmaps")
  186. args = parser.parse_args()
  187. if args.type == "2D":
  188. typ = TT_2D
  189. elif args.type == "cube":
  190. typ = TT_CUBE
  191. elif args.type == "3D":
  192. typ = TT_3D
  193. elif args.type == "2DArray":
  194. typ = TT_2D_ARRAY
  195. else:
  196. assert 0, "See file"
  197. if args.filter == "default":
  198. filter = TF_DEFAULT
  199. elif args.filter == "linear":
  200. filter = TF_LINEAR
  201. elif args.filter == "nearest":
  202. filter = TF_NEAREST
  203. else:
  204. assert 0, "See file"
  205. if args.mip_count <= 0:
  206. parser.error("Wrong number of mipmaps")
  207. config = Config()
  208. config.in_files = args.input
  209. config.out_file = args.output
  210. config.fast = args.fast
  211. config.type = typ
  212. config.normal = args.normal
  213. config.convert_path = args.convert_path
  214. config.no_alpha = args.no_alpha
  215. config.store_uncompressed = args.store_uncompressed
  216. config.to_linear_rgb = args.to_linear_rgb
  217. config.filter = filter
  218. config.mip_count = args.mip_count
  219. if args.store_etc:
  220. config.compressed_formats = config.compressed_formats | DC_ETC2
  221. if args.store_s3tc:
  222. config.compressed_formats = config.compressed_formats | DC_S3TC
  223. return config
  224. def identify_image(in_file):
  225. """ Return the size of the input image and the internal format """
  226. img = Image.open(in_file)
  227. if img.mode == "RGB":
  228. color_format = CF_RGB8
  229. elif img.mode == "RGBA":
  230. color_format = CF_RGBA8
  231. else:
  232. raise Exception("Wrong format %s" % img.mode)
  233. # print some stuff and return
  234. printi("width: %s, height: %s color format: %s" % (img.width, img.height, img.mode))
  235. return (color_format, img.width, img.height)
  236. def create_mipmaps(in_file, tmp_dir, width_, height_, color_format, to_linear_rgb, max_mip_count):
  237. """ Create a number of images for all mipmaps """
  238. printi("Generate mipmaps")
  239. width = width_
  240. height = height_
  241. mips_fnames = []
  242. while width >= 4 and height >= 4:
  243. size_str = "%dx%d" % (width, height)
  244. out_file_str = os.path.join(tmp_dir, get_base_fname(in_file)) + "." + size_str
  245. mips_fnames.append(out_file_str)
  246. args = ["convert", in_file]
  247. # to linear
  248. if to_linear_rgb:
  249. if color_format != CF_RGB8:
  250. raise Exception("to linear RGB only supported for RGB textures")
  251. args.append("-set")
  252. args.append("colorspace")
  253. args.append("sRGB")
  254. args.append("-colorspace")
  255. args.append("RGB")
  256. # Add this because it will automatically convert gray-like images to grayscale TGAs
  257. #args.append("-type")
  258. #args.append("TrueColor")
  259. # resize
  260. args.append("-resize")
  261. args.append(size_str)
  262. # alpha
  263. args.append("-alpha")
  264. if color_format == CF_RGB8:
  265. args.append("deactivate")
  266. else:
  267. args.append("activate")
  268. args.append(out_file_str + ".png")
  269. printi(" " + " ".join(args))
  270. subprocess.check_call(args)
  271. if (len(mips_fnames) == max_mip_count):
  272. break
  273. width = width / 2
  274. height = height / 2
  275. return mips_fnames
  276. def create_etc_images(mips_fnames, tmp_dir, fast, color_format, convert_path):
  277. """ Create the etc files """
  278. printi("Creating ETC images")
  279. # Copy the convert tool to the working dir so that etcpack will see it
  280. shutil.copy2(convert_path, \
  281. os.path.join(tmp_dir, os.path.basename(convert_path)))
  282. for fname in mips_fnames:
  283. # Unfortunately we need to flip the image. Use convert again
  284. in_fname = fname + ".tga"
  285. flipped_fname = fname + "_flip.tga"
  286. args = ["convert", in_fname, "-flip", flipped_fname]
  287. subprocess.check_call(args)
  288. in_fname = flipped_fname
  289. printi(" %s" % in_fname)
  290. args = ["etcpack", in_fname, tmp_dir, "-c", "etc2"]
  291. if fast:
  292. args.append("-s")
  293. args.append("fast")
  294. args.append("-f")
  295. if color_format == CF_RGB8:
  296. args.append("RGB")
  297. else:
  298. args.append("RGBA")
  299. # Call the executable AND change the working directory so that etcpack will find convert
  300. subprocess.check_call(args, stdout=subprocess.PIPE, cwd=tmp_dir)
  301. def create_dds_images(mips_fnames, tmp_dir, fast, color_format, normal):
  302. """ Create the dds files """
  303. printi("Creating DDS images")
  304. for fname in mips_fnames:
  305. # Unfortunately we need to flip the image. Use convert again
  306. in_fname = fname + ".png"
  307. """
  308. flipped_fname = fname + "_flip.tga"
  309. args = ["convert", in_fname, "-flip", flipped_fname]
  310. subprocess.check_call(args)
  311. in_fname = flipped_fname
  312. """
  313. # Continue
  314. out_fname = os.path.join(tmp_dir, os.path.basename(fname) + ".dds")
  315. args = ["CompressonatorCLI", "-nomipmap"]
  316. if color_format == CF_RGB8:
  317. args.append("-fd")
  318. args.append("BC1")
  319. elif color_format == CF_RGBA8:
  320. args.append("-fd")
  321. args.append("BC3")
  322. args.append(in_fname)
  323. args.append(out_fname)
  324. printi(" " + " ".join(args))
  325. subprocess.check_call(args, stdout=subprocess.PIPE)
  326. def write_raw(tex_file, fname, width, height, color_format):
  327. """ Append raw data to the AnKi texture file """
  328. printi(" Appending %s" % fname)
  329. img = Image.open(fname)
  330. if img.size[0] != width or img.size[1] != height:
  331. raise Exception("Expecting different image size")
  332. if (img.mode == "RGB" and color_format != CF_RGB8) or (img.mode == "RGBA" and color_format != CF_RGBA8):
  333. raise Exception("Expecting different image format")
  334. if color_format == CF_RGB8:
  335. img = img.convert("RGB")
  336. else:
  337. img = img.convert("RGBA")
  338. data = bytearray()
  339. for h in range(0, int(height)):
  340. for w in range(0, int(width)):
  341. if color_format == CF_RGBA8:
  342. r, g, b, a = img.getpixel((w, h))
  343. data.append(r)
  344. data.append(g)
  345. data.append(b)
  346. data.append(a)
  347. else:
  348. r, g, b = img.getpixel((w, h))
  349. data.append(r)
  350. data.append(g)
  351. data.append(b)
  352. tex_file.write(data)
  353. def write_s3tc(out_file, fname, width, height, color_format):
  354. """ Append s3tc data to the AnKi texture file """
  355. # Read header
  356. printi(" Appending %s" % fname)
  357. in_file = open(fname, "rb")
  358. header_bin = in_file.read(sizeof(DdsHeader()))
  359. if len(header_bin) != sizeof(DdsHeader()):
  360. raise Exception("Failed to read DDS header")
  361. dds_header = DdsHeader()
  362. dds_header.from_bytearray(header_bin)
  363. if dds_header.dwWidth != width or dds_header.dwHeight != height:
  364. raise Exception("Incorrect width")
  365. if color_format == CF_RGB8 and dds_header.dwFourCC != b"DXT1":
  366. raise Exception("Incorrect format. Expecting DXT1")
  367. if color_format == CF_RGBA8 and dds_header.dwFourCC != b"DXT5":
  368. raise Exception("Incorrect format. Expecting DXT5")
  369. # Read and write the data
  370. if color_format == CF_RGB8:
  371. block_size = 8
  372. else:
  373. block_size = 16
  374. data_size = (width / 4) * (height / 4) * block_size
  375. data = in_file.read(int(data_size))
  376. if len(data) != data_size:
  377. raise Exception("Failed to read DDS data")
  378. # Make sure that the file doesn't contain any more data
  379. tmp = in_file.read(1)
  380. if len(tmp) != 0:
  381. printw(" File shouldn't contain more data")
  382. out_file.write(data)
  383. def write_etc(out_file, fname, width, height, color_format):
  384. """ Append etc2 data to the AnKi texture file """
  385. printi(" Appending %s" % fname)
  386. # Read header
  387. in_file = open(fname, "rb")
  388. header = in_file.read(PkmHeader.get_size())
  389. if len(header) != PkmHeader.get_size():
  390. raise Exception("Failed to read PKM header")
  391. pkm_header = PkmHeader(header)
  392. if pkm_header.magic != "PKM 20":
  393. raise Exception("Incorrect PKM header")
  394. if width != pkm_header.width or height != pkm_header.height:
  395. raise Exception("Incorrect PKM width or height")
  396. # Read and write the data
  397. data_size = (pkm_header.width / 4) * (pkm_header.height / 4) * 8
  398. data = in_file.read(data_size)
  399. if len(data) != data_size:
  400. raise Exception("Failed to read PKM data")
  401. # Make sure that the file doesn't contain any more data
  402. tmp = in_file.read(1)
  403. if len(tmp) != 0:
  404. printw(" File shouldn't contain more data")
  405. out_file.write(data)
  406. def convert(config):
  407. """ This is the function that does all the work """
  408. # Invoke app named "identify" to get internal format and width and height
  409. (color_format, width, height) = identify_image(config.in_files[0])
  410. if not is_power2(width) or not is_power2(height):
  411. raise Exception("Image width and height should power of 2")
  412. if color_format == CF_RGBA8 and config.normal:
  413. raise Exception("RGBA image and normal does not make much sense")
  414. for i in range(1, len(config.in_files)):
  415. (color_format_2, width_2, height_2) = identify_image(config.in_files[i])
  416. if width != width_2 or height != height_2 \
  417. or color_format != color_format_2:
  418. raise Exception("Images are not same size and color space")
  419. if config.no_alpha:
  420. color_format = CF_RGB8
  421. # Create images
  422. for in_file in config.in_files:
  423. mips_fnames = create_mipmaps(in_file, config.tmp_dir, width, height, color_format, config.to_linear_rgb,
  424. config.mip_count)
  425. # Create etc images
  426. if config.compressed_formats & DC_ETC2:
  427. create_etc_images(mips_fnames, config.tmp_dir, config.fast, color_format, config.convert_path)
  428. # Create dds images
  429. if config.compressed_formats & DC_S3TC:
  430. create_dds_images(mips_fnames, config.tmp_dir, config.fast, color_format, config.normal)
  431. # Open file
  432. fname = config.out_file
  433. printi("Writing %s" % fname)
  434. tex_file = open(fname, "wb")
  435. # Write header
  436. ak_format = "8sIIIIIIII"
  437. data_compression = config.compressed_formats
  438. if config.store_uncompressed:
  439. data_compression = data_compression | DC_RAW
  440. buff = struct.pack(ak_format, b"ANKITEX1", width, height, len(config.in_files), config.type, color_format,
  441. data_compression, config.normal, len(mips_fnames))
  442. tex_file.write(buff)
  443. # Write header padding
  444. header_padding_size = 128 - struct.calcsize(ak_format)
  445. if header_padding_size != 88:
  446. raise Exception("Check the header")
  447. padding = bytearray()
  448. for i in range(0, header_padding_size):
  449. padding.append(0)
  450. tex_file.write(padding)
  451. # For each compression
  452. for compression in range(0, 3):
  453. tmp_width = width
  454. tmp_height = height
  455. # For each level
  456. for i in range(0, len(mips_fnames)):
  457. # For each image
  458. for in_file in config.in_files:
  459. size_str = "%dx%d" % (tmp_width, tmp_height)
  460. in_base_fname = os.path.join(config.tmp_dir, get_base_fname(in_file)) + "." + size_str
  461. # Write RAW
  462. if compression == 0 and config.store_uncompressed:
  463. write_raw(tex_file, in_base_fname + ".png", tmp_width, tmp_height, color_format)
  464. # Write S3TC
  465. elif compression == 1 and (config.compressed_formats & DC_S3TC):
  466. write_s3tc(tex_file, in_base_fname + ".dds", tmp_width, tmp_height, color_format)
  467. # Write ETC
  468. elif compression == 2 and (config.compressed_formats & DC_ETC2):
  469. write_etc(tex_file, in_base_fname + "_flip.pkm", tmp_width, tmp_height, color_format)
  470. tmp_width = tmp_width / 2
  471. tmp_height = tmp_height / 2
  472. def main():
  473. """ The main """
  474. # Parse cmd line args
  475. config = parse_commandline()
  476. if config.type == TT_CUBE and len(config.in_files) != 6:
  477. raise Exception("Not enough images for cube generation")
  478. if (config.type == TT_3D or config.type == TT_2D_ARRAY) and len(config.in_files) < 2:
  479. #raise Exception("Not enough images for 2DArray/3D texture")
  480. printw("Not enough images for 2DArray/3D texture")
  481. printi("Number of images %u" % len(config.in_files))
  482. if config.type == TT_2D and len(config.in_files) != 1:
  483. raise Exception("Only one image for 2D textures needed")
  484. if not os.path.isfile(config.convert_path):
  485. raise Exception("Tool convert not found: " + config.convert_path)
  486. # Setup the temp dir
  487. config.tmp_dir = tempfile.mkdtemp("_ankitex")
  488. # Do the work
  489. try:
  490. convert(config)
  491. finally:
  492. shutil.rmtree(config.tmp_dir)
  493. #i = 0
  494. # Done
  495. printi("Done!")
  496. if __name__ == "__main__":
  497. main()