__init__.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  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. from pyquaternion import Quaternion
  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. # Convert Data Functions
  36. # -------------------------------------------------------------------
  37. def convert_loc(x):
  38. return u * Vector([x[0], -x[2], x[1]])
  39. def convert_quat(q):
  40. return Quaternion([q[3], q[0], -q[2], q[1]])
  41. def convert_scale(s):
  42. return Vector([s[0], s[2], s[1]])
  43. def local_rotation(obj, rotation_before, rot):
  44. """Appends a local rotation to vnode's world transform:
  45. (new world transform) = (old world transform) @ (rot)
  46. without changing the world transform of vnode's children.
  47. For correctness, rot must be a signed permutation of the axes
  48. (eg. (X Y Z)->(X -Z Y)) OR vnode's scale must always be uniform.
  49. """
  50. rotation_before = Quaternion((1, 0, 0, 0))
  51. obj.rotation_before @= rot
  52. # # Append the inverse rotation after children's TRS to cancel it out.
  53. # rot_inv = rot.conjugated()
  54. # for child in gltf.vnodes[vnode_id].children:
  55. # gltf.vnodes[child].rotation_after = rot_inv @ gltf.vnodes[child].rotation_after
  56. # -------------------------------------------------------------------
  57. # Functions
  58. # -------------------------------------------------------------------
  59. @dataclass
  60. class AssetData:
  61. path: str
  62. collection_name: str
  63. type: str
  64. product_asset = AssetData(
  65. path="sample_scene/01_Products", collection_name="01_Products", type="product"
  66. )
  67. element_asset = AssetData(
  68. path="sample_scene/02_Elements", collection_name="02_Elements", type="asset"
  69. )
  70. basic_shapes_asset = AssetData(
  71. path="sample_scene/03_BasicShapes",
  72. collection_name="03_BasicShapes",
  73. type="shape",
  74. )
  75. def convert_base64_string_to_object(base64_string):
  76. bytes = base64.b64decode(base64_string)
  77. string = bytes.decode("ascii")
  78. return json.loads(string)
  79. return string
  80. def load_scene():
  81. print("Loading Scene")
  82. # load scene data
  83. scene_data = load_scene_data()
  84. print(scene_data)
  85. # create parent collections
  86. create_parent_collections(product_asset.collection_name)
  87. create_parent_collections(element_asset.collection_name)
  88. create_parent_collections(basic_shapes_asset.collection_name)
  89. create_parent_collections("05_Cameras")
  90. # append products
  91. products_data = load_objects_data(scene_data, product_asset.type)
  92. for index, product in enumerate(products_data):
  93. append_objects(product, index, product_asset)
  94. # append elements
  95. elements_data = load_objects_data(scene_data, element_asset.type)
  96. for index, product in enumerate(elements_data):
  97. append_objects(product, index, element_asset)
  98. # append shapes
  99. basic_shapes_data = load_objects_data(scene_data, basic_shapes_asset.type)
  100. for index, product in enumerate(basic_shapes_data):
  101. append_objects(product, index, basic_shapes_asset)
  102. # set lighting
  103. set_environment(scene_data)
  104. # set camera
  105. create_cameras(scene_data)
  106. # rename outputs
  107. set_output_paths(
  108. "D://Git//ap-canvas-creation-module//03_blender//sd_blender//sample_scene//Renders",
  109. scene_data["project_id"],
  110. )
  111. # setup compositing
  112. set_cryptomatte_objects("01_Products", "mask_product")
  113. def invert_id_name(json_data):
  114. for obj in json_data["scene"]["objects"]:
  115. obj["name"], obj["id"] = obj["id"], obj["name"]
  116. return json_data
  117. def load_scene_data():
  118. # print("Loading Scene Data")
  119. # # load scene data
  120. # # to be replaced with actual data
  121. # # open scene_info.json
  122. # script_path = Path(__file__).resolve()
  123. # scene_data_path = script_path.parent / "sample_scene" / "scene_info.json"
  124. # with scene_data_path.open() as file:
  125. # scene_data = json.load(file)
  126. # print(scene_data)
  127. # return scene_data
  128. # load scene data
  129. print("Loading Scene Data")
  130. if bpy.context.scene.load_local_DB:
  131. loaded_scene_data = bpy.context.scene.config_string
  132. # check if loaded_scene_data is base64 encoded
  133. if loaded_scene_data.startswith("ey"):
  134. scene_data = convert_base64_string_to_object(loaded_scene_data)
  135. else:
  136. scene_data = json.loads(loaded_scene_data)
  137. else:
  138. scene_data = json.loads(bpy.context.scene.shot_info_ai)
  139. invert_scene_data = invert_id_name(scene_data)
  140. return invert_scene_data
  141. def load_objects_data(scene_data, object_type: str):
  142. print("Loading Assets Data")
  143. # load assets data
  144. objects_data = []
  145. for object in scene_data["scene"]["objects"]:
  146. if object["group_type"] == object_type:
  147. # get additional object data by id and combine with object data
  148. object_data = get_object_data_by_id(object["id"])
  149. # temporary fix
  150. # object_data = get_object_data_by_id(object["name"])
  151. object.update(object_data)
  152. objects_data.append(object)
  153. return objects_data
  154. # to be replaced with actual data
  155. def get_object_data_by_id(object_id: str):
  156. print("Getting Object Data")
  157. # open assets_database.json
  158. script_path = Path(__file__).resolve()
  159. assets_data_path = script_path.parent / "sample_scene" / "assets_database.json"
  160. with assets_data_path.open() as file:
  161. assets_data = json.load(file)
  162. # get object data by id
  163. for object in assets_data:
  164. if object["id"] == object_id:
  165. return object
  166. def get_hdri_data_by_id(object_id: str):
  167. print("Getting HDRI Data")
  168. # open assets_database.json
  169. script_path = Path(__file__).resolve()
  170. assets_data_path = script_path.parent / "sample_scene" / "lighting_database.json"
  171. with assets_data_path.open() as file:
  172. assets_data = json.load(file)
  173. # get object data by id
  174. for object in assets_data:
  175. if object["id"] == object_id:
  176. return object
  177. def append_objects(asset_info, index, asset_data: AssetData):
  178. print("Appending Objects")
  179. blendFileName = asset_info["name"]
  180. # visibleLayersJSONName = productInfo["Version"]
  181. # activeSwitchMaterials = json.dumps(productInfo["ActiveMaterials"])
  182. collectionName = blendFileName + "_" + str(index)
  183. append_active_layers(collectionName, asset_info, asset_data)
  184. # replace_switch_materials(shotInfo, productInfo["ActiveMaterials"])
  185. link_collection_to_collection(
  186. asset_data.collection_name, bpy.data.collections[collectionName]
  187. )
  188. def append_active_layers(newCollectionName, product_info, asset_data: AssetData):
  189. utility_collections = [
  190. "MaterialLibrary",
  191. "Animation_Controller",
  192. "Animation_Rig",
  193. "Animation_Target",
  194. ]
  195. # visible_layers = utility_collections + product_info["VisibleLayers"]
  196. visible_layers = utility_collections
  197. script_path = Path(__file__).resolve().parent
  198. filePath = str(
  199. script_path
  200. / asset_data.path
  201. / product_info["name"]
  202. / "BLEND"
  203. / (product_info["name"] + ".blend")
  204. )
  205. print(filePath)
  206. # delete all objects and collections from product collection
  207. create_parent_collections(newCollectionName)
  208. # append active collections
  209. with bpy.data.libraries.load(filePath) as (data_from, data_to):
  210. data_to.collections = []
  211. for name in data_from.collections:
  212. if name in visible_layers:
  213. data_to.collections.append(name)
  214. if "NonConfigurable" in name:
  215. data_to.collections.append(name)
  216. # link appended colections to newCollection
  217. for collection in data_to.collections:
  218. # try:
  219. # bpy.context.scene.collection.children.link(collection)
  220. # except:
  221. # print(collection)
  222. link_collection_to_collection(newCollectionName, collection)
  223. # hide utility collections
  224. for utilityCollectionName in utility_collections:
  225. if utilityCollectionName in collection.name:
  226. # rename utility collections
  227. collection.name = newCollectionName + "_" + utilityCollectionName
  228. hide_collection(collection)
  229. # need to redo this in the future
  230. if "Animation_Target" in collection.name:
  231. # set the x location
  232. collection.objects[0].location.x = product_info["properties"][
  233. "transform"
  234. ]["position"][0]
  235. # set the y location
  236. collection.objects[0].location.y = -product_info["properties"][
  237. "transform"
  238. ]["position"][2]
  239. # set the z location
  240. collection.objects[0].location.z = product_info["properties"][
  241. "transform"
  242. ]["position"][1]
  243. # collection.objects[0].location = product_info["properties"][
  244. # "transform"
  245. # ]["position"]
  246. # collection.objects[0].rotation_euler = product_info["properties"][
  247. # "transform"
  248. # ]["rotation"]
  249. rotation_in_degrees = product_info["properties"]["transform"][
  250. "rotation"
  251. ]
  252. rotation_in_degrees[0] = rotation_in_degrees[0] + 90
  253. # set object rotation in euler from radians
  254. collection.objects[0].rotation_euler = (
  255. math.radians(rotation_in_degrees[0]),
  256. math.radians(rotation_in_degrees[2]),
  257. math.radians(rotation_in_degrees[1]),
  258. )
  259. collection.objects[0].scale = product_info["properties"]["transform"][
  260. "scale"
  261. ]
  262. # make all objects in collection local
  263. for obj in bpy.data.collections[newCollectionName].all_objects:
  264. if obj.type == "MESH":
  265. obj.make_local()
  266. obj.data.make_local()
  267. # remove duplicated material slots
  268. mats = bpy.data.materials
  269. for obj in bpy.data.collections[newCollectionName].all_objects:
  270. for slot in obj.material_slots:
  271. part = slot.name.rpartition(".")
  272. if part[2].isnumeric() and part[0] in mats:
  273. slot.material = mats.get(part[0])
  274. def create_parent_collections(group_name: str):
  275. if collection_exists(group_name):
  276. remove_collection_and_objects(group_name)
  277. else:
  278. create_collection(group_name)
  279. def set_environment(scene_data):
  280. # Find the group named NG_Canvas_Background in the Blender world
  281. world = bpy.context.scene.world
  282. if world is not None:
  283. # Get the node group named NG_Canvas_Background
  284. node_group = world.node_tree.nodes.get("NG_Canvas_Background")
  285. if node_group is not None:
  286. # Set the group's properties from scene_data
  287. node_group.inputs[0].default_value = float(
  288. scene_data["scene"]["environment"]["lighting"]["rotation"]
  289. )
  290. node_group.inputs[1].default_value = float(
  291. scene_data["scene"]["environment"]["lighting"]["intensity"]
  292. )
  293. if scene_data["scene"]["environment"]["lighting"]["visible"] == True:
  294. node_group.inputs[2].default_value = 1.0
  295. else:
  296. node_group.inputs[2].default_value = 0.0
  297. node_group.inputs[3].default_value = (
  298. scene_data["scene"]["environment"]["background"]["color"]["r"],
  299. scene_data["scene"]["environment"]["background"]["color"]["g"],
  300. scene_data["scene"]["environment"]["background"]["color"]["b"],
  301. 1.0,
  302. )
  303. hdri_data = get_hdri_data_by_id(
  304. scene_data["scene"]["environment"]["lighting"]["id"]
  305. )
  306. # go inside the node group, and find the image texture node, and set the image to the one from the scene data
  307. for node in node_group.node_tree.nodes:
  308. if node.name == "environment_map":
  309. node.image = bpy.data.images.load(
  310. str(
  311. Path(__file__).resolve().parent
  312. / "sample_scene"
  313. / "05_Lighting"
  314. / "HDRI"
  315. / (hdri_data["name"] + ".exr")
  316. )
  317. )
  318. else:
  319. print("Group 'NG_Canvas_Background' not found")
  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. rotation = camera_data["properties"]["transform"]["rotation"]
  342. local_rotation = Euler(
  343. (
  344. math.radians(rotation[0]),
  345. math.radians(rotation[1]),
  346. math.radians(rotation[2]),
  347. ),
  348. "XYZ",
  349. )
  350. # Apply the local rotation to the camera
  351. camera.rotation_euler = local_rotation
  352. # Update the camera's matrix_world to apply the local transformation
  353. camera.matrix_world = camera.matrix_basis
  354. # Calculate the global rotation
  355. global_rotation = camera.matrix_world.to_euler()
  356. # Set the camera's rotation to the global rotation
  357. camera.rotation_euler = global_rotation
  358. # Set the camera's lens properties
  359. lens = camera_data["properties"]["lens"]
  360. type_mapping = {
  361. "PERSPECTIVE": "PERSP",
  362. "ORTHOGRAPHIC": "ORTHO",
  363. "PANORAMIC": "PANO",
  364. }
  365. camera.data.type = type_mapping.get(lens["type"].upper(), "PERSP")
  366. camera.data.angle = math.radians(lens["fov"])
  367. camera.data.clip_start = lens["near"]
  368. camera.data.clip_end = lens["far"]
  369. # Add the camera to the 05_Cameras collection
  370. collection.objects.link(camera)
  371. bpy.context.scene.collection.objects.unlink(camera)
  372. # Set the camera as the active camera if "active" is true
  373. if camera_data["properties"]["active"]:
  374. bpy.context.scene.camera = camera
  375. def set_output_paths(base_path, project_name):
  376. # check if folder exist, if not create it
  377. folder_path = base_path + "//" + project_name
  378. if not os.path.exists(folder_path):
  379. os.makedirs(folder_path)
  380. # Get the current scene
  381. scene = bpy.context.scene
  382. # Check if the scene has a compositor node tree
  383. if scene.node_tree:
  384. # Iterate over all nodes in the node tree
  385. for node in scene.node_tree.nodes:
  386. # Check if the node is an output node
  387. if node.type == "OUTPUT_FILE":
  388. # Set the base path of the output node
  389. node.base_path = folder_path
  390. # Iterate over all file slots of the output node
  391. # for file_slot in node.file_slots:
  392. # # Set the path of the file slot
  393. # file_slot.path = project_name
  394. def set_cryptomatte_objects(collection_name, node_name):
  395. # Get all objects in the specified collection
  396. objects = bpy.data.collections[collection_name].all_objects
  397. # Convert the objects to a list
  398. object_names = [obj.name for obj in objects]
  399. print(object_names)
  400. # Get the current scene
  401. scene = bpy.context.scene
  402. # Check if the scene has a compositor node tree
  403. if scene.node_tree:
  404. # Iterate over all nodes in the node tree
  405. for node in scene.node_tree.nodes:
  406. # Check if the node is a Cryptomatte node with the specified name
  407. if node.type == "CRYPTOMATTE_V2" and node.name == node_name:
  408. # Set the Matte ID objects of the node
  409. node.matte_id = ",".join(object_names)
  410. # -------------------------------------------------------------------
  411. # Utilities
  412. # -------------------------------------------------------------------
  413. def remove_collection_and_objects(collection_name):
  414. oldObjects = list(bpy.data.collections[collection_name].all_objects)
  415. for obj in oldObjects:
  416. bpy.data.objects.remove(obj, do_unlink=True)
  417. old_collection = bpy.data.collections[collection_name]
  418. if old_collection is not None:
  419. old_collection_names = get_subcollection_names(old_collection)
  420. else:
  421. print("Collection not found.")
  422. # print line break
  423. print("-----------------------------------------------------------------")
  424. print(old_collection_names)
  425. print("-----------------------------------------------------------------")
  426. for old_collection_name in old_collection_names:
  427. for collection in bpy.data.collections:
  428. if collection.name == old_collection_name:
  429. bpy.data.collections.remove(collection)
  430. bpy.ops.outliner.orphans_purge(
  431. do_local_ids=True, do_linked_ids=True, do_recursive=True
  432. )
  433. def get_subcollection_names(collection):
  434. subcollection_names = []
  435. for child in collection.children:
  436. subcollection_names.append(child.name)
  437. subcollection_names.extend(get_subcollection_names(child))
  438. return subcollection_names
  439. def select_objects_in_collection(collection):
  440. """Recursively select all objects in the given collection and its subcollections."""
  441. for obj in collection.objects:
  442. obj.select_set(True)
  443. for subcollection in collection.children:
  444. select_objects_in_collection(subcollection)
  445. def link_collection_to_collection(parentCollectionName, childCollection):
  446. if bpy.context.scene.collection.children:
  447. parentCollection = bpy.context.scene.collection.children.get(
  448. parentCollectionName
  449. )
  450. # Add it to the main collection
  451. # childCollection = bpy.context.scene.collection.children.get(childCollection)
  452. parentCollection.children.link(childCollection)
  453. # if child collection is in scene collection unlink it
  454. if bpy.context.scene.collection.children.get(childCollection.name):
  455. bpy.context.scene.collection.children.unlink(childCollection)
  456. # bpy.context.scene.collection.children.unlink(childCollection)
  457. # link collection to collection
  458. def link_collection_to_collection_old(parentCollectionName, childCollection):
  459. if bpy.context.scene.collection.children:
  460. parentCollection = bpy.context.scene.collection.children.get(
  461. parentCollectionName
  462. )
  463. # Add it to the main collection
  464. try:
  465. childCollection = bpy.data.collections[childCollection]
  466. except:
  467. print("Collection not found.")
  468. return
  469. parentCollection.children.link(childCollection)
  470. bpy.context.scene.collection.children.unlink(childCollection)
  471. # function that checks if a collection exists
  472. def collection_exists(collection_name):
  473. return collection_name in bpy.data.collections
  474. # function that creates a new collection and adds it to the scene
  475. def create_collection(collection_name):
  476. new_collection = bpy.data.collections.new(collection_name)
  477. bpy.context.scene.collection.children.link(new_collection)
  478. def hide_collection(collection):
  479. collection.hide_render = True
  480. collection.hide_viewport = True
  481. def check_if_selected_objects_have_parent(self):
  482. for obj in bpy.context.selected_objects:
  483. if obj.parent is None:
  484. message = f"Object {obj.name} has no parent"
  485. self.report({"ERROR"}, message)
  486. return False
  487. return True
  488. def add_rig_controller_to_selection(self):
  489. # add "Rig_Controller_Main" to the selection
  490. has_controller_object = False
  491. for obj in bpy.data.objects:
  492. if obj.name == "Rig_Controller_Main":
  493. if obj.hide_viewport:
  494. self.report({"ERROR"}, "Rig_Controller_Main is hidden")
  495. return has_controller_object
  496. obj.select_set(True)
  497. # if object is not visible, make it visible
  498. has_controller_object = True
  499. return has_controller_object
  500. if not has_controller_object:
  501. message = f"Rig_Controller_Main not found"
  502. self.report({"ERROR"}, message)
  503. print("Rig_Controller_Main not found")
  504. return has_controller_object
  505. def select_objects_in_collection(collection):
  506. """Recursively select all objects in the given collection and its subcollections."""
  507. for obj in collection.objects:
  508. obj.select_set(True)
  509. for subcollection in collection.children:
  510. select_objects_in_collection(subcollection)
  511. def check_if_object_has_principled_material(obj):
  512. for slot in obj.material_slots:
  513. # if more than one slot is principled, return
  514. for node in slot.material.node_tree.nodes:
  515. # print(node.type)
  516. if node.type == "BSDF_PRINCIPLED":
  517. return True
  518. else:
  519. print("Object has no principled material", obj.name)
  520. return False
  521. return True
  522. def unhide_all_objects():
  523. # show all objects using operator
  524. bpy.ops.object.hide_view_clear()
  525. # -------------------------------------------------------------------
  526. # Scene optimization
  527. # -------------------------------------------------------------------
  528. def export_non_configurable_to_fbx():
  529. # Get the current .blend file path
  530. blend_filepath = bpy.data.filepath
  531. if not blend_filepath:
  532. print("Save the .blend file first.")
  533. return
  534. # Get the parent directory of the .blend file
  535. blend_dir = os.path.dirname(blend_filepath)
  536. parent_dir = os.path.dirname(blend_dir)
  537. blend_filename = os.path.splitext(os.path.basename(blend_filepath))[0]
  538. # Create the FBX export path
  539. fbx_export_path = os.path.join(parent_dir, "FBX", f"{blend_filename}.fbx")
  540. # Ensure the FBX directory exists
  541. os.makedirs(os.path.dirname(fbx_export_path), exist_ok=True)
  542. # Deselect all objects
  543. bpy.ops.object.select_all(action="DESELECT")
  544. # Select all objects in the NonConfigurable collection
  545. collection_name = "NonConfigurable"
  546. if collection_name in bpy.data.collections:
  547. collection = bpy.data.collections[collection_name]
  548. for obj in collection.objects:
  549. obj.select_set(True)
  550. else:
  551. print(f"Collection '{collection_name}' not found.")
  552. return
  553. def export_scene_to_fbx(self):
  554. # Ensure the .blend file is saved
  555. if not bpy.data.is_saved:
  556. print("Save the .blend file first.")
  557. self.report({"ERROR"}, "Save the .blend file first.")
  558. return
  559. # Get the current .blend file path
  560. blend_filepath = bpy.data.filepath
  561. if not blend_filepath:
  562. print("Unable to get the .blend file path.")
  563. return
  564. # Get the parent directory of the .blend file
  565. blend_dir = os.path.dirname(blend_filepath)
  566. parent_dir = os.path.dirname(blend_dir)
  567. blend_filename = os.path.splitext(os.path.basename(blend_filepath))[0]
  568. # Create the FBX export path
  569. fbx_export_path = os.path.join(parent_dir, "FBX", f"{blend_filename}.fbx")
  570. # Ensure the FBX directory exists
  571. os.makedirs(os.path.dirname(fbx_export_path), exist_ok=True)
  572. # unhide all objects
  573. unhide_all_objects()
  574. # Deselect all objects
  575. bpy.ops.object.select_all(action="DESELECT")
  576. # Select all objects in the NonConfigurable collection and its subcollections
  577. collection_name = "NonConfigurable"
  578. if collection_name in bpy.data.collections:
  579. collection = bpy.data.collections[collection_name]
  580. select_objects_in_collection(collection)
  581. else:
  582. print(f"Collection '{collection_name}' not found.")
  583. return
  584. # check if all objects selected have a parent, if not return
  585. if not check_if_selected_objects_have_parent(self):
  586. return
  587. if not add_rig_controller_to_selection(self):
  588. return
  589. # Export selected objects to FBX
  590. bpy.ops.export_scene.fbx(
  591. filepath=fbx_export_path,
  592. use_selection=True,
  593. global_scale=1.0,
  594. apply_unit_scale=True,
  595. bake_space_transform=False,
  596. object_types={"MESH", "ARMATURE", "EMPTY"},
  597. use_mesh_modifiers=True,
  598. mesh_smooth_type="FACE",
  599. use_custom_props=True,
  600. # bake_anim=False,
  601. )
  602. print(f"Exported to {fbx_export_path}")
  603. def export_scene_to_glb(self):
  604. # Ensure the .blend file is saved
  605. if not bpy.data.is_saved:
  606. print("Save the .blend file first.")
  607. self.report({"ERROR"}, "Save the .blend file first.")
  608. return
  609. # Get the current .blend file path
  610. blend_filepath = bpy.data.filepath
  611. if not blend_filepath:
  612. print("Unable to get the .blend file path.")
  613. return
  614. # Get the parent directory of the .blend file
  615. blend_dir = os.path.dirname(blend_filepath)
  616. parent_dir = os.path.dirname(blend_dir)
  617. blend_filename = os.path.splitext(os.path.basename(blend_filepath))[0]
  618. # Create the GLB export path
  619. glb_export_path = os.path.join(parent_dir, "WEB", f"{blend_filename}.glb")
  620. # Ensure the GLB directory exists
  621. os.makedirs(os.path.dirname(glb_export_path), exist_ok=True)
  622. # unhide all objects
  623. unhide_all_objects()
  624. # Deselect all objects
  625. bpy.ops.object.select_all(action="DESELECT")
  626. # Select all objects in the NonConfigurable collection and its subcollections
  627. collection_name = "WebGL"
  628. if collection_name in bpy.data.collections:
  629. collection = bpy.data.collections[collection_name]
  630. select_objects_in_collection(collection)
  631. else:
  632. print(f"Collection '{collection_name}' not found.")
  633. return
  634. if not check_if_selected_objects_have_parent(self):
  635. return
  636. # check if all objects selected have a parent, if not return
  637. if not add_rig_controller_to_selection(self):
  638. return
  639. # # for each selected objects, check if the the material is principled, if not return
  640. # for obj in bpy.context.selected_objects:
  641. # if not check_if_object_has_principled_material(obj):
  642. # message = f"Object {obj.name} has no principled material"
  643. # self.report({"ERROR"}, message)
  644. # return
  645. # Export selected objects to GLB
  646. bpy.ops.export_scene.gltf(
  647. filepath=glb_export_path,
  648. export_format="GLB",
  649. use_selection=True,
  650. export_apply=True,
  651. export_animations=False,
  652. export_yup=True,
  653. export_cameras=False,
  654. export_lights=False,
  655. export_materials="EXPORT",
  656. export_normals=True,
  657. export_tangents=True,
  658. export_morph=False,
  659. export_skins=False,
  660. export_draco_mesh_compression_enable=False,
  661. export_draco_mesh_compression_level=6,
  662. export_draco_position_quantization=14,
  663. export_draco_normal_quantization=10,
  664. export_draco_texcoord_quantization=12,
  665. export_draco_color_quantization=10,
  666. export_draco_generic_quantization=12,
  667. export_keep_originals=False,
  668. export_texture_dir="",
  669. )
  670. print(f"Exported to {glb_export_path}")
  671. # -------------------------------------------------------------------
  672. # Operators
  673. # -------------------------------------------------------------------
  674. # load scene operator
  675. class ZSSD_OT_LoadScene(bpy.types.Operator):
  676. bl_idname = "zs_sd_loader.load_scene"
  677. bl_label = "Load Scene"
  678. bl_description = "Load Scene"
  679. def execute(self, context):
  680. load_scene()
  681. return {"FINISHED"}
  682. # canvas exporter operator
  683. class ZSSD_OT_ExportAssets(bpy.types.Operator):
  684. bl_idname = "zs_canvas.export_assets"
  685. bl_label = "Export Assets"
  686. bl_description = "Export Scene Assets to FBX and GLB"
  687. def execute(self, context):
  688. export_scene_to_fbx(self)
  689. export_scene_to_glb(self)
  690. return {"FINISHED"}
  691. # parent class for panels
  692. class ZSSDPanel:
  693. bl_space_type = "VIEW_3D"
  694. bl_region_type = "UI"
  695. bl_category = "ZS SD Loader"
  696. # -------------------------------------------------------------------
  697. # Draw
  698. # -------------------------------------------------------------------
  699. # Panels
  700. class ZSSD_PT_Main(ZSSDPanel, bpy.types.Panel):
  701. bl_label = "SD Loader"
  702. def draw(self, context):
  703. layout = self.layout
  704. scene = context.scene
  705. col = layout.column()
  706. self.is_connected = False
  707. col.label(text="Stable Diffusion Connection")
  708. col.prop(context.scene, "load_local_DB")
  709. col.prop(context.scene, "config_string")
  710. # load scene button
  711. col.operator("zs_sd_loader.load_scene", text="Load Scene")
  712. col.separator()
  713. # export assets button
  714. col.operator("zs_canvas.export_assets", text="Export Assets")
  715. # modify after making products
  716. blender_classes = [
  717. ZSSD_PT_Main,
  718. ZSSD_OT_LoadScene,
  719. ZSSD_OT_ExportAssets,
  720. ]
  721. def register():
  722. # register classes
  723. for blender_class in blender_classes:
  724. bpy.utils.register_class(blender_class)
  725. bpy.types.Scene.shot_info_ai = bpy.props.StringProperty(
  726. name="Shot Info",
  727. )
  728. bpy.types.Scene.config_string = bpy.props.StringProperty( # type: ignore
  729. name="Configuration String",
  730. )
  731. bpy.types.Scene.load_local_DB = bpy.props.BoolProperty( # type: ignore
  732. name="Load Local DB",
  733. )
  734. # Has to be afqter class registering to correctly register property
  735. # register global properties
  736. # register list
  737. # list data
  738. # bpy.types.Scene.zs_product_list = bpy.props.CollectionProperty(
  739. # type=ZS_Product_ListItem)
  740. # current item in list
  741. def unregister():
  742. # unregister classes
  743. for blender_class in blender_classes:
  744. bpy.utils.unregister_class(blender_class)
  745. # unregister global properties
  746. del bpy.types.Scene.shot_info_ai
  747. del bpy.types.Scene.config_string
  748. del bpy.types.Scene.load_local_DB
  749. # unregister list items
  750. # del bpy.types.Scene.my_list
  751. # del bpy.types.Scene.product_product_list_index