__init__.py 31 KB

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