__init__.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  1. # ----------------------------------------------------------
  2. # File __init__.py
  3. # ----------------------------------------------------------
  4. # Imports
  5. # Check if this add-on is being reloaded
  6. if "bpy" in locals():
  7. # reloading .py files
  8. import bpy
  9. import importlib
  10. # from . import zs_renderscene as zsrs
  11. # importlib.reload(zsrs)
  12. # or if this is the first load of this add-on
  13. else:
  14. import bpy
  15. import json
  16. from pathlib import Path
  17. from dataclasses import dataclass
  18. from mathutils import Euler, Vector, Quaternion, Matrix
  19. import math
  20. import os
  21. import base64
  22. import numpy as np
  23. import shutil
  24. # from . import zs_renderscene as zsrs # noqa
  25. # Addon info
  26. bl_info = {
  27. "name": "ZS Stable Diffusion Connection V0.0.1",
  28. "author": "Sergiu <sergiu@zixelise.com>",
  29. "Version": (0, 0, 1),
  30. "blender": (4, 00, 0),
  31. "category": "Scene",
  32. "description": "Stable Diffusion Connection",
  33. }
  34. # -------------------------------------------------------------------
  35. # Functions
  36. # -------------------------------------------------------------------
  37. @dataclass
  38. class AssetData:
  39. path: str
  40. collection_name: str
  41. type: str
  42. product_asset = AssetData(
  43. path="sample_scene/01_Products", collection_name="01_Products", type="product"
  44. )
  45. element_asset = AssetData(
  46. path="sample_scene/02_Elements", collection_name="02_Elements", type="asset"
  47. )
  48. basic_shapes_asset = AssetData(
  49. path="sample_scene/03_BasicShapes",
  50. collection_name="03_BasicShapes",
  51. type="shape",
  52. )
  53. def convert_base64_string_to_object(base64_string):
  54. bytes = base64.b64decode(base64_string)
  55. string = bytes.decode("ascii")
  56. return json.loads(string)
  57. return string
  58. def load_scene():
  59. print("Loading Scene")
  60. # load scene data
  61. scene_data = load_scene_data()
  62. print(scene_data)
  63. # create parent collections
  64. create_parent_collections(product_asset.collection_name)
  65. create_parent_collections(element_asset.collection_name)
  66. create_parent_collections(basic_shapes_asset.collection_name)
  67. create_parent_collections("05_Cameras")
  68. # append products
  69. products_data = load_objects_data(scene_data, product_asset.type)
  70. for index, product in enumerate(products_data):
  71. append_objects(product, index, product_asset)
  72. # append elements
  73. elements_data = load_objects_data(scene_data, element_asset.type)
  74. for index, product in enumerate(elements_data):
  75. append_objects(product, index, element_asset)
  76. # append shapes
  77. basic_shapes_data = load_objects_data(scene_data, basic_shapes_asset.type)
  78. for index, product in enumerate(basic_shapes_data):
  79. append_objects(product, index, basic_shapes_asset)
  80. # set lighting
  81. set_environment(scene_data)
  82. # set camera
  83. create_cameras(scene_data)
  84. # rename outputs
  85. set_output_paths(
  86. "D://Git//ap-canvas-creation-module//03_blender//sd_blender//sample_scene//Renders",
  87. scene_data["project_id"],
  88. )
  89. # setup compositing
  90. set_cryptomatte_objects("01_Products", "mask_product")
  91. def invert_id_name(json_data):
  92. for obj in json_data["scene"]["objects"]:
  93. obj["name"], obj["id"] = obj["id"], obj["name"]
  94. return json_data
  95. def load_scene_data():
  96. # print("Loading Scene Data")
  97. # # load scene data
  98. # # to be replaced with actual data
  99. # # open scene_info.json
  100. # script_path = Path(__file__).resolve()
  101. # scene_data_path = script_path.parent / "sample_scene" / "scene_info.json"
  102. # with scene_data_path.open() as file:
  103. # scene_data = json.load(file)
  104. # print(scene_data)
  105. # return scene_data
  106. # load scene data
  107. print("Loading Scene Data")
  108. if bpy.context.scene.load_local_DB:
  109. loaded_scene_data = bpy.context.scene.config_string
  110. # check if loaded_scene_data is base64 encoded
  111. if loaded_scene_data.startswith("ey"):
  112. scene_data = convert_base64_string_to_object(loaded_scene_data)
  113. else:
  114. scene_data = json.loads(loaded_scene_data)
  115. else:
  116. scene_data = json.loads(bpy.context.scene.shot_info_ai)
  117. # invert_scene_data = invert_id_name(scene_data)
  118. return scene_data
  119. def load_objects_data(scene_data, object_type: str):
  120. print("Loading Assets Data")
  121. # load assets data
  122. objects_data = []
  123. for object in scene_data["scene"]["objects"]:
  124. if object["group_type"] == object_type:
  125. # get additional object data by id and combine with object data
  126. object_data = get_object_data_by_id(object["id"])
  127. if object_data:
  128. # temporary fix
  129. # object_data = get_object_data_by_id(object["name"])
  130. object.update(object_data)
  131. objects_data.append(object)
  132. else:
  133. print("Object not found in database", object["id"], object["name"])
  134. return objects_data
  135. # to be replaced with actual data
  136. def get_object_data_by_id(object_id: str):
  137. print("Getting Object Data")
  138. # open assets_database.json
  139. script_path = Path(__file__).resolve()
  140. assets_data_path = script_path.parent / "sample_scene" / "assets_database.json"
  141. with assets_data_path.open() as file:
  142. assets_data = json.load(file)
  143. # get object data by id
  144. for object in assets_data:
  145. if object["id"] == object_id:
  146. return object
  147. def get_hdri_data_by_id(object_id: str):
  148. print("Getting HDRI Data")
  149. # open assets_database.json
  150. script_path = Path(__file__).resolve()
  151. assets_data_path = script_path.parent / "sample_scene" / "lighting_database.json"
  152. with assets_data_path.open() as file:
  153. assets_data = json.load(file)
  154. # get object data by id
  155. for object in assets_data:
  156. if object["id"] == object_id:
  157. return object
  158. def append_objects(asset_info, index, asset_data: AssetData):
  159. print("Appending Objects")
  160. blendFileName = asset_info["name"]
  161. # visibleLayersJSONName = productInfo["Version"]
  162. # activeSwitchMaterials = json.dumps(productInfo["ActiveMaterials"])
  163. collectionName = blendFileName + "_" + str(index)
  164. append_active_layers(collectionName, asset_info, asset_data)
  165. # replace_switch_materials(shotInfo, productInfo["ActiveMaterials"])
  166. link_collection_to_collection(
  167. asset_data.collection_name, bpy.data.collections[collectionName]
  168. )
  169. def append_active_layers(newCollectionName, product_info, asset_data: AssetData):
  170. utility_collections = [
  171. "MaterialLibrary",
  172. "Animation_Controller",
  173. "Animation_Rig",
  174. "Animation_Target",
  175. ]
  176. # visible_layers = utility_collections + product_info["VisibleLayers"]
  177. visible_layers = utility_collections
  178. script_path = Path(__file__).resolve().parent
  179. filePath = str(
  180. script_path
  181. / asset_data.path
  182. / product_info["name"]
  183. / "BLEND"
  184. / (product_info["name"] + ".blend")
  185. )
  186. print(filePath)
  187. # delete all objects and collections from product collection
  188. create_parent_collections(newCollectionName)
  189. # append active collections
  190. with bpy.data.libraries.load(filePath) as (data_from, data_to):
  191. data_to.collections = []
  192. for name in data_from.collections:
  193. if name in visible_layers:
  194. data_to.collections.append(name)
  195. if "NonConfigurable" in name:
  196. data_to.collections.append(name)
  197. # link appended colections to newCollection
  198. for collection in data_to.collections:
  199. # try:
  200. # bpy.context.scene.collection.children.link(collection)
  201. # except:
  202. # print(collection)
  203. link_collection_to_collection(newCollectionName, collection)
  204. # hide utility collections
  205. for utilityCollectionName in utility_collections:
  206. if utilityCollectionName in collection.name:
  207. # rename utility collections
  208. collection.name = newCollectionName + "_" + utilityCollectionName
  209. hide_collection(collection)
  210. # need to redo this in the future
  211. if "Animation_Target" in collection.name:
  212. # set the x location
  213. collection.objects[0].location.x = product_info["properties"][
  214. "transform"
  215. ]["position"][0]
  216. # set the y location
  217. collection.objects[0].location.y = -product_info["properties"][
  218. "transform"
  219. ]["position"][2]
  220. # set the z location
  221. collection.objects[0].location.z = product_info["properties"][
  222. "transform"
  223. ]["position"][1]
  224. # collection.objects[0].location = product_info["properties"][
  225. # "transform"
  226. # ]["position"]
  227. # collection.objects[0].rotation_euler = product_info["properties"][
  228. # "transform"
  229. # ]["rotation"]
  230. rotation_in_degrees = product_info["properties"]["transform"][
  231. "rotation"
  232. ]
  233. rotation_in_degrees[0] = rotation_in_degrees[0] + 90
  234. # set object rotation in euler from radians
  235. collection.objects[0].rotation_euler = (
  236. math.radians(rotation_in_degrees[0]),
  237. math.radians(rotation_in_degrees[2]),
  238. math.radians(rotation_in_degrees[1]),
  239. )
  240. collection.objects[0].scale = product_info["properties"]["transform"][
  241. "scale"
  242. ]
  243. # make all objects in collection local
  244. for obj in bpy.data.collections[newCollectionName].all_objects:
  245. if obj.type == "MESH":
  246. obj.make_local()
  247. obj.data.make_local()
  248. # remove duplicated material slots
  249. mats = bpy.data.materials
  250. for obj in bpy.data.collections[newCollectionName].all_objects:
  251. for slot in obj.material_slots:
  252. part = slot.name.rpartition(".")
  253. if part[2].isnumeric() and part[0] in mats:
  254. slot.material = mats.get(part[0])
  255. def create_parent_collections(group_name: str):
  256. if collection_exists(group_name):
  257. remove_collection_and_objects(group_name)
  258. else:
  259. create_collection(group_name)
  260. def set_environment(scene_data):
  261. # Find the group named NG_Canvas_Background in the Blender world
  262. world = bpy.context.scene.world
  263. if world is not None:
  264. # Get the node group named NG_Canvas_Background
  265. node_group = world.node_tree.nodes.get("NG_Canvas_Background")
  266. if node_group is not None:
  267. # Set the group's properties from scene_data
  268. node_group.inputs[0].default_value = float(
  269. scene_data["scene"]["environment"]["lighting"]["rotation"]
  270. )
  271. node_group.inputs[1].default_value = float(
  272. scene_data["scene"]["environment"]["lighting"]["intensity"]
  273. )
  274. if scene_data["scene"]["environment"]["lighting"]["visible"] == True:
  275. node_group.inputs[2].default_value = 1.0
  276. else:
  277. node_group.inputs[2].default_value = 0.0
  278. node_group.inputs[3].default_value = (
  279. scene_data["scene"]["environment"]["background"]["color"]["r"],
  280. scene_data["scene"]["environment"]["background"]["color"]["g"],
  281. scene_data["scene"]["environment"]["background"]["color"]["b"],
  282. 1.0,
  283. )
  284. hdri_data = get_hdri_data_by_id(
  285. scene_data["scene"]["environment"]["lighting"]["id"]
  286. )
  287. # go inside the node group, and find the image texture node, and set the image to the one from the scene data
  288. for node in node_group.node_tree.nodes:
  289. if node.name == "environment_map":
  290. node.image = bpy.data.images.load(
  291. str(
  292. Path(__file__).resolve().parent
  293. / "sample_scene"
  294. / "05_Lighting"
  295. / "HDRI"
  296. / (hdri_data["name"] + ".exr")
  297. )
  298. )
  299. else:
  300. print("Group 'NG_Canvas_Background' not found")
  301. def calculate_focal_length(fov, film_height):
  302. # Convert FOV from degrees to radians
  303. fov_rad = math.radians(fov)
  304. # Calculate the focal length
  305. focal_length = (film_height / 2) / math.tan(fov_rad / 2)
  306. return focal_length
  307. def quaternion_multiply(q1, q2):
  308. """
  309. Multiplies two quaternions.
  310. q1 and q2 are arrays or lists of length 4.
  311. Returns the resulting quaternion as a NumPy array.
  312. """
  313. w1, x1, y1, z1 = q1
  314. w2, x2, y2, z2 = q2
  315. w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2
  316. x = w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2
  317. y = w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2
  318. z = w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2
  319. return np.array([w, x, y, z])
  320. def create_cameras(scene_data):
  321. # # Get the 05_Cameras collection, or create it if it doesn't exist
  322. collection_name = "05_Cameras"
  323. if collection_name in bpy.data.collections:
  324. collection = bpy.data.collections[collection_name]
  325. else:
  326. return
  327. # Assuming `scene_data` and `collection` are already defined
  328. for camera_data in scene_data["scene"]["cameras"]:
  329. # Create a new camera object
  330. bpy.ops.object.camera_add()
  331. # Get the newly created camera
  332. camera = bpy.context.object
  333. # Set the camera's name
  334. camera.name = camera_data["name"]
  335. # Set the camera's position
  336. position = camera_data["properties"]["transform"]["position"]
  337. camera.location.x = position[0]
  338. camera.location.y = -position[2]
  339. camera.location.z = position[1]
  340. # Set the camera's rotation
  341. # # euler
  342. # rotation_euler = camera_data["properties"]["transform"]["rotation"]
  343. # rotation_euler = Euler(
  344. # (
  345. # math.radians(rotation_euler[0] + 90),
  346. # math.radians(-rotation_euler[2]),
  347. # math.radians(rotation_euler[1]),
  348. # ),
  349. # "XYZ",
  350. # )
  351. # quaternion
  352. rotation_quat_data = camera_data["properties"]["transform"]["rotation"]
  353. # rotation_quat = (
  354. # rotation_quat[3],
  355. # rotation_quat[0],
  356. # rotation_quat[1],
  357. # rotation_quat[2],
  358. # )
  359. # new_quat = Quaternion((2**0.5 / 2, 2**0.5 / 2, 0.0, 0.0))
  360. # current_quat = Quaternion(rotation_quat)
  361. # result_quat = current_quat @ new_quat
  362. # rotation_quat = (result_quat.w, result_quat.x, result_quat.y, result_quat.z)
  363. rotation_quat = [
  364. rotation_quat_data[3],
  365. rotation_quat_data[0],
  366. rotation_quat_data[1],
  367. rotation_quat_data[2],
  368. ] # Example quaternion
  369. # new_quat = [2**0.5 / 2, 2**0.5 / 2, 0.0, 0.0]
  370. # result_quat = quaternion_multiply(rotation_quat, new_quat)
  371. # Example quaternion from GLTF: [x, y, z, w]
  372. gltf_quat = [0.0, 0.707, 0.0, 0.707]
  373. # Convert the GLTF quaternion to Blender space (Y-up to Z-up)
  374. converted_quat = Quaternion(
  375. [
  376. rotation_quat_data[3],
  377. rotation_quat_data[0],
  378. rotation_quat_data[1],
  379. rotation_quat_data[2],
  380. ]
  381. )
  382. # Define the camera correction quaternion (from GLTF file)
  383. camera_correction = Quaternion((2**0.5 / 2, 2**0.5 / 2, 0.0, 0.0))
  384. # Apply the camera correction to the converted quaternion
  385. corrected_quat = camera_correction @ converted_quat
  386. # Apply the corrected quaternion to the camera's rotation
  387. camera.rotation_mode = "QUATERNION"
  388. camera.rotation_quaternion = corrected_quat
  389. # camera.rotation_mode = "QUATERNION"
  390. # camera.rotation_quaternion = rotation_quat
  391. # Apply the local rotation to the camera
  392. # Set the camera's lens properties
  393. lens = camera_data["properties"]["lens"]
  394. type_mapping = {
  395. "PERSPECTIVE": "PERSP",
  396. "ORTHOGRAPHIC": "ORTHO",
  397. "PANORAMIC": "PANO",
  398. }
  399. camera.data.lens = lens["focalLength"]
  400. camera.data.type = type_mapping.get(lens["type"].upper(), "PERSP")
  401. camera.data.clip_start = lens["near"]
  402. camera.data.clip_end = lens["far"]
  403. # Add the camera to the 05_Cameras collection
  404. collection.objects.link(camera)
  405. # Unlink the camera from the scene collection
  406. # check all objects in scene collection, if camera is there, unlink it
  407. for obj in bpy.context.scene.collection.objects:
  408. if obj.name == camera.name:
  409. bpy.context.scene.collection.objects.unlink(camera)
  410. # Set the camera as the active camera if "active" is true
  411. if camera_data["properties"]["active"]:
  412. bpy.context.scene.camera = camera
  413. def set_output_paths(base_path, project_name):
  414. # check if folder exist, if not create it
  415. folder_path = base_path + "//" + project_name
  416. if not os.path.exists(folder_path):
  417. os.makedirs(folder_path)
  418. # Get the current scene
  419. scene = bpy.context.scene
  420. # Check if the scene has a compositor node tree
  421. if scene.node_tree:
  422. # Iterate over all nodes in the node tree
  423. for node in scene.node_tree.nodes:
  424. # Check if the node is an output node
  425. if node.type == "OUTPUT_FILE":
  426. # Set the base path of the output node
  427. node.base_path = folder_path
  428. # Iterate over all file slots of the output node
  429. # for file_slot in node.file_slots:
  430. # # Set the path of the file slot
  431. # file_slot.path = project_name
  432. def set_cryptomatte_objects(collection_name, node_name):
  433. # Get all objects in the specified collection
  434. objects = bpy.data.collections[collection_name].all_objects
  435. # Convert the objects to a list
  436. object_names = [obj.name for obj in objects]
  437. print(object_names)
  438. # Get the current scene
  439. scene = bpy.context.scene
  440. # Check if the scene has a compositor node tree
  441. if scene.node_tree:
  442. # Iterate over all nodes in the node tree
  443. for node in scene.node_tree.nodes:
  444. # Check if the node is a Cryptomatte node with the specified name
  445. if node.type == "CRYPTOMATTE_V2" and node.name == node_name:
  446. # Set the Matte ID objects of the node
  447. node.matte_id = ",".join(object_names)
  448. # -------------------------------------------------------------------
  449. # Utilities
  450. # -------------------------------------------------------------------
  451. def get_all_objects_in_collection(collection):
  452. """Recursively get all objects in the given collection and its subcollections."""
  453. objects = []
  454. for obj in collection.objects:
  455. objects.append(obj)
  456. for subcollection in collection.children:
  457. objects.extend(get_all_objects_in_collection(subcollection))
  458. return objects
  459. def remove_collection_and_objects(collection_name):
  460. oldObjects = list(bpy.data.collections[collection_name].all_objects)
  461. for obj in oldObjects:
  462. bpy.data.objects.remove(obj, do_unlink=True)
  463. old_collection = bpy.data.collections[collection_name]
  464. if old_collection is not None:
  465. old_collection_names = get_subcollection_names(old_collection)
  466. else:
  467. print("Collection not found.")
  468. # print line break
  469. print("-----------------------------------------------------------------")
  470. print(old_collection_names)
  471. print("-----------------------------------------------------------------")
  472. for old_collection_name in old_collection_names:
  473. for collection in bpy.data.collections:
  474. if collection.name == old_collection_name:
  475. bpy.data.collections.remove(collection)
  476. bpy.ops.outliner.orphans_purge(
  477. do_local_ids=True, do_linked_ids=True, do_recursive=True
  478. )
  479. def get_subcollection_names(collection):
  480. subcollection_names = []
  481. for child in collection.children:
  482. subcollection_names.append(child.name)
  483. subcollection_names.extend(get_subcollection_names(child))
  484. return subcollection_names
  485. def select_objects_in_collection(collection):
  486. """Recursively select all objects in the given collection and its subcollections."""
  487. for obj in collection.objects:
  488. obj.select_set(True)
  489. for subcollection in collection.children:
  490. select_objects_in_collection(subcollection)
  491. def link_collection_to_collection(parentCollectionName, childCollection):
  492. if bpy.context.scene.collection.children:
  493. parentCollection = bpy.context.scene.collection.children.get(
  494. parentCollectionName
  495. )
  496. # Add it to the main collection
  497. # childCollection = bpy.context.scene.collection.children.get(childCollection)
  498. parentCollection.children.link(childCollection)
  499. # if child collection is in scene collection unlink it
  500. if bpy.context.scene.collection.children.get(childCollection.name):
  501. bpy.context.scene.collection.children.unlink(childCollection)
  502. # bpy.context.scene.collection.children.unlink(childCollection)
  503. # link collection to collection
  504. def link_collection_to_collection_old(parentCollectionName, childCollection):
  505. if bpy.context.scene.collection.children:
  506. parentCollection = bpy.context.scene.collection.children.get(
  507. parentCollectionName
  508. )
  509. # Add it to the main collection
  510. try:
  511. childCollection = bpy.data.collections[childCollection]
  512. except:
  513. print("Collection not found.")
  514. return
  515. parentCollection.children.link(childCollection)
  516. bpy.context.scene.collection.children.unlink(childCollection)
  517. # function that checks if a collection exists
  518. def collection_exists(collection_name):
  519. return collection_name in bpy.data.collections
  520. # function that creates a new collection and adds it to the scene
  521. def create_collection(collection_name):
  522. new_collection = bpy.data.collections.new(collection_name)
  523. bpy.context.scene.collection.children.link(new_collection)
  524. def hide_collection(collection):
  525. collection.hide_render = True
  526. collection.hide_viewport = True
  527. def check_if_selected_objects_have_parent(self):
  528. for obj in bpy.context.selected_objects:
  529. if obj.parent is None:
  530. message = f"Object {obj.name} has no parent"
  531. self.report({"ERROR"}, message)
  532. return False
  533. return True
  534. def add_rig_controller_to_selection(self):
  535. # add "Rig_Controller_Main" to the selection
  536. has_controller_object = False
  537. for obj in bpy.data.objects:
  538. if obj.name == "Rig_Controller_Main":
  539. if obj.hide_viewport:
  540. self.report({"ERROR"}, "Rig_Controller_Main is hidden")
  541. return has_controller_object
  542. obj.select_set(True)
  543. # if object is not visible, make it visible
  544. has_controller_object = True
  545. return has_controller_object
  546. if not has_controller_object:
  547. message = f"Rig_Controller_Main not found"
  548. self.report({"ERROR"}, message)
  549. print("Rig_Controller_Main not found")
  550. return has_controller_object
  551. def select_objects_in_collection(collection):
  552. """Recursively select all objects in the given collection and its subcollections."""
  553. for obj in collection.objects:
  554. obj.select_set(True)
  555. for subcollection in collection.children:
  556. select_objects_in_collection(subcollection)
  557. def check_if_object_has_principled_material(obj):
  558. for slot in obj.material_slots:
  559. # if more than one slot is principled, return
  560. for node in slot.material.node_tree.nodes:
  561. # print(node.type)
  562. if node.type == "BSDF_PRINCIPLED":
  563. return True
  564. else:
  565. print("Object has no principled material", obj.name)
  566. return False
  567. return True
  568. def unhide_all_objects():
  569. # show all objects using operator
  570. bpy.ops.object.hide_view_clear()
  571. # -------------------------------------------------------------------
  572. # Scene optimization
  573. # -------------------------------------------------------------------
  574. def export_non_configurable_to_fbx():
  575. # Get the current .blend file path
  576. blend_filepath = bpy.data.filepath
  577. if not blend_filepath:
  578. print("Save the .blend file first.")
  579. return
  580. # Get the parent directory of the .blend file
  581. blend_dir = os.path.dirname(blend_filepath)
  582. parent_dir = os.path.dirname(blend_dir)
  583. blend_filename = os.path.splitext(os.path.basename(blend_filepath))[0]
  584. # Create the FBX export path
  585. fbx_export_path = os.path.join(parent_dir, "FBX", f"{blend_filename}.fbx")
  586. # Ensure the FBX directory exists
  587. os.makedirs(os.path.dirname(fbx_export_path), exist_ok=True)
  588. # Deselect all objects
  589. bpy.ops.object.select_all(action="DESELECT")
  590. # Select all objects in the NonConfigurable collection
  591. collection_name = "NonConfigurable"
  592. if collection_name in bpy.data.collections:
  593. collection = bpy.data.collections[collection_name]
  594. for obj in collection.objects:
  595. obj.select_set(True)
  596. else:
  597. print(f"Collection '{collection_name}' not found.")
  598. return
  599. def export_scene_to_fbx(self):
  600. # Ensure the .blend file is saved
  601. if not bpy.data.is_saved:
  602. print("Save the .blend file first.")
  603. self.report({"ERROR"}, "Save the .blend file first.")
  604. return
  605. # Get the current .blend file path
  606. blend_filepath = bpy.data.filepath
  607. if not blend_filepath:
  608. print("Unable to get the .blend file path.")
  609. return
  610. # Get the parent directory of the .blend file
  611. blend_dir = os.path.dirname(blend_filepath)
  612. parent_dir = os.path.dirname(blend_dir)
  613. blend_filename = os.path.splitext(os.path.basename(blend_filepath))[0]
  614. # Create the FBX export path
  615. fbx_export_path = os.path.join(parent_dir, "FBX", f"{blend_filename}.fbx")
  616. # Ensure the FBX directory exists
  617. os.makedirs(os.path.dirname(fbx_export_path), exist_ok=True)
  618. # unhide all objects
  619. unhide_all_objects()
  620. # Deselect all objects
  621. bpy.ops.object.select_all(action="DESELECT")
  622. # Select all objects in the NonConfigurable collection and its subcollections
  623. collection_name = "NonConfigurable"
  624. if collection_name in bpy.data.collections:
  625. collection = bpy.data.collections[collection_name]
  626. select_objects_in_collection(collection)
  627. else:
  628. print(f"Collection '{collection_name}' not found.")
  629. return
  630. # check if all objects selected have a parent, if not return
  631. if not check_if_selected_objects_have_parent(self):
  632. return
  633. if not add_rig_controller_to_selection(self):
  634. return
  635. # Export selected objects to FBX
  636. bpy.ops.export_scene.fbx(
  637. filepath=fbx_export_path,
  638. use_selection=True,
  639. global_scale=1.0,
  640. apply_unit_scale=True,
  641. bake_space_transform=False,
  642. object_types={"MESH", "ARMATURE", "EMPTY"},
  643. use_mesh_modifiers=True,
  644. mesh_smooth_type="FACE",
  645. use_custom_props=True,
  646. # bake_anim=False,
  647. )
  648. print(f"Exported to {fbx_export_path}")
  649. def export_scene_to_glb(self):
  650. # Ensure the .blend file is saved
  651. if not bpy.data.is_saved:
  652. print("Save the .blend file first.")
  653. self.report({"ERROR"}, "Save the .blend file first.")
  654. return
  655. # Get the current .blend file path
  656. blend_filepath = bpy.data.filepath
  657. if not blend_filepath:
  658. print("Unable to get the .blend file path.")
  659. return
  660. # Get the parent directory of the .blend file
  661. blend_dir = os.path.dirname(blend_filepath)
  662. parent_dir = os.path.dirname(blend_dir)
  663. blend_filename = os.path.splitext(os.path.basename(blend_filepath))[0]
  664. # Create the GLB export path
  665. glb_export_path = os.path.join(parent_dir, "WEB", f"{blend_filename}.glb")
  666. # Ensure the GLB directory exists
  667. os.makedirs(os.path.dirname(glb_export_path), exist_ok=True)
  668. # unhide all objects
  669. unhide_all_objects()
  670. # Deselect all objects
  671. bpy.ops.object.select_all(action="DESELECT")
  672. # Select all objects in the NonConfigurable collection and its subcollections
  673. collection_name = "Web"
  674. for collection in bpy.data.collections:
  675. if collection_name == collection.name:
  676. select_objects_in_collection(collection)
  677. if not check_if_selected_objects_have_parent(self):
  678. return
  679. # check if all objects selected have a parent, if not return
  680. if not add_rig_controller_to_selection(self):
  681. return
  682. # # for each selected objects, check if the the material is principled, if not return
  683. # for obj in bpy.context.selected_objects:
  684. # if not check_if_object_has_principled_material(obj):
  685. # message = f"Object {obj.name} has no principled material"
  686. # self.report({"ERROR"}, message)
  687. # return
  688. # Export selected objects to GLB
  689. bpy.ops.export_scene.gltf(
  690. filepath=glb_export_path,
  691. export_format="GLB",
  692. use_selection=True,
  693. export_apply=True,
  694. export_animations=False,
  695. export_yup=True,
  696. export_cameras=False,
  697. export_lights=False,
  698. export_materials="EXPORT",
  699. export_normals=True,
  700. export_tangents=True,
  701. export_morph=False,
  702. export_skins=False,
  703. export_draco_mesh_compression_enable=False,
  704. export_draco_mesh_compression_level=6,
  705. export_draco_position_quantization=14,
  706. export_draco_normal_quantization=10,
  707. export_draco_texcoord_quantization=12,
  708. export_draco_color_quantization=10,
  709. export_draco_generic_quantization=12,
  710. export_keep_originals=False,
  711. export_texture_dir="",
  712. )
  713. print(f"Exported to {glb_export_path}")
  714. else:
  715. print(f"Collection '{collection_name}' not found.")
  716. return
  717. def copy_and_relink_textures(collection_name):
  718. # Ensure the target directory exists
  719. target_directory = bpy.path.abspath("//..")
  720. textures_directory = os.path.join(target_directory, "01_Textures")
  721. os.makedirs(textures_directory, exist_ok=True)
  722. # Get the collection
  723. collection = bpy.data.collections.get(collection_name)
  724. if not collection:
  725. print(f"Collection '{collection_name}' not found.")
  726. return
  727. # Iterate through each object in the collection
  728. objects = get_all_objects_in_collection(collection)
  729. for obj in objects:
  730. if obj.type != "MESH":
  731. continue
  732. # Iterate through each material of the object
  733. for mat_slot in obj.material_slots:
  734. material = mat_slot.material
  735. if not material:
  736. continue
  737. # Check if the material contains any image textures
  738. if material.use_nodes:
  739. for node in material.node_tree.nodes:
  740. if node.type == "TEX_IMAGE":
  741. image = node.image
  742. if image:
  743. # Copy the image texture to the target directory
  744. src_path = bpy.path.abspath(image.filepath)
  745. filename = os.path.basename(src_path)
  746. dest_path = os.path.join(textures_directory, filename)
  747. # Check if the source and destination paths are the same
  748. if os.path.abspath(src_path) != os.path.abspath(dest_path):
  749. # Check if the file already exists in the destination directory
  750. if not os.path.exists(dest_path):
  751. shutil.copy(src_path, dest_path)
  752. print(
  753. f"File '{filename}' copied to '{textures_directory}'"
  754. )
  755. else:
  756. print(
  757. f"File '{filename}' already exists in '{textures_directory}', relinking."
  758. )
  759. # Relink the image texture to the new location
  760. image.filepath = bpy.path.relpath(dest_path)
  761. image.reload()
  762. print(f"Textures copied and relinked to '{textures_directory}'.")
  763. def set_assets_render_output_paths():
  764. # Get the current scene
  765. scene = bpy.context.scene
  766. target_directory = bpy.path.abspath("//..")
  767. custom_folder = os.path.join(target_directory, "PNG")
  768. blender_file_name = os.path.splitext(bpy.path.basename(bpy.data.filepath))[0]
  769. components = blender_file_name.split("_")
  770. if len(components) != 7:
  771. raise ValueError(
  772. "Blender file name must be in the format 'Brand_AssetName_Year_ContentUsage_ContentType_AssetType_AssetNumber'"
  773. )
  774. brand = components[0]
  775. asset_name = components[1]
  776. year = components[2]
  777. content_usage = components[3]
  778. content_type = components[4]
  779. asset_type = components[5]
  780. asset_number = components[6]
  781. imag_asset_type = "IMG"
  782. # Construct the new .blend file name
  783. image_name = f"{brand}_{asset_name}_{year}_{content_usage}_{content_type}_{imag_asset_type}_{asset_number}_"
  784. # Ensure the scene has a compositor node tree
  785. if not scene.use_nodes:
  786. print("Scene does not use nodes.")
  787. return
  788. node_tree = scene.node_tree
  789. # Search for the ZS_Canvas_Output group node
  790. for node in node_tree.nodes:
  791. if node.type == "GROUP" and node.node_tree.name == "ZS_Canvas_Output":
  792. # Check inside the group for all file output nodes
  793. for sub_node in node.node_tree.nodes:
  794. if sub_node.type == "OUTPUT_FILE":
  795. # Set the base_path to the custom folder
  796. sub_node.base_path = custom_folder
  797. # Set the path for each file output slot to the Blender file name
  798. for output in sub_node.file_slots:
  799. output.path = image_name
  800. print("Output paths set.")
  801. # -------------------------------------------------------------------
  802. # Operators
  803. # -------------------------------------------------------------------
  804. # load scene operator
  805. class ZSSD_OT_LoadScene(bpy.types.Operator):
  806. bl_idname = "zs_sd_loader.load_scene"
  807. bl_label = "Load Scene"
  808. bl_description = "Load Scene"
  809. def execute(self, context):
  810. load_scene()
  811. return {"FINISHED"}
  812. # canvas exporter operator
  813. class ZSSD_OT_ExportAssets(bpy.types.Operator):
  814. bl_idname = "zs_canvas.export_assets"
  815. bl_label = "Export Assets"
  816. bl_description = "Export Scene Assets to FBX and GLB"
  817. def execute(self, context):
  818. copy_and_relink_textures("NonConfigurable")
  819. copy_and_relink_textures("Web")
  820. set_assets_render_output_paths()
  821. export_scene_to_fbx(self)
  822. export_scene_to_glb(self)
  823. return {"FINISHED"}
  824. # parent class for panels
  825. class ZSSDPanel:
  826. bl_space_type = "VIEW_3D"
  827. bl_region_type = "UI"
  828. bl_category = "ZS SD Loader"
  829. # -------------------------------------------------------------------
  830. # Draw
  831. # -------------------------------------------------------------------
  832. # Panels
  833. class ZSSD_PT_Main(ZSSDPanel, bpy.types.Panel):
  834. bl_label = "SD Loader"
  835. def draw(self, context):
  836. layout = self.layout
  837. scene = context.scene
  838. col = layout.column()
  839. self.is_connected = False
  840. col.label(text="Stable Diffusion Connection")
  841. col.prop(context.scene, "load_local_DB")
  842. col.prop(context.scene, "config_string")
  843. # load scene button
  844. col.operator("zs_sd_loader.load_scene", text="Load Scene")
  845. col.separator()
  846. # export assets button
  847. col.operator("zs_canvas.export_assets", text="Export Assets")
  848. # modify after making products
  849. blender_classes = [
  850. ZSSD_PT_Main,
  851. ZSSD_OT_LoadScene,
  852. ZSSD_OT_ExportAssets,
  853. ]
  854. def register():
  855. # register classes
  856. for blender_class in blender_classes:
  857. bpy.utils.register_class(blender_class)
  858. bpy.types.Scene.shot_info_ai = bpy.props.StringProperty(
  859. name="Shot Info",
  860. )
  861. bpy.types.Scene.config_string = bpy.props.StringProperty( # type: ignore
  862. name="Configuration String",
  863. )
  864. bpy.types.Scene.load_local_DB = bpy.props.BoolProperty( # type: ignore
  865. name="Load Local DB",
  866. )
  867. # Has to be afqter class registering to correctly register property
  868. # register global properties
  869. # register list
  870. # list data
  871. # bpy.types.Scene.zs_product_list = bpy.props.CollectionProperty(
  872. # type=ZS_Product_ListItem)
  873. # current item in list
  874. def unregister():
  875. # unregister classes
  876. for blender_class in blender_classes:
  877. bpy.utils.unregister_class(blender_class)
  878. # unregister global properties
  879. del bpy.types.Scene.shot_info_ai
  880. del bpy.types.Scene.config_string
  881. del bpy.types.Scene.load_local_DB
  882. # unregister list items
  883. # del bpy.types.Scene.my_list
  884. # del bpy.types.Scene.product_product_list_index