Datasets:
File size: 47,152 Bytes
8a28bb6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 | # pyright: reportAttributeAccessIssue=false
from collections import defaultdict
from numpy import ndarray
from PIL import Image
from typing import Optional, Tuple, Dict, List
import bpy # type: ignore
import logging
import numpy as np
import os
import trimesh
from .abstract import AbstractParser
from ..info.asset import Asset
from mathutils import Vector, Matrix # type: ignore
class BpyParser(AbstractParser):
@classmethod
def load(cls, filepath: str, **kwargs) -> Asset:
"""
Args:
use_material: if False, do not try loading (baked) textures and vertex_colors. Default True.
resolution: baked image resolution, default 512.
"""
clean_bpy()
load(filepath=filepath, **kwargs)
collection = bpy.data.collections.get("glTF_not_exported")
if collection is not None and collection.objects is not None:
for obj in list(collection.objects):
bpy.data.objects.remove(obj, do_unlink=True)
armature = get_armature()
if armature is None:
bones = None
joint_names = None
parents = None
lengths = None
matrix_world = np.eye(4)
matrix_local = None
matrix_basis = None
armature_name = None
else:
bones = armature.pose.bones # list of PoseBone
joint_names = [b.name for b in bones]
parents = []
lengths = []
matrix_world = np.array(armature.matrix_world)
matrix_local = []
for pbone in bones:
matrix_local.append(np.array(pbone.bone.matrix_local))
parents.append(joint_names.index(pbone.parent.name) if pbone.parent is not None else -1)
lengths.append(pbone.bone.length)
matrix_local = np.stack(matrix_local, axis=0)
parents = np.array(parents, dtype=np.int32)
lengths = np.array(lengths, dtype=np.float32)
matrix_basis = get_matrix_basis(armature, bones=bones)
armature_name = armature.name
mesh_dict = extract_mesh(
bones=bones,
use_material=kwargs.get('use_material', True),
resolution=kwargs.get('resolution', 512),
)
return Asset(
vertices=mesh_dict['vertices'],
faces=mesh_dict['faces'],
vertex_normals=mesh_dict['vertex_normals'],
face_normals=mesh_dict['face_normals'],
vertex_bias=mesh_dict['vertex_bias'],
face_bias=mesh_dict['face_bias'],
mesh_names=mesh_dict['mesh_names'],
joint_names=joint_names,
parents=parents,
lengths=lengths,
matrix_world=matrix_world,
matrix_local=matrix_local,
matrix_basis=matrix_basis,
armature_name=armature_name,
skin=mesh_dict['skin'],
uvs=mesh_dict['uvs'],
texture=mesh_dict['texture'],
texture_slot=mesh_dict['texture_slot'],
_vertex_colors=mesh_dict['_vertex_colors'],
have_texture=mesh_dict['have_texture'],
)
@classmethod
def export(cls, asset: Asset, filepath: str, **kwargs):
"""
If export obj, kwargs:
precision: int=6, number of decimal places for vertex coordinates
Otherwise, export fbx/glb/gltf using bpy, kwargs:
extrude_scale: float=0.5, if there is no tails in asset, first calculate the average length between parents and sons, then the length of leaf bone is l*extrude_scale. Otherwise do not affect final results.
connect_tail_to_unique_child: bool=False, if True, the tail of a bone with only one child will be exactly at the head of its child.
extrude_from_parent: bool=False, if True, the orientation of the leaf bone will be the same as its parent.
group_per_vertex: int=-1, number of the largest weights to keep for each vertex. -1 means keep all.
add_root: bool=False, if True, add a root bone at (0, 0, 0).
do_not_normalize: bool=False, if True, do not normalize the skinning weights.
collection_name: str='new_collection', name of the new collection to store objects.
add_leaf_bones: bool=False, if True, add a leaf bone at the end of each bone.
"""
ext = os.path.splitext(filepath)[1].lower()
if ext == '.obj':
cls.export_obj(asset, filepath, **kwargs)
elif ext == 'ply':
cls.export_ply(asset, filepath, **kwargs)
else:
cls.export_asset(asset, filepath, **kwargs)
@classmethod
def export_obj(
cls,
asset: Asset,
filepath: str,
precision: int=6,
use_pc: bool=False,
use_normal: bool=False,
use_skeleton: bool=False,
normal_size: float=0.01,
):
"""
Export the asset as an .obj file. This will ignore skeleton and skinning.
Args:
use_normal: export normals
use_skeleton: export skeleton
"""
asset._build_bias()
if asset.vertices is None or asset.vertex_bias is None:
raise ValueError("do not have vertices or vertex_bias")
if use_normal and asset.vertex_normals is None:
raise ValueError("use_normal is True but do not have vertex_normals")
if not filepath.lower().endswith('.obj'):
filepath += ".obj"
faces = asset.faces
mesh_names = asset.mesh_names
if mesh_names is None:
mesh_names = [f"mesh_{i}" for i in range(asset.P)]
cls._safe_make_dir(filepath)
file = open(filepath, 'w')
lines = []
tot = 0
if use_skeleton:
raise NotImplementedError()
for i, mesh_name in enumerate(mesh_names):
lines.append(f'o {mesh_name}\n')
if use_normal:
s = asset.get_vertex_slice(i)
for v, n in zip(asset.vertices[s], asset.vertex_normals[s]): # type: ignore
vv = v + n * normal_size
lines.append(f'v {v[0]:.{precision}f} {v[2]:.{precision}f} {-v[1]:.{precision}f}\n')
lines.append(f'v {vv[0]:.{precision}f} {vv[2]:.{precision}f} {-vv[1]:.{precision}f}\n')
lines.append(f'v {vv[0]:.{precision}f} {vv[2]:.{precision}f} {-vv[1]+0.000001:.{precision}f}\n')
lines.append(f"f {tot+1} {tot+2} {tot+3}\n")
tot += 3
else:
for v in asset.vertices[asset.get_vertex_slice(i)]:
lines.append(f'v {v[0]:.{precision}f} {v[2]:.{precision}f} {-v[1]:.{precision}f}\n')
if faces is not None and use_pc == False:
for f in faces[asset.get_face_slice(i)]:
lines.append(f"f {f[0]+1} {f[1]+1} {f[2]+1}\n")
file.writelines(lines)
file.close()
@classmethod
def export_ply(
cls,
asset: Asset,
filepath: str,
use_pc: bool=False,
render_skin_id: Optional[int]=None,
):
"""
Export the asset as an .ply file. This will ignore skeleton and skinning.
"""
import open3d as o3d
asset._build_bias()
if asset.vertices is None or asset.vertex_bias is None:
raise ValueError("do not have vertices or vertex_bias")
if not filepath.lower().endswith('.ply'):
filepath += ".ply"
faces = asset.faces
if use_pc:
faces = None
mesh_names = asset.mesh_names
if mesh_names is None:
mesh_names = [f"mesh_{i}" for i in range(asset.P)]
cls._safe_make_dir(filepath)
if render_skin_id is not None:
if asset.skin is None:
raise ValueError("render_skin_id is not None, but skin of asset is None")
t = asset.skin[:, render_skin_id]
colors = np.stack([
np.clip(1.5*t-0.5, 0, 1),
np.clip(1.5-np.abs(2*t-1), 0, 1),
np.clip(1-1.5*t, 0, 1),
], axis=1)
else:
colors = None
if faces is None:
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(asset.vertices)
if colors is not None:
pcd.colors = o3d.utility.Vector3dVector(colors)
o3d.io.write_point_cloud(filepath, pcd)
else:
mesh = o3d.geometry.TriangleMesh()
mesh.vertices = o3d.utility.Vector3dVector(asset.vertices)
mesh.triangles = o3d.utility.Vector3iVector(faces)
if colors is not None:
mesh.vertex_colors = o3d.utility.Vector3dVector(colors)
o3d.io.write_triangle_mesh(filepath, mesh)
@classmethod
def export_asset(cls, asset: Asset, filepath: str, do_not_export: bool=False, **kwargs):
clean_bpy()
images = kwargs.pop('images', None)
x_offset = kwargs.pop('x_offset', 0)
collection = make_asset(asset=asset, **kwargs)
if do_not_export == True:
return
if images is not None:
if isinstance(images, ndarray) and images.ndim==4:
images = [images[i] for i in range(images.shape[0])]
if not isinstance(images, list):
images = [images]
add_images_as_planes(
images=images,
collection=collection,
y=1,
z_offset=2,
plane_half_size=1,
x_offset=x_offset,
x_stride=2,
)
cls._safe_make_dir(filepath)
_, ext = os.path.splitext(filepath)
ext = ext.lower()[1:]
if ext == 'fbx':
if asset.joints is not None and asset.matrix_basis is not None:
logging.warning("Exporting animation, but fbx format is deprecated because the rest pose will not be exported in bpy4.2. Use glb/gltf format instead. See: https://blender.stackexchange.com/questions/273398/blender-export-fbx-lose-the-origin-rest-pose.")
export_dir = os.path.join("tmp_bpy", os.path.dirname(filepath))
os.makedirs(export_dir, exist_ok=True)
for img in bpy.data.images:
if img.source == 'GENERATED' or img.filepath == '':
img_path = os.path.join(export_dir, img.name + ".png")
img.filepath_raw = img_path
img.file_format = 'PNG'
img.save()
bpy.ops.export_scene.fbx(filepath=filepath, check_existing=False, add_leaf_bones=kwargs.get('add_leaf_bones', False), path_mode='COPY', embed_textures=True, mesh_smooth_type="FACE")
elif ext == 'glb' or ext == 'gltf':
bpy.ops.export_scene.gltf(filepath=filepath)
elif ext == 'blend':
import math
for w in bpy.context.window_manager.windows:
for a in w.screen.areas:
if a.type == 'VIEW_3D':
a.spaces.active.shading.type = 'MATERIAL'
for region in a.regions:
if region.type != 'WINDOW':
continue
rv3d = a.spaces.active.region_3d
rv3d.view_perspective = 'ORTHO'
from mathutils import Quaternion
rv3d.view_rotation = Quaternion(
(1, 0, 0), # axis
math.pi / 2
)
center=(0.0, 1.0, 0.0)
distance=10.0
rv3d.view_location = Vector(center)
rv3d.view_distance = distance
bpy.ops.wm.save_as_mainfile(filepath=filepath)
else:
raise ValueError(f"Unsupported format: {ext}")
@classmethod
def _safe_make_dir(cls, path: str):
if os.path.dirname(path) == '':
return
os.makedirs(os.path.dirname(path), exist_ok=True)
def clean_bpy():
"""Clean all the data in bpy."""
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True)
data_types = [
bpy.data.actions,
bpy.data.armatures,
bpy.data.cameras,
bpy.data.collections,
bpy.data.curves,
bpy.data.images,
bpy.data.lights,
bpy.data.materials,
bpy.data.meshes,
bpy.data.objects,
bpy.data.textures,
bpy.data.worlds,
bpy.data.node_groups,
]
for data_collection in data_types:
for item in data_collection:
data_collection.remove(item)
def load(filepath: str, **kwargs):
"""Load a 3D file into bpy."""
_, ext = os.path.splitext(filepath)
ext = ext.lower()[1:]
if not os.path.exists(filepath):
raise RuntimeError(f"file does not exist: {filepath}")
if ext == "obj":
bpy.ops.wm.obj_import(filepath=filepath)
elif ext == "fbx":
bpy.ops.import_scene.fbx(
filepath=filepath,
ignore_leaf_bones=kwargs.get('ignore_leaf_bones', False),
use_image_search=kwargs.get('use_image_search', False),
)
elif ext == "glb" or ext == "gltf":
bpy.ops.import_scene.gltf(filepath=filepath)
col_name = "glTF_not_exported"
if col_name in bpy.data.collections:
col = bpy.data.collections[col_name]
for obj in col.objects:
bpy.data.objects.remove(obj, do_unlink=True)
bpy.data.collections.remove(col)
elif ext == "dae":
bpy.ops.wm.collada_import(filepath=filepath)
elif ext == "blend":
with bpy.data.libraries.load(filepath) as (data_from, data_to):
data_to.objects = data_from.objects
for obj in data_to.objects:
if obj is not None:
bpy.context.collection.objects.link(obj)
elif ext == "bvh":
bpy.ops.import_anim.bvh(filepath=filepath)
else:
raise ValueError(f"unsupported type: {ext}")
def get_armature():
"""Get the armature object in the current scene."""
armatures = [obj for obj in bpy.context.scene.objects if obj.type == 'ARMATURE']
if len(armatures) == 0:
return None
return armatures[0]
def get_all_shader_nodes(meshes, resolution: int) -> Tuple[Dict, ndarray]:
name_to_image = {}
have_texture = []
order = []
for obj in meshes:
order.append(obj.name)
mesh = obj.data
# TODO: handle geometry node texture
if len(mesh.uv_layers) == 0:
have_texture.append(False)
continue
ok = False
for slot in obj.material_slots:
material = slot.material
if material.name in name_to_image:
ok = True
continue
if material is None or material.node_tree is None:
continue
node_tree = material.node_tree
nodes = node_tree.nodes
links = node_tree.links
for node in nodes:
# TODO: different shader nodes
# blender can only bake diffuse texture
if node.type == "BSDF_PRINCIPLED":
base_input = node.inputs["Base Color"]
if not base_input.is_linked:
continue
diffuse_node = nodes.new("ShaderNodeBsdfDiffuse")
diffuse_node.location = node.location
link = base_input.links[0]
links.new(link.from_socket, diffuse_node.inputs["Color"])
for out_link in node.outputs["BSDF"].links:
links.new(diffuse_node.outputs["BSDF"], out_link.to_socket)
nodes.remove(node)
image = bpy.data.images.new("tmp_bake", resolution, resolution)
tex_node = nodes.new("ShaderNodeTexImage")
tex_node.image = image
nodes.active = tex_node
name_to_image[material.name] = image
ok = True
have_texture.append(ok)
have_texture = np.array(have_texture, dtype=bool)
return name_to_image, have_texture
def get_vertex_colors(mesh) -> ndarray|None:
N = len(mesh.vertices)
v_vertex_group = None
if len(mesh.color_attributes) > 0:
vcol = mesh.color_attributes[0]
v_vertex_group = np.ones((N, 3), dtype=np.float32)
for loop_idx, loop in enumerate(mesh.loops):
r, g, b, a = vcol.data[loop_idx].color
v_vertex_group[loop.vertex_index] = [r, g, b]
return v_vertex_group
else:
return None
def get_all_texture_correspondence(meshes, name_to_image: Dict) -> Tuple[Dict[str, ndarray], Dict[str, ndarray]]:
name_to_id = {s: [] for s in name_to_image}
name_to_uv = {s: [] for s in name_to_image}
tri_index = 0
tot = 0
for obj in meshes:
mesh = obj.data
if len(mesh.uv_layers) == 0:
continue
uv_layer = mesh.uv_layers.active.data
for poly in mesh.polygons:
if len(obj.material_slots)==0:
continue
mat = obj.material_slots[poly.material_index].material
if mat.name not in name_to_image:
continue
start = poly.loop_start
total = poly.loop_total
v0 = start
for v1 in range(start+1, start+total-1):
v2 = v1 + 1
def f(i):
nonlocal tri_index, tot
uv = uv_layer[i].uv
name_to_id[mat.name].append(tot)
name_to_uv[mat.name].append([uv.x%1.0, uv.y%1.0])
tri_index += 1
tot += 1
f(v0)
f(v1)
f(v2)
name_to_id = {s: np.array(name_to_id[s], dtype=np.int32) for s in name_to_id}
name_to_uv = {s: np.stack(name_to_uv[s], dtype=np.float32) if len(name_to_uv[s]) > 0 else np.zeros((0, 2), dtype=np.float32) for s in name_to_uv}
return name_to_id, name_to_uv
def extract_mesh(bones=None, use_material: bool=True, resolution: int=512):
"""
Extract vertices, face_normals, faces and skinning(if possible).
"""
meshes = []
for v in bpy.data.objects:
if v.type == 'MESH':
# skip bad meshes
if np.abs(np.linalg.det(np.array(v.matrix_world)))**0.333333333333 < 1e-6:
continue
if v.parent is not None:
if np.abs(np.linalg.det(np.array(v.parent.matrix_world)))**0.333333333333 < 1e-6:
continue
meshes.append(v)
index = {}
if bones is not None:
for (id, pbone) in enumerate(bones):
index[pbone.name] = id
total_bones = len(bones)
else:
total_bones = None
mesh_names_list = []
vertices_list = []
faces_list = []
skin_list = []
vertex_bias = []
face_bias = []
cur_vertex_bias = 0
cur_face_bias = 0
for obj in meshes:
# directly apply mesh's transformation because armature operates on the transformed mesh
if obj.parent is not None:
m = np.linalg.inv(np.array(obj.parent.matrix_world)) @ np.array(obj.matrix_world)
else:
m = np.eye(4)
matrix_world_rot = m[:3, :3]
matrix_world_bias = m[:3, 3]
rot = matrix_world_rot
total_vertices = len(obj.data.vertices)
vertices = np.zeros((3, total_vertices))
if total_bones is not None:
skin_weight = np.zeros((total_vertices, total_bones))
else:
skin_weight = np.zeros((1, 1))
obj_verts = obj.data.vertices
obj_group_names = [g.name for g in obj.vertex_groups]
# get faces and normals
faces = []
normals = []
loops = obj.data.loops
polygons = obj.data.polygons
for poly in polygons:
start = poly.loop_start
total = poly.loop_total
verts = [loops[i].vertex_index for i in range(start, start + total)]
v0 = verts[0]
n = rot @ poly.normal
for v1, v2 in zip(verts[1:], verts[2:]):
faces.append((v0, v1, v2))
normals.append(n)
faces = np.asarray(faces, dtype=np.int32).reshape(-1, 3)
normals = np.asarray(normals, dtype=np.float32).reshape(-1, 3)
vg_lut = {}
for v in obj_verts:
for g in v.groups:
vg_lut[(v.index, g.group)] = g.weight
coords = np.array([v.co for v in obj_verts]).reshape(-1, 3)
rot_np = np.array(rot)
coords = (rot_np @ coords.T).T + matrix_world_bias
vertices[0:3, :coords.shape[0]] = coords.T
# extract skin
if bones is not None:
for bone in bones:
if bone.name not in obj_group_names:
continue
gidx = obj.vertex_groups[bone.name].index
col = index[bone.name]
for v in obj_verts:
w = vg_lut.get((v.index, gidx))
if w is not None:
skin_weight[v.index, col] = w
vertices = vertices.T
mesh_names_list.append(obj.name)
vertices_list.append(vertices)
faces_list.append(faces+cur_vertex_bias) # add bias to faces
if total_bones is not None:
skin_list.append(skin_weight)
cur_vertex_bias += len(vertices)
cur_face_bias += len(faces)
vertex_bias.append(cur_vertex_bias)
face_bias.append(cur_face_bias)
vertices = np.vstack(vertices_list) if len(vertices_list) > 0 else np.zeros((0, 3), dtype=np.float32)
faces = np.vstack(faces_list) if len(faces_list) > 0 else np.zeros((0, 3), dtype=np.int32)
mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False, maintain_order=True)
vertex_normals = mesh.vertex_normals
face_normals = mesh.face_normals
uvs = None
texture = None
texture_slot = None
_vertex_colors = None
have_texture = None
if use_material and len(meshes) > 0:
name_to_image, have_texture = get_all_shader_nodes(meshes, resolution=resolution)
else:
name_to_image = {}
have_texture = {}
if len(name_to_image) > 0:
name_to_id, name_to_uv = get_all_texture_correspondence(meshes, name_to_image)
bpy.ops.object.select_all(action='DESELECT')
for obj in meshes:
obj.select_set(True)
bpy.context.view_layer.objects.active = meshes[0]
if bpy.context.mode != 'OBJECT':
bpy.ops.object.mode_set(mode='OBJECT')
############################ baked image will be black if uv is out of [0, 1]^2
for obj in meshes:
mesh = obj.data
if len(mesh.uv_layers) == 0:
continue
uv_layer = mesh.uv_layers.active.data
for loop_uv in uv_layer:
u, v = loop_uv.uv
loop_uv.uv = (u % 1.0, v % 1.0)
############################
for i in range(len(have_texture)):
if not have_texture[i]:
v = get_vertex_colors(meshes[i].data)
if _vertex_colors is None:
_vertex_colors = np.ones((vertices.shape[0], 3), dtype=np.float32)
if i == 0:
_vertex_colors[:vertex_bias[0]] = v
else:
_vertex_colors[vertex_bias[i-1]:vertex_bias[i]] = v
_vertex_colors = np.nan_to_num(_vertex_colors) if _vertex_colors is not None else None
# bake
bpy.context.scene.render.engine = 'CYCLES'
bpy.context.scene.cycles.bake_type = 'DIFFUSE'
bpy.context.scene.render.bake.use_pass_direct = False
bpy.context.scene.render.bake.use_pass_indirect = False
bpy.context.scene.render.bake.use_pass_color = True
# bpy.ops.object.bake(type='DIFFUSE')
valid_objects = [
obj for obj in bpy.context.selected_objects
if obj.type == 'MESH' and obj.data.uv_layers
]
bpy.ops.object.select_all(action='DESELECT')
for obj in valid_objects:
obj.select_set(True)
if valid_objects:
bpy.context.view_layer.objects.active = valid_objects[0]
try:
bpy.ops.object.bake(type='DIFFUSE')
except:
logging.warning("Baking failed!!!")
bpy.ops.object.select_all(action='DESELECT')
# ######################
# debug: export baked images to ./tmp_delete/1.png, 2.png, ...
# dbg_dir = os.path.join(os.getcwd(), "tmp_delete")
# os.makedirs(dbg_dir, exist_ok=True)
# for idx, img in enumerate(name_to_image.values(), start=1):
# img.filepath_raw = os.path.join(dbg_dir, f"{idx}.png")
# img.file_format = 'PNG'
# img.save()
# ######################
bpy.ops.object.select_all(action='DESELECT')
# concat textures
images = []
where = {}
for name, img in name_to_image.items():
where[name] = len(images)
images.append(img)
num_images = len(images)
texture = np.ones((resolution, resolution*num_images, 3), dtype=np.float32) # white texture
texture_slot = np.zeros(len(faces)*3, dtype=np.int32)
uvs = np.zeros((len(faces)*3, 2), dtype=np.float32)
for i, img in enumerate(images):
pixels = np.array(img.pixels[:], dtype=np.float32)
pixels = pixels.reshape(resolution, resolution, 4)[..., :3]
texture[:, i*resolution:(i+1)*resolution, :] = pixels
for name in name_to_id:
id = name_to_id[name]
uv = name_to_uv[name]
pos = where[name]
uv[:, 0] = uv[:, 0] / num_images + pos / num_images
uvs[id] = uv
texture_slot[id] = pos
uvs = uvs % 1.0
return {
'mesh_names': np.array(mesh_names_list),
'vertices': vertices,
'faces': faces,
'face_normals': face_normals,
'vertex_normals': vertex_normals,
'skin': np.vstack(skin_list) if len(skin_list) > 0 else None,
'vertex_bias': np.array(vertex_bias),
'face_bias': np.array(face_bias),
'uvs': uvs,
'texture': texture,
'texture_slot': texture_slot,
'_vertex_colors': _vertex_colors,
'have_texture': have_texture,
}
def get_matrix_basis(armature, bones=None):
if bones is None or len(bones) == 0:
return None
actions = bpy.data.actions
if actions is None or len(actions) == 0:
return None
J = len(bones)
all_frames = []
if not hasattr(armature, 'animation_data') or armature.animation_data is None:
return None
orig_action = armature.animation_data.action
for action in actions:
armature.animation_data.action = action
start = int(action.frame_range[0])
end = int(action.frame_range[1])
for frame in range(start, end + 1):
bpy.context.scene.frame_set(frame)
mat = np.zeros((J, 4, 4), dtype=np.float32)
for j, pbone in enumerate(bones):
mat[j] = np.array(pbone.matrix_basis) # remember to normalize rot (in case matrix_local != identity)
all_frames.append(mat)
armature.animation_data.action = orig_action
m = np.stack(all_frames, axis=0)
mask = np.linalg.det(m[..., :3, :3]) > 1e-6
m[~mask] = np.eye(4)
m[..., :3, :3] = m[..., :3, :3] / np.linalg.norm(m[..., :3, :3], axis=-2, keepdims=True)
return m
###################################
# DIRTY DEBUG CODE BEGIN
###################################
def _to_rgb_uint8(img):
"""PIL.Image or np.ndarray -> (H, W, 3) uint8"""
if isinstance(img, Image.Image):
img = np.array(img)
if img.ndim == 2:
img = np.repeat(img[..., None], 3, axis=-1)
elif img.ndim == 3:
if img.shape[2] == 1:
img = np.repeat(img, 3, axis=-1)
elif img.shape[2] == 4:
img = img[..., :3]
assert img.ndim == 3 and img.shape[2] == 3
return img.astype(np.uint8)
def _create_plane_mesh(name: str, x: float, y: float, z: float, x_offset: float, z_offset: float, collection):
"""(-x+offset, y, -z+offset) to (x+offset, y, z+offset)"""
mesh = bpy.data.meshes.new(name)
verts = [
(-x+x_offset, y, z+z_offset),
( x+x_offset, y, z+z_offset),
( x+x_offset, y, -z+z_offset),
(-x+x_offset, y, -z+z_offset),
]
mesh.from_pydata(verts, [], [(0, 1, 2, 3)])
mesh.update()
mesh.uv_layers.new(name="UVMap")
uv_data = mesh.uv_layers.active.data
uv_data[0].uv = (0.0, 0.0)
uv_data[1].uv = (1.0, 0.0)
uv_data[2].uv = (1.0, 1.0)
uv_data[3].uv = (0.0, 1.0)
obj = bpy.data.objects.new(name, mesh)
collection.objects.link(obj)
return obj
def _create_material_from_np(name, img_np):
h, w, _ = img_np.shape
rgba = np.ones((h, w, 4), dtype=np.uint8) * 255
rgba[..., :3] = img_np
img = bpy.data.images.new(
name=name,
width=w,
height=h,
alpha=False,
float_buffer=False,
)
img.pixels = (rgba.reshape(-1) / 255.0).tolist()
mat = bpy.data.materials.new(name + "_mat")
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
nodes.clear()
tex = nodes.new("ShaderNodeTexImage")
tex.image = img
bsdf = nodes.new("ShaderNodeBsdfPrincipled")
out = nodes.new("ShaderNodeOutputMaterial")
links.new(tex.outputs["Color"], bsdf.inputs["Base Color"])
links.new(bsdf.outputs["BSDF"], out.inputs["Surface"])
img.pack()
return mat
def add_images_as_planes(
images,
collection,
y: float=1.0,
x_offset: float=0.0,
z_offset: float=2.0,
plane_half_size: float=1.0,
x_stride: float=2.0,
):
for i, img in enumerate(images):
rgb = _to_rgb_uint8(img)
obj = _create_plane_mesh(
name=f"ImagePlane_{i}",
x=plane_half_size,
y=y,
z=plane_half_size,
x_offset=i*x_stride+x_offset,
z_offset=z_offset,
collection=collection,
)
mat = _create_material_from_np(f"Image_{i}", rgb)
obj.data.materials.append(mat)
###################################
# DIRTY DEBUG CODE END
###################################
def set_vertex_colors(mesh, vertex_colors, layer_name: str="vertex_colors", mat_name: str="mat_vertex_colors"):
mesh.materials.clear()
vcol = mesh.color_attributes.new(name=layer_name, type="BYTE_COLOR", domain="POINT")
if vcol is not None:
assert len(mesh.vertices) == len(vertex_colors), "length of vertex_colors does not match mesh.vertices"
for j in range(len(vertex_colors)):
r, g, b = vertex_colors[j]
vcol.data[j].color = (r, g, b, 1.0)
mat = bpy.data.materials.new(mat_name)
mat.use_nodes = True
nt = mat.node_tree
nodes = nt.nodes
links = nt.links
nodes.clear()
attr_node = nodes.new("ShaderNodeAttribute")
attr_node.attribute_name = layer_name
attr_node.location = (-600, 0)
bsdf = nodes.new("ShaderNodeBsdfPrincipled")
bsdf.location = (-300, 0)
output = nodes.new("ShaderNodeOutputMaterial")
output.location = (0, 0)
links.new(attr_node.outputs["Color"], bsdf.inputs["Base Color"])
links.new(bsdf.outputs["BSDF"], output.inputs["Surface"])
mesh.materials.append(mat)
mesh.update()
# one mesh, one uv, multiple textures
def set_texture(meshes, uvs: ndarray, texture: ndarray, slots: ndarray, have_texture: ndarray, uv_name: str="uv", mat_name: str="mat"):
assert uvs.shape[0] == slots.shape[0]
h, w_full, _ = texture.shape
num_images = w_full // h
if num_images == 0:
return
w = w_full // num_images
images = []
materials = []
for i in range(num_images):
image = bpy.data.images.new(
name=f"{mat_name}_{i}",
width=w,
height=h,
)
rgba = np.ones((h, w, 4), dtype=np.float32)
rgba[:, :, :3] = texture[:, i*w:(i+1)*w, :]
image.pixels = rgba.flatten()
images.append(image)
mat = bpy.data.materials.new(f"{mat_name}_{i}")
mat.use_nodes = True
nt = mat.node_tree
nodes = nt.nodes
links = nt.links
nodes.clear()
tex_node = nodes.new("ShaderNodeTexImage")
tex_node.image = image
tex_node.location = (-600, 0)
bsdf = nodes.new("ShaderNodeBsdfPrincipled")
bsdf.location = (-300, 0)
output = nodes.new("ShaderNodeOutputMaterial")
output.location = (0, 0)
links.new(tex_node.outputs["Color"], bsdf.inputs["Base Color"])
links.new(bsdf.outputs["BSDF"], output.inputs["Surface"])
materials.append(mat)
tri_index = 0
for i, mesh in enumerate(meshes):
if not have_texture[i]:
# TODO: faster?
for poly in mesh.polygons:
start = poly.loop_start
total = poly.loop_total
tri_index += (total-2) * 3
continue
mesh.materials.clear()
for mat in materials:
mesh.materials.append(mat)
while len(mesh.uv_layers) > 0:
mesh.uv_layers.remove(mesh.uv_layers[0])
uv_layer = mesh.uv_layers.new(name=uv_name)
mesh.uv_layers.active = uv_layer
uv_data = uv_layer.data
for poly in mesh.polygons:
start = poly.loop_start
total = poly.loop_total
loops = list(range(start, start + total))
v0 = loops[0]
first_slot = slots[tri_index]
if first_slot >= num_images:
first_slot = 0
poly.material_index = first_slot
for i in range(1, total - 1):
v1 = loops[i]
v2 = loops[i + 1]
for loop_id in (v0, v1, v2):
u, v = uvs[tri_index]
u = u * num_images - poly.material_index
uv_data[loop_id].uv = (u, v)
tri_index += 1
mesh.update()
def make_asset(
asset: Asset,
extrude_scale: float=0.5,
connect_tail_to_unique_child: bool=False,
extrude_from_parent: bool=False,
use_simple_tails: bool=False,
group_per_vertex: int=-1,
add_root: bool=False,
do_not_normalize: bool=False,
collection_name: str='new_collection',
use_vertices: bool=True,
use_faces: bool=True,
use_animation: bool=True,
use_material: bool=True,
):
"""
Args:
extrude_scale: float=0.5, if there is no tails in asset, first calculate the average length between parents and sons, then the length of leaf bone is l*extrude_scale. Otherwise do not affect final results.
connect_tail_to_unique_child: bool=False, if True, the tail of a bone with only one child will be exactly at the head of its child.
extrude_from_parent: bool=False, if True, the orientation of the leaf bone will be the same as its parent.
use_simple_tails: if True, add tails along the axis.
group_per_vertex: int=-1, number of the largest weights to keep for each vertex. -1 means keep all.
add_root: bool=False, if True, add a root bone at (0, 0, 0).
do_not_normalize: bool=False, if True, do not normalize the skinning weights.
collection_name: str='new_collection', name of the new collection to store objects.
use_vertices: bool=True, if False, do not export vertices.
use_faces: bool=True, if False, do not export faces.
use_animation: bool=True, if False, do not export animation.
use_material: bool=True, if False, do not export material.
"""
def to_matrix(x: ndarray):
return Matrix((x[0, :], x[1, :], x[2, :], x[3, :]))
collection = bpy.data.collections.new(collection_name)
bpy.context.scene.collection.children.link(collection)
# 1. if there are meshes, make meshes
objects = []
if use_vertices and asset.vertices is not None:
if asset.mesh_names is not None:
mesh_names = asset.mesh_names
else:
mesh_names = [f"mesh_{i}" for i in range(asset.P)]
meshes = []
for i in range(asset.P):
mesh = bpy.data.meshes.new(mesh_names[i])
meshes.append(mesh)
v = asset.vertices[asset.get_vertex_slice(i)]
if not use_faces or (asset.faces is None or asset.face_bias is None or asset.vertex_bias is None):
mesh.from_pydata(v, [], [])
else:
if i == 0:
mesh.from_pydata(v, [], asset.faces[asset.get_face_slice(i)])
else:
mesh.from_pydata(v, [], asset.faces[asset.get_face_slice(i)]-asset.vertex_bias[i-1])
if use_material and asset._vertex_colors is not None:
if asset.have_texture is None or not asset.have_texture[i]:
set_vertex_colors(mesh, asset._vertex_colors[asset.get_vertex_slice(i)], layer_name=f"vcol_{i}", mat_name=f"mat_vcol_{i}")
mesh.update()
# make object from mesh
object = bpy.data.objects.new(mesh_names[i], mesh)
objects.append(object)
# add object to scene collection
collection.objects.link(object)
if use_material and asset.uvs is not None and asset.texture is not None and asset.texture_slot is not None and asset.have_texture is not None:
set_texture(meshes, asset.uvs, asset.texture, asset.texture_slot, asset.have_texture)
# 2. if there is armature, process tails and make armature
armature = None
armature_name = 'Armature'
joint_names = asset.joint_names if asset.joint_names is not None else [f"bone_{i}" for i in range(asset.J)]
if asset.joints is not None and asset.parents is not None:
joints = asset.joints
length_sum = 0.
sons = defaultdict(list)
for i in range(len(asset.parents)):
p = asset.parents[i]
if p == -1:
continue
sons[p].append(i)
length_sum += np.linalg.norm(joints[i] - joints[p])
if asset.J <= 1:
length = 1.0
else:
length_avg = length_sum / max(len(asset.parents) - 1, 1)
length = length_avg * extrude_scale
tails = asset.tails
if use_simple_tails and tails is None:
asset.lengths = np.ones((asset.J)) * length
tails = asset.tails
connect_tail_to_unique_child = False
extrude_from_parent = False
if tails is None:
tails = joints.copy()
connect_tail_to_unique_child = True
extrude_from_parent = True
root_tail = False
root_id = asset.root
for i in range(len(asset.parents)):
p = asset.parents[i]
if p == -1:
continue
d = np.linalg.norm(joints[i] - joints[p])
if d <= length * 1e-2:
max_d = max(length, 1e-5)
joints[i] += np.random.randn(3) * max_d * 1e-2
if connect_tail_to_unique_child:
for i in range(len(asset.parents)):
if len(sons[i]) == 1:
child = sons[i][0]
tails[i] = joints[child]
if root_id == i:
root_tail = True
if extrude_from_parent:
for i in range(len(asset.parents)):
if len(sons[i]) != 1 and asset.parents[i] != -1:
p = asset.parents[i]
d = joints[i] - joints[p]
if np.linalg.norm(d) < 1e-6:
d = np.array([0., 0., 1.]) # in case son.head == parent.head
else:
d = d / np.linalg.norm(d)
tails[i] = joints[i] + d * length
if root_tail is False:
tails[root_id] = joints[root_id] + np.array([0., 0., length])
bpy.ops.object.armature_add(enter_editmode=True)
armature = bpy.data.armatures.get('Armature')
armature_name = asset.armature_name if asset.armature_name is not None else 'Armature'
armature.name = armature_name
bpy.data.objects['Armature'].name = armature_name
edit_bones = armature.edit_bones
if add_root:
bone_root = edit_bones.get('Bone')
root_name = 'Root'
x = 0
while root_name in joint_names:
root_name = f'Root_{x}'
x += 1
bone_root.name = root_name
bone_root.tail = Vector((joints[0, 0], joints[0, 1], joints[0, 2]))
else:
bone_root = edit_bones.get('Bone')
bone_root.name = joint_names[0]
bone_root.head = Vector((joints[0, 0], joints[0, 1], joints[0, 2]))
bone_root.tail = Vector((tails[0, 0], tails[0, 1], tails[0, 2]))
def extrude_bone(
edit_bones,
name: str,
parent_name: str,
head: Tuple[float, float, float],
tail: Tuple[float, float, float],
):
bone = edit_bones.new(name)
bone.head = Vector((head[0], head[1], head[2]))
bone.tail = Vector((tail[0], tail[1], tail[2]))
bone.name = name
parent_bone = edit_bones.get(parent_name)
bone.parent = parent_bone
bone.use_connect = False
assert not np.isnan(head).any(), f"nan found in head of bone {name}"
assert not np.isnan(tail).any(), f"nan found in tail of bone {name}"
for u in asset.dfs_order:
if add_root is False and u==0:
continue
pname = joint_names[u] if asset.parents[u] == -1 else joint_names[asset.parents[u]]
extrude_bone(edit_bones, joint_names[u], pname, joints[u], tails[u])
bpy.ops.object.mode_set(mode='OBJECT')
# 3. if there is skin, set vertex groups
if asset.skin is not None and armature is not None and len(objects) > 0:
if bpy.context.mode != 'OBJECT':
bpy.ops.object.mode_set(mode='OBJECT')
armature_obj = bpy.data.objects.get(armature_name)
if not armature_obj:
raise ValueError(f"Armature {armature_name} not found")
all_objects = bpy.data.objects
for i in range(len(objects)):
skin_slice = asset.skin[asset.get_vertex_slice(i)]
ob_name = mesh_names[i]
ob = all_objects.get(ob_name)
if ob is None:
continue
ob.select_set(True)
armature_obj.select_set(True)
bpy.ops.object.parent_set(type='ARMATURE_NAME')
argsorted = np.argsort(-skin_slice, axis=1)
current_group_per_vertex = min(group_per_vertex, skin_slice.shape[1])
if group_per_vertex == -1:
current_group_per_vertex = skin_slice.shape[-1]
top_indices = argsorted[:, :current_group_per_vertex]
row_indices = np.arange(skin_slice.shape[0])[:, None]
top_weights = skin_slice[row_indices, top_indices]
if not do_not_normalize:
weight_sums = top_weights.sum(axis=1, keepdims=True)
weight_sums[weight_sums == 0] = 1.0
top_weights /= weight_sums
vg_lookup = []
for j_name in joint_names:
vg = ob.vertex_groups.get(j_name)
if not vg:
vg = ob.vertex_groups.new(name=j_name)
vg_lookup.append(vg)
for v in range(len(skin_slice)):
for k in range(current_group_per_vertex):
joint_idx = top_indices[v, k]
weight_val = top_weights[v, k]
vg_lookup[joint_idx].add([v], weight_val, 'REPLACE')
if armature_name in bpy.data.objects:
armature = bpy.data.objects[armature_name]
armature.select_set(True)
if asset.matrix_world is not None:
matrix_world = to_matrix(asset.matrix_world)
else:
matrix_world = to_matrix(np.eye(4))
armature.matrix_world = matrix_world
# 4. if there is animation, set keyframes
if use_animation and asset.matrix_basis is not None and asset.matrix_local is not None and armature is not None:
matrix_basis = asset.matrix_basis
matrix_local = asset.matrix_local
objects = bpy.data.objects
for o in bpy.context.selected_objects:
o.select_set(False)
frames = matrix_basis.shape[0]
# change matrix_local
bpy.context.view_layer.objects.active = armature
bpy.ops.object.mode_set(mode='EDIT')
for (id, name) in enumerate(joint_names):
# matrix_local of pose bone
bpy.context.active_object.data.edit_bones.get(name).matrix = to_matrix(matrix_local[id])
bpy.ops.object.mode_set(mode='OBJECT')
for (id, name) in enumerate(joint_names):
pbone = armature.pose.bones.get(name)
for frame in range(frames):
bpy.context.scene.frame_set(frame + 1)
q = to_matrix(matrix_basis[frame, id])
if pbone.rotation_mode == "QUATERNION":
pbone.rotation_quaternion = q.to_quaternion()
pbone.keyframe_insert(data_path = 'rotation_quaternion')
else:
pbone.rotation_euler = q.to_euler()
pbone.keyframe_insert(data_path = 'rotation_euler')
pbone.location = q.to_translation()
pbone.keyframe_insert(data_path = 'location')
bpy.ops.object.mode_set(mode='OBJECT')
return collection
|