Advertisement
Guest User

Untitled

a guest
Sep 4th, 2015
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. import bpy
  2. import bmesh
  3. from mathutils.geometry import barycentric_transform, intersect_point_tri_2d
  4.  
  5. # this will use the 2D cursor of the first UV editor found
  6. for area in bpy.context.screen.areas:
  7. if area.type == 'IMAGE_EDITOR':
  8. space_data = area.spaces.active
  9. loc = space_data.cursor_location
  10. norm_coords = space_data.uv_editor.show_normalized_coords
  11. break
  12. else:
  13. raise Exception("No UV editor found")
  14.  
  15. # mesh UVs are always normalized, but not the 2D cursor!
  16. def uv_normalize(tex, uv):
  17. if tex.image is None:
  18. x, y = 256, 256
  19. else:
  20. x, y = tex.image.size
  21. return (uv[0] / x, uv[1] / y, 0) # to_3d()
  22.  
  23. ob = bpy.context.object
  24. assert ob.type == "MESH", "Selected object not a mesh"
  25. me = ob.data
  26. bm = bmesh.new()
  27. bm.from_mesh(me)
  28.  
  29.  
  30. # tag selected faces, because triangulate may clear selection state
  31. for f in bm.faces:
  32. if f.select:
  33. f.tag = True
  34.  
  35.  
  36. # viewport seems to use fixed / clipping instead of beauty
  37. bmesh.ops.triangulate(bm, faces=bm.faces, quad_method=1, ngon_method=1)
  38.  
  39.  
  40. # re-select faces
  41. for f in bm.faces:
  42. if f.tag:
  43. f.select_set(True)
  44.  
  45.  
  46. uv_layer = bm.loops.layers.uv.active
  47. tex = bm.faces.layers.tex.active
  48.  
  49.  
  50. def find_coord(loc, face, uvs):
  51. uv1, uv2, uv3 = uvs
  52. x, y, z = [v.co for v in face.verts]
  53. co = barycentric_transform(loc, uv1, uv2, uv3, x, y, z)
  54. bpy.context.scene.cursor_location = ob.matrix_world * co
  55.  
  56.  
  57. random_face = None
  58. sel_faces = [f for f in bm.faces if f.select]
  59. for face in sel_faces:
  60. uv1, uv2, uv3 = [l[uv_layer].uv.to_3d() for l in face.loops]
  61. if norm_coords:
  62. loc_normalized = loc.to_3d()
  63. else:
  64. loc_normalized = uv_normalize(face[tex], loc)
  65.  
  66. # remember the first face for possible fallback
  67. if random_face is None:
  68. random_face = loc_normalized, face, (uv1, uv2, uv3)
  69.  
  70. #print("trying", loc_normalized, "vs", uv1, uv2, uv3)
  71. if intersect_point_tri_2d(loc_normalized, uv1, uv2, uv3):
  72. print("found intersecting triangle")
  73. find_coord(loc_normalized, face, (uv1, uv2, uv3))
  74. break
  75. else:
  76. print("trying random selected face for extrapolation")
  77. find_coord(*random_face)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement