process_atlas.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals, print_function
  3. try:
  4. import Image
  5. import ImageChops
  6. except ImportError:
  7. from PIL import Image
  8. from PIL import ImageChops
  9. import os
  10. import struct
  11. import base64
  12. from . import atlas
  13. from . import process
  14. def isImagesIdentical(im1, im2):
  15. if im1.size[0] == 0 or im1.size[1] == 0:
  16. return False
  17. if im2.size[0] == 0 or im2.size[1] == 0:
  18. return False
  19. bbox = ImageChops.difference(im1, im2).getbbox()
  20. r = bbox is None
  21. return r
  22. def as_int(attr, df=0):
  23. if not attr:
  24. return df
  25. return int(attr)
  26. def as_float(attr, df=0):
  27. if not attr:
  28. return df
  29. return float(attr)
  30. def as_bool(attr, df=False):
  31. if not attr:
  32. return df
  33. lw = attr.lower()
  34. return lw == "true" or lw == "1"
  35. def fixImage_unused(image):
  36. if image.mode != "RGBA":
  37. return image
  38. data = image.load()
  39. for y in range(image.size[1]):
  40. for x in range(image.size[0]):
  41. a = data[x, y][3]
  42. # if a == 0 or a == 1:
  43. if a == 0:
  44. data[x, y] = (0, 0, 0, 0)
  45. return image
  46. def premultipliedAlpha(image):
  47. if image.mode != "RGBA":
  48. return image
  49. data = image.load()
  50. for y in range(image.size[1]):
  51. for x in range(image.size[0]):
  52. dt = data[x, y]
  53. a = dt[3]
  54. data[x, y] = ((dt[0] * a) / 255, (dt[1] * a) /
  55. 255, (dt[2] * a) / 255, a)
  56. return image
  57. def bbox(x, y, w, h):
  58. return (x, y, x + w, y + h)
  59. class alphaData(object):
  60. def __init__(self, w, h, data):
  61. self.w = w
  62. self.h = h
  63. self.data = data
  64. class frame(object):
  65. def __init__(self, image, bbox, image_element, rs, adata, extend):
  66. self.image = image
  67. self.image_element = image_element
  68. self.adata = adata
  69. self.extend = extend
  70. self.node = None
  71. self.resanim = rs
  72. self.border_top = self.border_left = 2
  73. self.border_right = self.border_bottom = 1
  74. self.identicalWith = None
  75. if not bbox:
  76. bbox = (0, 0, 1, 1)
  77. self.bbox = bbox
  78. class ResAnim(object):
  79. def __init__(self):
  80. self.frames = []
  81. self.name = ""
  82. self.frame_size2 = (1, 1) # original size * scale_factor
  83. self.frame_scale2 = 1.0
  84. self.columns = 0
  85. self.rows = 0
  86. self.walker = None
  87. def frame_cmp_sort(f1, f2):
  88. return f2.image.size[0] - f1.image.size[0]
  89. def applyScale(intVal, scale):
  90. return int(intVal * scale + 0.5)
  91. def applyScale2(x, scale):
  92. initialX = x
  93. best = None
  94. while 1:
  95. X = x * scale
  96. d = abs(X - int(X))
  97. if not best:
  98. best = (d, X)
  99. if best[0] > d:
  100. best = (d, X)
  101. eps = 0.00000001
  102. if d < eps:
  103. return int(X)
  104. if x > initialX * 2:
  105. return int(best[1])
  106. x += 1
  107. def nextPOT(v):
  108. v = v - 1
  109. v = v | (v >> 1)
  110. v = v | (v >> 2)
  111. v = v | (v >> 4)
  112. v = v | (v >> 8)
  113. v = v | (v >> 16)
  114. return v + 1
  115. class settings(object):
  116. def __init__(self):
  117. self.get_size = None
  118. self.set_node = None
  119. self.padding = 1
  120. self.max_w = 2048
  121. self.max_h = 2048
  122. self.atlasses = []
  123. self.square = False
  124. self.npot = False
  125. def makeAlpha(a):
  126. def roundUp(v, multiple):
  127. if multiple == 0:
  128. return v
  129. rem = v % multiple
  130. if rem == 0:
  131. return v
  132. res = v + multiple - rem
  133. return res
  134. try:
  135. asmall = a.resize(
  136. (int(a.size[0] / 4), int(a.size[1] / 4)), Image.ANTIALIAS)
  137. except ValueError:
  138. return None
  139. b = asmall.getextrema()
  140. if not b:
  141. return None
  142. if b[0] > 10:
  143. return None
  144. asmall_size = asmall.size
  145. BITS = 32
  146. val = roundUp(asmall_size[0], BITS)
  147. lineLen = val // BITS
  148. buff = b''
  149. for y in range(asmall_size[1]):
  150. line = [0 for x in range(lineLen)]
  151. for x in range(asmall_size[0]):
  152. p = asmall.getpixel((x, y))
  153. if p > 5:
  154. n = x // BITS
  155. b = x % BITS
  156. line[n] |= 1 << b
  157. for v in line:
  158. buff += struct.pack("<I", v)
  159. adata = alphaData(asmall_size[0], asmall_size[1], buff)
  160. return adata
  161. def pack(st, frames, sw, sh):
  162. atl = atlas.Atlas(st.padding, sw, sh)
  163. not_packed = []
  164. for fr in frames:
  165. if fr.identicalWith:
  166. continue
  167. ns = st.get_size(fr)
  168. node = atl.add(ns[0], ns[1], fr)
  169. if not node:
  170. not_packed.append(fr)
  171. else:
  172. st.set_node(fr, node)
  173. # atl.add(250, 250)
  174. # atl.save()
  175. return not_packed, atl
  176. def get_pow2list(npot, mn, mx):
  177. # ls = []
  178. if npot:
  179. while 1:
  180. yield mn
  181. mn += 64
  182. if mn > mx:
  183. yield mx
  184. break
  185. else:
  186. mn = nextPOT(mn)
  187. mx = nextPOT(mx)
  188. while 1:
  189. yield mn
  190. mn *= 2
  191. if mn > mx:
  192. break
  193. def pck(st, frames):
  194. if 0:
  195. st = settings()
  196. while frames:
  197. sq = 0
  198. min_w = 64
  199. min_h = 64
  200. for f in frames:
  201. size = st.get_size(f)
  202. sq += size[0] * size[1]
  203. min_w = max(min_w, size[0])
  204. min_h = max(min_h, size[1])
  205. max_w = st.max_w
  206. max_h = st.max_h
  207. if st.square:
  208. min_w = min_h = max(min_w, min_h)
  209. max_w = max_h = max(max_w, max_h)
  210. sizes_w = list(get_pow2list(st.npot, min_w, max_w))
  211. sizes_h = list(get_pow2list(st.npot, min_h, max_h))
  212. for sw in sizes_w:
  213. for sh in sizes_h:
  214. end = sh == sizes_h[-1] and sw == sizes_w[-1]
  215. if st.square and sw != sh:
  216. continue
  217. if sw * sh < sq and not end:
  218. continue
  219. not_packed, bn = pack(st, frames, sw, sh)
  220. st.atlasses.append(bn)
  221. if not not_packed:
  222. return
  223. if end:
  224. frames = not_packed
  225. else:
  226. st.atlasses.pop()
  227. def processRS(context, walker):
  228. image_el = walker.root
  229. image_name = image_el.getAttribute("file")
  230. if not image_name:
  231. return None
  232. file_path = walker.getPath("file")
  233. # print image_path
  234. image = None
  235. # fn = self._getExistsFile(image_path)
  236. # virtual_width = 1
  237. # virtual_height = 1
  238. path = context.src_data + file_path
  239. try:
  240. image = Image.open(path)
  241. except IOError:
  242. pass
  243. if image:
  244. # virtual_width = int(image.size[0] * scale + 0.001)
  245. # virtual_height= int(image.size[1] * scale + 0.001)
  246. pass
  247. else:
  248. context.error("can't find image:\n%s\n" % (path, ))
  249. image = Image.new("RGBA", (0, 0))
  250. resAnim = ResAnim()
  251. resAnim.walker = walker
  252. resAnim.image = image
  253. resAnim.name = image_name
  254. columns = as_int(image_el.getAttribute("cols"))
  255. frame_width = as_int(image_el.getAttribute("frame_width"))
  256. rows = as_int(image_el.getAttribute("rows"))
  257. frame_height = as_int(image_el.getAttribute("frame_height"))
  258. border = as_int(image_el.getAttribute("border"))
  259. trim = as_bool(image_el.getAttribute("trim"), True)
  260. extend = as_bool(image_el.getAttribute("extend"), True)
  261. if not extend:
  262. pass
  263. # sq = as_float(image_el.getAttribute("scale_quality"), 1)
  264. # next.scale_quality *= sq
  265. if not columns:
  266. columns = 1
  267. if not rows:
  268. rows = 1
  269. if frame_width:
  270. columns = image.size[0] / frame_width
  271. else:
  272. frame_width = image.size[0] / columns
  273. if frame_height:
  274. rows = image.size[1] / frame_height
  275. else:
  276. frame_height = image.size[1] / rows
  277. size_warning = False
  278. if frame_width * columns != image.size[0]:
  279. size_warning = True
  280. context.warning("image has width %d and %d columns:" %
  281. (image.size[0], columns))
  282. if frame_height * rows != image.size[1]:
  283. size_warning = True
  284. context.warning("<image has height %d and %d rows:" %
  285. (image.size[1], rows))
  286. if size_warning:
  287. context.warnings += 1
  288. scale_factor = walker.scale_factor
  289. resAnim.frame_scale2 = scale_factor
  290. finalScale = 1
  291. upscale = False
  292. if context.args.resize:
  293. max_scale = 1.0 / scale_factor
  294. finalScale = context.scale * walker.scale_quality
  295. if finalScale > max_scale:
  296. if not context.args.upscale:
  297. finalScale = max_scale
  298. else:
  299. upscale = True
  300. resAnim.frame_scale2 = 1.0 / finalScale
  301. finalScale = finalScale * scale_factor
  302. frame_size = (applyScale(frame_width, finalScale),
  303. applyScale(frame_height, finalScale))
  304. resAnim.frame_size2 = (applyScale(frame_width, scale_factor),
  305. applyScale(frame_height, scale_factor))
  306. resAnim.columns = columns
  307. resAnim.rows = rows
  308. for row in range(rows):
  309. for col in range(columns):
  310. rect = (int(col * frame_width),
  311. int(row * frame_height),
  312. int((col + 1) * frame_width),
  313. int((row + 1) * frame_height))
  314. frame_image = image.crop(rect)
  315. def resize():
  316. ax = applyScale2(frame_width, finalScale)
  317. ay = applyScale2(frame_height, finalScale)
  318. bx = int(ax / finalScale)
  319. by = int(ay / finalScale)
  320. im = Image.new("RGBA", (bx, by))
  321. im.paste(frame_image, (0, 0, frame_image.size[
  322. 0], frame_image.size[1]))
  323. frame_image = im.resize((ax, ay), Image.ANTIALIAS)
  324. frame_image = frame_image.crop(
  325. (0, 0, frame_size[0], frame_size[1]))
  326. resize_filter = Image.ANTIALIAS
  327. if upscale:
  328. resize_filter = Image.BICUBIC
  329. if context.args.resize:
  330. if as_bool(image_el.getAttribute("trueds")) or (not trim and not extend) or context.args.simple_downsample:
  331. frame_image = frame_image.resize(
  332. (frame_size[0], frame_size[1]), resize_filter)
  333. else:
  334. ax = applyScale2(frame_width, finalScale)
  335. ay = applyScale2(frame_height, finalScale)
  336. bx = int(ax / finalScale)
  337. by = int(ay / finalScale)
  338. im = Image.new("RGBA", (bx, by))
  339. im.paste(frame_image, (0, 0, frame_image.size[
  340. 0], frame_image.size[1]))
  341. frame_image = im.resize((ax, ay), resize_filter)
  342. frame_image = frame_image.crop(
  343. (0, 0, frame_size[0], frame_size[1]))
  344. adata = None
  345. if image.mode == "RGBA" and trim:
  346. r, g, b, a = frame_image.split()
  347. tt = context.args.trim_threshold
  348. if tt:
  349. a = a.point(lambda p: p - tt)
  350. if walker.hit_test:
  351. adata = makeAlpha(a)
  352. frame_bbox = a.getbbox()
  353. else:
  354. frame_bbox = (0, 0, frame_image.size[0], frame_image.size[1])
  355. if not frame_bbox:
  356. frame_bbox = (0, 0, 0, 0)
  357. frame_image = frame_image.crop(frame_bbox)
  358. fr = frame(frame_image, frame_bbox, image_el, resAnim, adata, extend)
  359. if border:
  360. fr.border_left = fr.border_right = fr.border_top = fr.border_bottom = border
  361. if not extend:
  362. fr.border_left = fr.border_right = fr.border_top = fr.border_bottom = 0
  363. for f in resAnim.frames:
  364. if isImagesIdentical(f.image, fr.image):
  365. fr.identicalWith = f
  366. if f.identicalWith:
  367. fr.identicalWith = f.identicalWith
  368. resAnim.frames.append(fr)
  369. return resAnim
  370. class atlas_Processor(process.Process):
  371. node_id = "atlas"
  372. def __init__(self):
  373. self.atlas_group_id = 0
  374. def process(self, context, walker):
  375. self.atlas_group_id += 1
  376. # meta = context.add_meta()
  377. anims = []
  378. frames = []
  379. alphaData = ""
  380. while True:
  381. next = walker.next()
  382. if 0:
  383. import xml_processor
  384. next = xml_processor.XmlWalker()
  385. if not next:
  386. break
  387. anim = processRS(context, next)
  388. if anim:
  389. anims.append(anim)
  390. frames.extend(anim.frames)
  391. # sort frames by size
  392. #frames = sorted(frames, key = lambda fr: -fr.image.size[1])
  393. #frames = sorted(frames, key = lambda fr: -fr.image.size[0])
  394. frames = sorted(frames, key=lambda fr: -1 * max(
  395. fr.image.size[0], fr.image.size[1]) * max(fr.image.size[0], fr.image.size[1]))
  396. sq = 0
  397. for f in frames:
  398. sq += f.image.size[0] * f.image.size[1]
  399. compression = context.compression
  400. def get_aligned_frame_size(frame):
  401. def align_pixel(p):
  402. if not compression or compression == "no":
  403. return p + 1
  404. align = 4
  405. v = p % align
  406. if v == 0:
  407. p += align
  408. else:
  409. p += 8 - v
  410. return p
  411. sz = frame.image.size
  412. if frame.extend:
  413. return align_pixel(sz[0] + frame.border_left + frame.border_right), align_pixel(sz[1] + frame.border_top + frame.border_bottom)
  414. return sz
  415. def get_original_frame_size(frame):
  416. sz = frame.image.size
  417. return sz
  418. def set_node(frame, node):
  419. frame.node = node
  420. st = settings()
  421. st.npot = context._npot
  422. st.get_size = get_aligned_frame_size
  423. st.set_node = set_node
  424. st.max_w = context.args.max_width
  425. st.max_h = context.args.max_height
  426. st.square = context.compression == "pvrtc"
  427. st.padding = 0
  428. if len(frames) == 1:
  429. st.get_size = get_original_frame_size
  430. pck(st, frames)
  431. # print "done"
  432. for atlas_id, atl in enumerate(st.atlasses):
  433. image = Image.new("RGBA", (atl.w, atl.h))
  434. for node in atl.nodes:
  435. fr = node.data
  436. x = node.rect.x + fr.border_left
  437. y = node.rect.y + fr.border_top
  438. sz = fr.image.size
  439. rect = bbox(x, y, sz[0], sz[1])
  440. if fr.extend:
  441. part = fr.image.crop(bbox(0, 0, sz[0], 1))
  442. image.paste(part, bbox(x, y - 1, sz[0], 1))
  443. part = fr.image.crop(bbox(0, sz[1] - 1, sz[0], 1))
  444. image.paste(part, bbox(x, y + sz[1], sz[0], 1))
  445. part = fr.image.crop(bbox(0, 0, 1, sz[1]))
  446. image.paste(part, bbox(x - 1, y, 1, sz[1]))
  447. part = fr.image.crop(bbox(sz[0] - 1, 0, 1, sz[1]))
  448. image.paste(part, bbox(x + sz[0], y, 1, sz[1]))
  449. image.paste(fr.image, rect)
  450. fr.atlas_id = atlas_id
  451. image_atlas_el = walker.root_meta.ownerDocument.createElement(
  452. "atlas")
  453. walker.root_meta.insertBefore(
  454. image_atlas_el, anims[0].walker.root_meta)
  455. # meta.appendChild(image_atlas_el)
  456. base_name = "%d_%d" % (self.atlas_group_id, atlas_id)
  457. ox_fmt = "r8g8b8a8"
  458. def compress(src, dest, fmt):
  459. cmd = context.helper.path_pvrtextool + \
  460. " -i %s -f %s,UBN,lRGB -o %s" % (src, fmt, dest)
  461. cmd += " -l" # alpha bleed
  462. if context.args.quality == "best":
  463. cmd += " -q pvrtcbest"
  464. else:
  465. cmd += " -q pvrtcfast"
  466. if context.args.dither:
  467. cmd += " -dither"
  468. cmd += " -shh" # silent
  469. os.system(cmd)
  470. if compression == "etc1":
  471. # premultipliedAlpha(v)
  472. r, g, b, a = image.split()
  473. rgb = Image.merge("RGB", (r, g, b))
  474. alpha = Image.merge("RGB", (a, a, a))
  475. base_alpha_name = base_name + "_alpha"
  476. alpha_path = context.get_inner_dest(base_alpha_name + ".png")
  477. alpha.save(alpha_path)
  478. image_atlas_el.setAttribute("alpha", base_alpha_name + ".png")
  479. path_base = base_name + ".png"
  480. rs = ".pvr"
  481. rgb_path = context.get_inner_dest(path_base)
  482. path = context.get_inner_dest(path_base)
  483. rgb.save(path)
  484. pkm_rgb = base_name + rs
  485. pkm_alpha = base_alpha_name + rs
  486. def compress_etc1(src, dest):
  487. compress(src, dest, "etc1")
  488. #os.system(context.etc1tool + "%s -o %s -f etc1" %(src, dest))
  489. ox_fmt = "ETC1"
  490. compress_etc1(rgb_path, context.get_inner_dest() + pkm_rgb)
  491. os.remove(rgb_path)
  492. image_atlas_el.setAttribute("file", pkm_rgb)
  493. compress_etc1(alpha_path, context.get_inner_dest() + pkm_alpha)
  494. os.remove(alpha_path)
  495. image_atlas_el.setAttribute("alpha", pkm_alpha)
  496. else:
  497. if context.args.nopng:
  498. path_base = base_name + ".tga"
  499. else:
  500. path_base = base_name + ".png"
  501. path = context.get_inner_dest(path_base)
  502. image_atlas_el.setAttribute("file", path_base)
  503. image.save(path)
  504. if context.compression == "pvrtc":
  505. ox_fmt = "PVRTC_4RGBA"
  506. compress(path, context.get_inner_dest(
  507. base_name + ".pvr"), "PVRTC1_4")
  508. image_atlas_el.setAttribute("file", base_name + ".pvr")
  509. os.remove(path)
  510. if context.compression == "pvrtc2":
  511. ox_fmt = "PVRTC2_4RGBA"
  512. compress(path, context.get_inner_dest(
  513. base_name + ".pvr"), "PVRTC2_4")
  514. image_atlas_el.setAttribute("file", base_name + ".pvr")
  515. os.remove(path)
  516. image_atlas_el.setAttribute("format", ox_fmt)
  517. image_atlas_el.setAttribute("w", str(image.size[0]))
  518. image_atlas_el.setAttribute("h", str(image.size[1]))
  519. alpha = b''
  520. for anim in anims:
  521. if 0:
  522. anim = ResAnim()
  523. image_frames_el = anim.walker.root_meta
  524. image_frames_el.setAttribute("fs", "%d,%d,%d,%d,%f" % (anim.columns, anim.rows,
  525. anim.frame_size2[
  526. 0], anim.frame_size2[1],
  527. anim.frame_scale2))
  528. adata = anim.frames[0].adata
  529. if adata:
  530. image_frames_el.setAttribute("ht", "%d,%d,%d,%d" % (
  531. len(alpha), len(adata.data), adata.w, adata.h))
  532. if context.debug:
  533. image_frames_el.setAttribute("debug_image", anim.name)
  534. data = ""
  535. for item in anim.frames:
  536. fr = item
  537. if item.identicalWith:
  538. fr = item.identicalWith
  539. data += "%d,%d,%d,%d,%d,%d,%d;" % (fr.atlas_id,
  540. fr.node.rect.x + fr.border_left, fr.node.rect.y + fr.border_top,
  541. fr.bbox[0], fr.bbox[1],
  542. fr.bbox[2] - fr.bbox[0], fr.bbox[3] - fr.bbox[1])
  543. if fr.adata:
  544. alpha += fr.adata.data
  545. text = image_frames_el.ownerDocument.createTextNode(data)
  546. image_frames_el.appendChild(text)
  547. if alpha:
  548. doc = walker.root_meta.ownerDocument
  549. alpha_el = doc.createElement("ht")
  550. adata_str = base64.b64encode(alpha)
  551. text = doc.createTextNode(adata_str.decode("utf-8"))
  552. alpha_el.setAttribute("len", str(len(adata_str)))
  553. alpha_el.appendChild(text)
  554. walker.root_meta.appendChild(alpha_el)