uvcalc_smart_project.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  1. # ##### BEGIN GPL LICENSE BLOCK #####
  2. #
  3. # This program is free software; you can redistribute it and/or
  4. # modify it under the terms of the GNU General Public License
  5. # as published by the Free Software Foundation; either version 2
  6. # of the License, or (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with this program; if not, write to the Free Software Foundation,
  15. # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  16. #
  17. # ##### END GPL LICENSE BLOCK #####
  18. # TODO <pep8 compliant>
  19. from mathutils import (
  20. Matrix,
  21. Vector,
  22. geometry,
  23. )
  24. import bpy
  25. from bpy.types import Operator
  26. DEG_TO_RAD = 0.017453292519943295 # pi/180.0
  27. # see bugs:
  28. # - T31598 (when too small).
  29. # - T48086 (when too big).
  30. SMALL_NUM = 1e-12
  31. global USER_FILL_HOLES
  32. global USER_FILL_HOLES_QUALITY
  33. USER_FILL_HOLES = None
  34. USER_FILL_HOLES_QUALITY = None
  35. def pointInTri2D(v, v1, v2, v3):
  36. key = v1.x, v1.y, v2.x, v2.y, v3.x, v3.y
  37. # Commented because its slower to do the bounds check, we should really cache the bounds info for each face.
  38. '''
  39. # BOUNDS CHECK
  40. xmin= 1000000
  41. ymin= 1000000
  42. xmax= -1000000
  43. ymax= -1000000
  44. for i in (0,2,4):
  45. x= key[i]
  46. y= key[i+1]
  47. if xmax<x: xmax= x
  48. if ymax<y: ymax= y
  49. if xmin>x: xmin= x
  50. if ymin>y: ymin= y
  51. x= v.x
  52. y= v.y
  53. if x<xmin or x>xmax or y < ymin or y > ymax:
  54. return False
  55. # Done with bounds check
  56. '''
  57. try:
  58. mtx = dict_matrix[key]
  59. if not mtx:
  60. return False
  61. except:
  62. side1 = v2 - v1
  63. side2 = v3 - v1
  64. nor = side1.cross(side2)
  65. mtx = Matrix((side1, side2, nor))
  66. # Zero area 2d tri, even tho we throw away zero area faces
  67. # the projection UV can result in a zero area UV.
  68. if not mtx.determinant():
  69. dict_matrix[key] = None
  70. return False
  71. mtx.invert()
  72. dict_matrix[key] = mtx
  73. uvw = (v - v1) @ mtx
  74. return 0 <= uvw[0] and 0 <= uvw[1] and uvw[0] + uvw[1] <= 1
  75. def boundsIsland(faces):
  76. minx = maxx = faces[0].uv[0][0] # Set initial bounds.
  77. miny = maxy = faces[0].uv[0][1]
  78. # print len(faces), minx, maxx, miny , maxy
  79. for f in faces:
  80. for uv in f.uv:
  81. x = uv.x
  82. y = uv.y
  83. if x < minx:
  84. minx = x
  85. if y < miny:
  86. miny = y
  87. if x > maxx:
  88. maxx = x
  89. if y > maxy:
  90. maxy = y
  91. return minx, miny, maxx, maxy
  92. """
  93. def boundsEdgeLoop(edges):
  94. minx = maxx = edges[0][0] # Set initial bounds.
  95. miny = maxy = edges[0][1]
  96. # print len(faces), minx, maxx, miny , maxy
  97. for ed in edges:
  98. for pt in ed:
  99. x= pt[0]
  100. y= pt[1]
  101. if x<minx: x= minx
  102. if y<miny: y= miny
  103. if x>maxx: x= maxx
  104. if y>maxy: y= maxy
  105. return minx, miny, maxx, maxy
  106. """
  107. # Turns the islands into a list of unpordered edges (Non internal)
  108. # Only for UV's
  109. # only returns outline edges for intersection tests. and unique points.
  110. def island2Edge(island):
  111. # Vert index edges
  112. edges = {}
  113. unique_points = {}
  114. for f in island:
  115. f_uvkey = list(map(tuple, f.uv))
  116. for vIdx in range(len(f_uvkey)):
  117. unique_points[f_uvkey[vIdx]] = f.uv[vIdx]
  118. if f.v[vIdx].index > f.v[vIdx - 1].index:
  119. i1 = vIdx - 1
  120. i2 = vIdx
  121. else:
  122. i1 = vIdx
  123. i2 = vIdx - 1
  124. try:
  125. edges[f_uvkey[i1], f_uvkey[i2]] *= 0 # sets any edge with more than 1 user to 0 are not returned.
  126. except:
  127. edges[f_uvkey[i1], f_uvkey[i2]] = (f.uv[i1] - f.uv[i2]).length
  128. # If 2 are the same then they will be together, but full [a,b] order is not correct.
  129. # Sort by length
  130. length_sorted_edges = [(Vector(key[0]), Vector(key[1]), value) for key, value in edges.items() if value != 0]
  131. length_sorted_edges.sort(key=lambda a: -a[2]) # largest first
  132. # Its okay to leave the length in there.
  133. # for e in length_sorted_edges:
  134. # e.pop(2)
  135. # return edges and unique points
  136. return length_sorted_edges, [v.to_3d() for v in unique_points.values()]
  137. def pointInIsland(pt, island):
  138. vec1, vec2, vec3 = Vector(), Vector(), Vector()
  139. for f in island:
  140. vec1.x, vec1.y = f.uv[0]
  141. vec2.x, vec2.y = f.uv[1]
  142. vec3.x, vec3.y = f.uv[2]
  143. if pointInTri2D(pt, vec1, vec2, vec3):
  144. return True
  145. if len(f.v) == 4:
  146. vec1.x, vec1.y = f.uv[0]
  147. vec2.x, vec2.y = f.uv[2]
  148. vec3.x, vec3.y = f.uv[3]
  149. if pointInTri2D(pt, vec1, vec2, vec3):
  150. return True
  151. return False
  152. # box is (left,bottom, right, top)
  153. def islandIntersectUvIsland(source, target, SourceOffset):
  154. # Is 1 point in the box, inside the vertLoops
  155. edgeLoopsSource = source[6] # Pretend this is offset
  156. edgeLoopsTarget = target[6]
  157. # Edge intersect test
  158. for ed in edgeLoopsSource:
  159. for seg in edgeLoopsTarget:
  160. i = geometry.intersect_line_line_2d(seg[0],
  161. seg[1],
  162. SourceOffset + ed[0],
  163. SourceOffset + ed[1],
  164. )
  165. if i:
  166. return 1 # LINE INTERSECTION
  167. # 1 test for source being totally inside target
  168. SourceOffset.resize_3d()
  169. for pv in source[7]:
  170. if pointInIsland(pv + SourceOffset, target[0]):
  171. return 2 # SOURCE INSIDE TARGET
  172. # 2 test for a part of the target being totally inside the source.
  173. for pv in target[7]:
  174. if pointInIsland(pv - SourceOffset, source[0]):
  175. return 3 # PART OF TARGET INSIDE SOURCE.
  176. return 0 # NO INTERSECTION
  177. def rotate_uvs(uv_points, angle):
  178. if angle != 0.0:
  179. mat = Matrix.Rotation(angle, 2)
  180. for uv in uv_points:
  181. uv[:] = mat @ uv
  182. def optiRotateUvIsland(faces):
  183. uv_points = [uv for f in faces for uv in f.uv]
  184. angle = geometry.box_fit_2d(uv_points)
  185. if angle != 0.0:
  186. rotate_uvs(uv_points, angle)
  187. # orient them vertically (could be an option)
  188. minx, miny, maxx, maxy = boundsIsland(faces)
  189. w, h = maxx - minx, maxy - miny
  190. # use epsilon so we don't randomly rotate (almost) perfect squares.
  191. if h + 0.00001 < w:
  192. from math import pi
  193. angle = pi / 2.0
  194. rotate_uvs(uv_points, angle)
  195. # Takes an island list and tries to find concave, hollow areas to pack smaller islands into.
  196. def mergeUvIslands(islandList):
  197. global USER_FILL_HOLES
  198. global USER_FILL_HOLES_QUALITY
  199. # Pack islands to bottom LHS
  200. # Sync with island
  201. # islandTotFaceArea = [] # A list of floats, each island area
  202. # islandArea = [] # a list of tuples ( area, w,h)
  203. decoratedIslandList = []
  204. islandIdx = len(islandList)
  205. while islandIdx:
  206. islandIdx -= 1
  207. minx, miny, maxx, maxy = boundsIsland(islandList[islandIdx])
  208. w, h = maxx - minx, maxy - miny
  209. totFaceArea = 0
  210. offset = Vector((minx, miny))
  211. for f in islandList[islandIdx]:
  212. for uv in f.uv:
  213. uv -= offset
  214. totFaceArea += f.area
  215. islandBoundsArea = w * h
  216. efficiency = abs(islandBoundsArea - totFaceArea)
  217. # UV Edge list used for intersections as well as unique points.
  218. edges, uniqueEdgePoints = island2Edge(islandList[islandIdx])
  219. decoratedIslandList.append([islandList[islandIdx], totFaceArea, efficiency, islandBoundsArea, w, h, edges, uniqueEdgePoints])
  220. # Sort by island bounding box area, smallest face area first.
  221. # no.. chance that to most simple edge loop first.
  222. decoratedIslandListAreaSort = decoratedIslandList[:]
  223. decoratedIslandListAreaSort.sort(key=lambda A: A[3])
  224. # sort by efficiency, Least Efficient first.
  225. decoratedIslandListEfficSort = decoratedIslandList[:]
  226. # decoratedIslandListEfficSort.sort(lambda A, B: cmp(B[2], A[2]))
  227. decoratedIslandListEfficSort.sort(key=lambda A: -A[2])
  228. # ================================================== THESE CAN BE TWEAKED.
  229. # This is a quality value for the number of tests.
  230. # from 1 to 4, generic quality value is from 1 to 100
  231. USER_STEP_QUALITY = ((USER_FILL_HOLES_QUALITY - 1) / 25.0) + 1
  232. # If 100 will test as long as there is enough free space.
  233. # this is rarely enough, and testing takes a while, so lower quality speeds this up.
  234. # 1 means they have the same quality
  235. USER_FREE_SPACE_TO_TEST_QUALITY = 1 + (((100 - USER_FILL_HOLES_QUALITY) / 100.0) * 5)
  236. # print 'USER_STEP_QUALITY', USER_STEP_QUALITY
  237. # print 'USER_FREE_SPACE_TO_TEST_QUALITY', USER_FREE_SPACE_TO_TEST_QUALITY
  238. removedCount = 0
  239. areaIslandIdx = 0
  240. ctrl = Window.Qual.CTRL
  241. BREAK = False
  242. while areaIslandIdx < len(decoratedIslandListAreaSort) and not BREAK:
  243. sourceIsland = decoratedIslandListAreaSort[areaIslandIdx]
  244. # Already packed?
  245. if not sourceIsland[0]:
  246. areaIslandIdx += 1
  247. else:
  248. efficIslandIdx = 0
  249. while efficIslandIdx < len(decoratedIslandListEfficSort) and not BREAK:
  250. if Window.GetKeyQualifiers() & ctrl:
  251. BREAK = True
  252. break
  253. # Now we have 2 islands, if the efficiency of the islands lowers there's an
  254. # increasing likely hood that we can fit merge into the bigger UV island.
  255. # this ensures a tight fit.
  256. # Just use figures we have about user/unused area to see if they might fit.
  257. targetIsland = decoratedIslandListEfficSort[efficIslandIdx]
  258. if sourceIsland[0] == targetIsland[0] or\
  259. not targetIsland[0] or\
  260. not sourceIsland[0]:
  261. pass
  262. else:
  263. #~ ([island, totFaceArea, efficiency, islandArea, w,h])
  264. # Wasted space on target is greater then UV bounding island area.
  265. #~ if targetIsland[3] > (sourceIsland[2]) and\ #
  266. # ~ print USER_FREE_SPACE_TO_TEST_QUALITY
  267. if targetIsland[2] > (sourceIsland[1] * USER_FREE_SPACE_TO_TEST_QUALITY) and\
  268. targetIsland[4] > sourceIsland[4] and\
  269. targetIsland[5] > sourceIsland[5]:
  270. # DEBUG # print '%.10f %.10f' % (targetIsland[3], sourceIsland[1])
  271. # These enough spare space lets move the box until it fits
  272. # How many times does the source fit into the target x/y
  273. blockTestXUnit = targetIsland[4] / sourceIsland[4]
  274. blockTestYUnit = targetIsland[5] / sourceIsland[5]
  275. boxLeft = 0
  276. # Distance we can move between whilst staying inside the targets bounds.
  277. testWidth = targetIsland[4] - sourceIsland[4]
  278. testHeight = targetIsland[5] - sourceIsland[5]
  279. # Increment we move each test. x/y
  280. xIncrement = (testWidth / (blockTestXUnit * ((USER_STEP_QUALITY / 50) + 0.1)))
  281. yIncrement = (testHeight / (blockTestYUnit * ((USER_STEP_QUALITY / 50) + 0.1)))
  282. # Make sure were not moving less then a 3rg of our width/height
  283. if xIncrement < sourceIsland[4] / 3:
  284. xIncrement = sourceIsland[4]
  285. if yIncrement < sourceIsland[5] / 3:
  286. yIncrement = sourceIsland[5]
  287. boxLeft = 0 # Start 1 back so we can jump into the loop.
  288. boxBottom = 0 # -yIncrement
  289. # ~ testcount= 0
  290. while boxBottom <= testHeight:
  291. # Should we use this? - not needed for now.
  292. # ~ if Window.GetKeyQualifiers() & ctrl:
  293. # ~ BREAK= True
  294. # ~ break
  295. # testcount+=1
  296. # print 'Testing intersect'
  297. Intersect = islandIntersectUvIsland(sourceIsland, targetIsland, Vector((boxLeft, boxBottom)))
  298. # print 'Done', Intersect
  299. if Intersect == 1: # Line intersect, don't bother with this any more
  300. pass
  301. if Intersect == 2: # Source inside target
  302. """
  303. We have an intersection, if we are inside the target
  304. then move us 1 whole width across,
  305. Its possible this is a bad idea since 2 skinny Angular faces
  306. could join without 1 whole move, but its a lot more optimal to speed this up
  307. since we have already tested for it.
  308. It gives about 10% speedup with minimal errors.
  309. """
  310. # Move the test along its width + SMALL_NUM
  311. #boxLeft += sourceIsland[4] + SMALL_NUM
  312. boxLeft += sourceIsland[4]
  313. elif Intersect == 0: # No intersection?? Place it.
  314. # Progress
  315. removedCount += 1
  316. # XXX Window.DrawProgressBar(0.0, 'Merged: %i islands, Ctrl to finish early.' % removedCount)
  317. # Move faces into new island and offset
  318. targetIsland[0].extend(sourceIsland[0])
  319. offset = Vector((boxLeft, boxBottom))
  320. for f in sourceIsland[0]:
  321. for uv in f.uv:
  322. uv += offset
  323. del sourceIsland[0][:] # Empty
  324. # Move edge loop into new and offset.
  325. # targetIsland[6].extend(sourceIsland[6])
  326. # while sourceIsland[6]:
  327. targetIsland[6].extend([(
  328. (e[0] + offset, e[1] + offset, e[2])
  329. ) for e in sourceIsland[6]])
  330. del sourceIsland[6][:] # Empty
  331. # Sort by edge length, reverse so biggest are first.
  332. try:
  333. targetIsland[6].sort(key=lambda A: A[2])
  334. except:
  335. targetIsland[6].sort(lambda B, A: cmp(A[2], B[2]))
  336. targetIsland[7].extend(sourceIsland[7])
  337. offset = Vector((boxLeft, boxBottom, 0.0))
  338. for p in sourceIsland[7]:
  339. p += offset
  340. del sourceIsland[7][:]
  341. # Decrement the efficiency
  342. targetIsland[1] += sourceIsland[1] # Increment totFaceArea
  343. targetIsland[2] -= sourceIsland[1] # Decrement efficiency
  344. # IF we ever used these again, should set to 0, eg
  345. sourceIsland[2] = 0 # No area if anyone wants to know
  346. break
  347. # INCREMENT NEXT LOCATION
  348. if boxLeft > testWidth:
  349. boxBottom += yIncrement
  350. boxLeft = 0.0
  351. else:
  352. boxLeft += xIncrement
  353. # print testcount
  354. efficIslandIdx += 1
  355. areaIslandIdx += 1
  356. # Remove empty islands
  357. i = len(islandList)
  358. while i:
  359. i -= 1
  360. if not islandList[i]:
  361. del islandList[i] # Can increment islands removed here.
  362. # Takes groups of faces. assumes face groups are UV groups.
  363. def getUvIslands(faceGroups, me):
  364. # Get seams so we don't cross over seams
  365. edge_seams = {} # should be a set
  366. for ed in me.edges:
  367. if ed.use_seam:
  368. edge_seams[ed.key] = None # dummy var- use sets!
  369. # Done finding seams
  370. islandList = []
  371. # XXX Window.DrawProgressBar(0.0, 'Splitting %d projection groups into UV islands:' % len(faceGroups))
  372. # print '\tSplitting %d projection groups into UV islands:' % len(faceGroups),
  373. # Find grouped faces
  374. faceGroupIdx = len(faceGroups)
  375. while faceGroupIdx:
  376. faceGroupIdx -= 1
  377. faces = faceGroups[faceGroupIdx]
  378. if not faces:
  379. continue
  380. # Build edge dict
  381. edge_users = {}
  382. for i, f in enumerate(faces):
  383. for ed_key in f.edge_keys:
  384. if ed_key in edge_seams: # DELIMIT SEAMS! ;)
  385. edge_users[ed_key] = [] # so as not to raise an error
  386. else:
  387. try:
  388. edge_users[ed_key].append(i)
  389. except:
  390. edge_users[ed_key] = [i]
  391. # Modes
  392. # 0 - face not yet touched.
  393. # 1 - added to island list, and need to search
  394. # 2 - touched and searched - don't touch again.
  395. face_modes = [0] * len(faces) # initialize zero - untested.
  396. face_modes[0] = 1 # start the search with face 1
  397. newIsland = []
  398. newIsland.append(faces[0])
  399. ok = True
  400. while ok:
  401. ok = True
  402. while ok:
  403. ok = False
  404. for i in range(len(faces)):
  405. if face_modes[i] == 1: # search
  406. for ed_key in faces[i].edge_keys:
  407. for ii in edge_users[ed_key]:
  408. if i != ii and face_modes[ii] == 0:
  409. face_modes[ii] = ok = 1 # mark as searched
  410. newIsland.append(faces[ii])
  411. # mark as searched, don't look again.
  412. face_modes[i] = 2
  413. islandList.append(newIsland)
  414. ok = False
  415. for i in range(len(faces)):
  416. if face_modes[i] == 0:
  417. newIsland = []
  418. newIsland.append(faces[i])
  419. face_modes[i] = ok = 1
  420. break
  421. # if not ok will stop looping
  422. # XXX Window.DrawProgressBar(0.1, 'Optimizing Rotation for %i UV Islands' % len(islandList))
  423. for island in islandList:
  424. optiRotateUvIsland(island)
  425. return islandList
  426. def packIslands(islandList):
  427. if USER_FILL_HOLES:
  428. # XXX Window.DrawProgressBar(0.1, 'Merging Islands (Ctrl: skip merge)...')
  429. mergeUvIslands(islandList) # Modify in place
  430. # Now we have UV islands, we need to pack them.
  431. # Make a synchronized list with the islands
  432. # so we can box pack the islands.
  433. packBoxes = []
  434. # Keep a list of X/Y offset so we can save time by writing the
  435. # uv's and packed data in one pass.
  436. islandOffsetList = []
  437. islandIdx = 0
  438. while islandIdx < len(islandList):
  439. minx, miny, maxx, maxy = boundsIsland(islandList[islandIdx])
  440. w, h = maxx - minx, maxy - miny
  441. if USER_ISLAND_MARGIN:
  442. minx -= USER_ISLAND_MARGIN * w / 2
  443. miny -= USER_ISLAND_MARGIN * h / 2
  444. maxx += USER_ISLAND_MARGIN * w / 2
  445. maxy += USER_ISLAND_MARGIN * h / 2
  446. # recalc width and height
  447. w, h = maxx - minx, maxy - miny
  448. if w < SMALL_NUM:
  449. w = SMALL_NUM
  450. if h < SMALL_NUM:
  451. h = SMALL_NUM
  452. """Save the offset to be applied later,
  453. we could apply to the UVs now and align them to the bottom left hand area
  454. of the UV coords like the box packer imagines they are
  455. but, its quicker just to remember their offset and
  456. apply the packing and offset in 1 pass """
  457. islandOffsetList.append((minx, miny))
  458. # Add to boxList. use the island idx for the BOX id.
  459. packBoxes.append([0, 0, w, h])
  460. islandIdx += 1
  461. # Now we have a list of boxes to pack that syncs
  462. # with the islands.
  463. # print '\tPacking UV Islands...'
  464. # XXX Window.DrawProgressBar(0.7, "Packing %i UV Islands..." % len(packBoxes) )
  465. # time1 = time.time()
  466. packWidth, packHeight = geometry.box_pack_2d(packBoxes)
  467. # print 'Box Packing Time:', time.time() - time1
  468. # if len(pa ckedLs) != len(islandList):
  469. # raise ValueError("Packed boxes differs from original length")
  470. # print '\tWriting Packed Data to faces'
  471. # XXX Window.DrawProgressBar(0.8, "Writing Packed Data to faces")
  472. # Sort by ID, so there in sync again
  473. islandIdx = len(islandList)
  474. # Having these here avoids divide by 0
  475. if islandIdx:
  476. if USER_STRETCH_ASPECT:
  477. # Maximize to uv area?? Will write a normalize function.
  478. xfactor = 1.0 / packWidth
  479. yfactor = 1.0 / packHeight
  480. else:
  481. # Keep proportions.
  482. xfactor = yfactor = 1.0 / max(packWidth, packHeight)
  483. while islandIdx:
  484. islandIdx -= 1
  485. # Write the packed values to the UV's
  486. xoffset = packBoxes[islandIdx][0] - islandOffsetList[islandIdx][0]
  487. yoffset = packBoxes[islandIdx][1] - islandOffsetList[islandIdx][1]
  488. for f in islandList[islandIdx]: # Offsetting the UV's so they fit in there packed box
  489. for uv in f.uv:
  490. uv.x = (uv.x + xoffset) * xfactor
  491. uv.y = (uv.y + yoffset) * yfactor
  492. def VectoQuat(vec):
  493. vec = vec.normalized()
  494. return vec.to_track_quat('Z', 'X' if abs(vec.x) > 0.5 else 'Y').inverted()
  495. class thickface:
  496. __slost__ = "v", "uv", "no", "area", "edge_keys"
  497. def __init__(self, face, uv_layer, mesh_verts):
  498. self.v = [mesh_verts[i] for i in face.vertices]
  499. self.uv = [uv_layer[i].uv for i in face.loop_indices]
  500. self.no = face.normal.copy()
  501. self.area = face.area
  502. self.edge_keys = face.edge_keys
  503. def main_consts():
  504. from math import radians
  505. global ROTMAT_2D_POS_90D
  506. global ROTMAT_2D_POS_45D
  507. global RotMatStepRotation
  508. ROTMAT_2D_POS_90D = Matrix.Rotation(radians(90.0), 2)
  509. ROTMAT_2D_POS_45D = Matrix.Rotation(radians(45.0), 2)
  510. RotMatStepRotation = []
  511. rot_angle = 22.5 # 45.0/2
  512. while rot_angle > 0.1:
  513. RotMatStepRotation.append([
  514. Matrix.Rotation(radians(+rot_angle), 2),
  515. Matrix.Rotation(radians(-rot_angle), 2),
  516. ])
  517. rot_angle = rot_angle / 2.0
  518. global ob
  519. ob = None
  520. def main(context,
  521. island_margin,
  522. projection_limit,
  523. user_area_weight,
  524. use_aspect,
  525. stretch_to_bounds,
  526. ):
  527. global USER_FILL_HOLES
  528. global USER_FILL_HOLES_QUALITY
  529. global USER_STRETCH_ASPECT
  530. global USER_ISLAND_MARGIN
  531. from math import cos
  532. import time
  533. global dict_matrix
  534. dict_matrix = {}
  535. # Constants:
  536. # Takes a list of faces that make up a UV island and rotate
  537. # until they optimally fit inside a square.
  538. global ROTMAT_2D_POS_90D
  539. global ROTMAT_2D_POS_45D
  540. global RotMatStepRotation
  541. main_consts()
  542. # Create the variables.
  543. USER_PROJECTION_LIMIT = projection_limit
  544. USER_ONLY_SELECTED_FACES = True
  545. USER_SHARE_SPACE = 1 # Only for hole filling.
  546. USER_STRETCH_ASPECT = stretch_to_bounds
  547. USER_ISLAND_MARGIN = island_margin # Only for hole filling.
  548. USER_FILL_HOLES = 0
  549. USER_FILL_HOLES_QUALITY = 50 # Only for hole filling.
  550. USER_VIEW_INIT = 0 # Only for hole filling.
  551. is_editmode = (context.mode == 'EDIT_MESH')
  552. if is_editmode:
  553. obList = context.objects_in_mode_unique_data
  554. else:
  555. obList = [
  556. ob for ob in context.selected_editable_objects
  557. if ob.type == 'MESH' and ob.data.library is None
  558. ]
  559. if not is_editmode:
  560. USER_ONLY_SELECTED_FACES = False
  561. if not obList:
  562. raise Exception("error, no selected mesh objects")
  563. # Convert from being button types
  564. USER_PROJECTION_LIMIT_CONVERTED = cos(USER_PROJECTION_LIMIT * DEG_TO_RAD)
  565. USER_PROJECTION_LIMIT_HALF_CONVERTED = cos((USER_PROJECTION_LIMIT / 2) * DEG_TO_RAD)
  566. # Toggle Edit mode
  567. if is_editmode:
  568. bpy.ops.object.mode_set(mode='OBJECT')
  569. # Assume face select mode! an annoying hack to toggle face select mode because Mesh doesn't like faceSelectMode.
  570. if USER_SHARE_SPACE:
  571. # Sort by data name so we get consistent results
  572. obList.sort(key=lambda ob: ob.data.name)
  573. collected_islandList = []
  574. time1 = time.time()
  575. # Tag as False so we don't operate on the same mesh twice.
  576. for me in bpy.data.meshes:
  577. me.tag = False
  578. for ob in obList:
  579. me = ob.data
  580. if me.tag or me.library:
  581. continue
  582. # Tag as used
  583. me.tag = True
  584. if not me.uv_layers: # Mesh has no UV Coords, don't bother.
  585. me.uv_layers.new()
  586. uv_layer = me.uv_layers.active.data
  587. me_verts = list(me.vertices)
  588. if USER_ONLY_SELECTED_FACES:
  589. meshFaces = [thickface(f, uv_layer, me_verts) for i, f in enumerate(me.polygons) if f.select]
  590. else:
  591. meshFaces = [thickface(f, uv_layer, me_verts) for i, f in enumerate(me.polygons)]
  592. # =======
  593. # Generate a projection list from face normals, this is meant to be smart :)
  594. # make a list of face props that are in sync with meshFaces
  595. # Make a Face List that is sorted by area.
  596. # meshFaces = []
  597. # meshFaces.sort( lambda a, b: cmp(b.area , a.area) ) # Biggest first.
  598. meshFaces.sort(key=lambda a: -a.area)
  599. # remove all zero area faces
  600. while meshFaces and meshFaces[-1].area <= SMALL_NUM:
  601. # Set their UV's to 0,0
  602. for uv in meshFaces[-1].uv:
  603. uv.zero()
  604. meshFaces.pop()
  605. if not meshFaces:
  606. continue
  607. # Smallest first is slightly more efficient,
  608. # but if the user cancels early then its better we work on the larger data.
  609. # Generate Projection Vecs
  610. # 0d is 1.0
  611. # 180 IS -0.59846
  612. # Initialize projectVecs
  613. if USER_VIEW_INIT:
  614. # Generate Projection
  615. # We add to this along the way
  616. projectVecs = [Vector(Window.GetViewVector()) @ ob.matrix_world.inverted().to_3x3()]
  617. else:
  618. projectVecs = []
  619. newProjectVec = meshFaces[0].no
  620. newProjectMeshFaces = [] # Popping stuffs it up.
  621. # Pretend that the most unique angle is ages away to start the loop off
  622. mostUniqueAngle = -1.0
  623. # This is popped
  624. tempMeshFaces = meshFaces[:]
  625. # This while only gathers projection vecs, faces are assigned later on.
  626. while 1:
  627. # If there's none there then start with the largest face
  628. # add all the faces that are close.
  629. for fIdx in range(len(tempMeshFaces) - 1, -1, -1):
  630. # Use half the angle limit so we don't overweight faces towards this
  631. # normal and hog all the faces.
  632. if newProjectVec.dot(tempMeshFaces[fIdx].no) > USER_PROJECTION_LIMIT_HALF_CONVERTED:
  633. newProjectMeshFaces.append(tempMeshFaces.pop(fIdx))
  634. # Add the average of all these faces normals as a projectionVec
  635. averageVec = Vector((0.0, 0.0, 0.0))
  636. if user_area_weight == 0.0:
  637. for fprop in newProjectMeshFaces:
  638. averageVec += fprop.no
  639. elif user_area_weight == 1.0:
  640. for fprop in newProjectMeshFaces:
  641. averageVec += fprop.no * fprop.area
  642. else:
  643. for fprop in newProjectMeshFaces:
  644. averageVec += fprop.no * ((fprop.area * user_area_weight) + (1.0 - user_area_weight))
  645. if averageVec.x != 0 or averageVec.y != 0 or averageVec.z != 0: # Avoid NAN
  646. projectVecs.append(averageVec.normalized())
  647. # Get the next vec!
  648. # Pick the face that's most different to all existing angles :)
  649. mostUniqueAngle = 1.0 # 1.0 is 0d. no difference.
  650. mostUniqueIndex = 0 # dummy
  651. for fIdx in range(len(tempMeshFaces) - 1, -1, -1):
  652. angleDifference = -1.0 # 180d difference.
  653. # Get the closest vec angle we are to.
  654. for p in projectVecs:
  655. temp_angle_diff = p.dot(tempMeshFaces[fIdx].no)
  656. if angleDifference < temp_angle_diff:
  657. angleDifference = temp_angle_diff
  658. if angleDifference < mostUniqueAngle:
  659. # We have a new most different angle
  660. mostUniqueIndex = fIdx
  661. mostUniqueAngle = angleDifference
  662. if mostUniqueAngle < USER_PROJECTION_LIMIT_CONVERTED:
  663. # print 'adding', mostUniqueAngle, USER_PROJECTION_LIMIT, len(newProjectMeshFaces)
  664. # Now weight the vector to all its faces, will give a more direct projection
  665. # if the face its self was not representative of the normal from surrounding faces.
  666. newProjectVec = tempMeshFaces[mostUniqueIndex].no
  667. newProjectMeshFaces = [tempMeshFaces.pop(mostUniqueIndex)]
  668. else:
  669. if len(projectVecs) >= 1: # Must have at least 2 projections
  670. break
  671. # If there are only zero area faces then its possible
  672. # there are no projectionVecs
  673. if not len(projectVecs):
  674. Draw.PupMenu('error, no projection vecs where generated, 0 area faces can cause this.')
  675. return
  676. faceProjectionGroupList = [[] for i in range(len(projectVecs))]
  677. # MAP and Arrange # We know there are 3 or 4 faces here
  678. for fIdx in range(len(meshFaces) - 1, -1, -1):
  679. fvec = meshFaces[fIdx].no
  680. i = len(projectVecs)
  681. # Initialize first
  682. bestAng = fvec.dot(projectVecs[0])
  683. bestAngIdx = 0
  684. # Cycle through the remaining, first already done
  685. while i - 1:
  686. i -= 1
  687. newAng = fvec.dot(projectVecs[i])
  688. if newAng > bestAng: # Reverse logic for dotvecs
  689. bestAng = newAng
  690. bestAngIdx = i
  691. # Store the area for later use.
  692. faceProjectionGroupList[bestAngIdx].append(meshFaces[fIdx])
  693. # Cull faceProjectionGroupList,
  694. # Now faceProjectionGroupList is full of faces that face match the project Vecs list
  695. for i in range(len(projectVecs)):
  696. # Account for projectVecs having no faces.
  697. if not faceProjectionGroupList[i]:
  698. continue
  699. # Make a projection matrix from a unit length vector.
  700. MatQuat = VectoQuat(projectVecs[i])
  701. # Get the faces UV's from the projected vertex.
  702. for f in faceProjectionGroupList[i]:
  703. f_uv = f.uv
  704. for j, v in enumerate(f.v):
  705. f_uv[j][:] = (MatQuat @ v.co).xy
  706. if USER_SHARE_SPACE:
  707. # Should we collect and pack later?
  708. islandList = getUvIslands(faceProjectionGroupList, me)
  709. collected_islandList.extend(islandList)
  710. else:
  711. # Should we pack the islands for this 1 object?
  712. islandList = getUvIslands(faceProjectionGroupList, me)
  713. packIslands(islandList)
  714. # update the mesh here if we need to.
  715. # We want to pack all in 1 go, so pack now
  716. if USER_SHARE_SPACE:
  717. packIslands(collected_islandList)
  718. print("Smart Projection time: %.2f" % (time.time() - time1))
  719. # aspect correction is only done in edit mode - and only smart unwrap supports currently
  720. if is_editmode:
  721. bpy.ops.object.mode_set(mode='EDIT')
  722. if use_aspect:
  723. import bmesh
  724. aspect = context.scene.uvedit_aspect(context.active_object)
  725. if aspect[0] > aspect[1]:
  726. aspect[0] = aspect[1] / aspect[0]
  727. aspect[1] = 1.0
  728. else:
  729. aspect[1] = aspect[0] / aspect[1]
  730. aspect[0] = 1.0
  731. bm = bmesh.from_edit_mesh(me)
  732. uv_act = bm.loops.layers.uv.active
  733. faces = [f for f in bm.faces if f.select]
  734. for f in faces:
  735. for l in f.loops:
  736. l[uv_act].uv[0] *= aspect[0]
  737. l[uv_act].uv[1] *= aspect[1]
  738. dict_matrix.clear()
  739. from bpy.props import FloatProperty, BoolProperty
  740. class SmartProject(Operator):
  741. """This script projection unwraps the selected faces of a mesh """ \
  742. """(it operates on all selected mesh objects, and can be used """ \
  743. """to unwrap selected faces, or all faces)"""
  744. bl_idname = "uv.smart_project"
  745. bl_label = "Smart UV Project"
  746. bl_options = {'REGISTER', 'UNDO'}
  747. angle_limit: FloatProperty(
  748. name="Angle Limit",
  749. description="Lower for more projection groups, higher for less distortion",
  750. min=1.0, max=89.0,
  751. default=66.0,
  752. )
  753. island_margin: FloatProperty(
  754. name="Island Margin",
  755. description="Margin to reduce bleed from adjacent islands",
  756. min=0.0, max=1.0,
  757. default=0.0,
  758. )
  759. user_area_weight: FloatProperty(
  760. name="Area Weight",
  761. description="Weight projections vector by faces with larger areas",
  762. min=0.0, max=1.0,
  763. default=0.0,
  764. )
  765. use_aspect: BoolProperty(
  766. name="Correct Aspect",
  767. description="Map UVs taking image aspect ratio into account",
  768. default=True,
  769. )
  770. stretch_to_bounds: BoolProperty(
  771. name="Stretch to UV Bounds",
  772. description="Stretch the final output to texture bounds",
  773. default=True,
  774. )
  775. @classmethod
  776. def poll(cls, context):
  777. return context.active_object is not None
  778. def execute(self, context):
  779. main(context,
  780. self.island_margin,
  781. self.angle_limit,
  782. self.user_area_weight,
  783. self.use_aspect,
  784. self.stretch_to_bounds,
  785. )
  786. return {'FINISHED'}
  787. def invoke(self, context, _event):
  788. wm = context.window_manager
  789. return wm.invoke_props_dialog(self)
  790. classes = (
  791. SmartProject,
  792. )