file_path
stringlengths
21
207
content
stringlengths
5
1.02M
size
int64
5
1.02M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.27
0.93
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/allegro_hand.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional import carb import numpy as np import torch from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage from pxr import Gf, PhysxSchema, Sdf, Usd, UsdGeom, UsdPhysics class AllegroHand(Robot): def __init__( self, prim_path: str, name: Optional[str] = "allegro_hand", usd_path: Optional[str] = None, translation: Optional[torch.tensor] = None, orientation: Optional[torch.tensor] = None, ) -> None: self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Robots/AllegroHand/allegro_hand_instanceable.usd" self._position = torch.tensor([0.0, 0.0, 0.5]) if translation is None else translation self._orientation = ( torch.tensor([0.257551, 0.283045, 0.683330, -0.621782]) if orientation is None else orientation ) add_reference_to_stage(self._usd_path, prim_path) super().__init__( prim_path=prim_path, name=name, translation=self._position, orientation=self._orientation, articulation_controller=None, ) def set_allegro_hand_properties(self, stage, allegro_hand_prim): for link_prim in allegro_hand_prim.GetChildren(): if not ( link_prim == stage.GetPrimAtPath("/allegro/Looks") or link_prim == stage.GetPrimAtPath("/allegro/root_joint") ): rb = PhysxSchema.PhysxRigidBodyAPI.Apply(link_prim) rb.GetDisableGravityAttr().Set(True) rb.GetRetainAccelerationsAttr().Set(False) rb.GetEnableGyroscopicForcesAttr().Set(False) rb.GetAngularDampingAttr().Set(0.01) rb.GetMaxLinearVelocityAttr().Set(1000) rb.GetMaxAngularVelocityAttr().Set(64 / np.pi * 180) rb.GetMaxDepenetrationVelocityAttr().Set(1000) rb.GetMaxContactImpulseAttr().Set(1e32) def set_motor_control_mode(self, stage, allegro_hand_path): prim = stage.GetPrimAtPath(allegro_hand_path) self._set_joint_properties(stage, prim) def _set_joint_properties(self, stage, prim): if prim.HasAPI(UsdPhysics.DriveAPI): drive = UsdPhysics.DriveAPI.Apply(prim, "angular") drive.GetStiffnessAttr().Set(3 * np.pi / 180) drive.GetDampingAttr().Set(0.1 * np.pi / 180) drive.GetMaxForceAttr().Set(0.5) revolute_joint = PhysxSchema.PhysxJointAPI.Get(stage, prim.GetPath()) revolute_joint.GetJointFrictionAttr().Set(0.01) for child_prim in prim.GetChildren(): self._set_joint_properties(stage, child_prim)
4,627
Python
43.5
107
0.673655
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/shadow_hand.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional import carb import numpy as np import torch from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage from omniisaacgymenvs.tasks.utils.usd_utils import set_drive from pxr import Gf, PhysxSchema, Sdf, Usd, UsdGeom, UsdPhysics class ShadowHand(Robot): def __init__( self, prim_path: str, name: Optional[str] = "shadow_hand", usd_path: Optional[str] = None, translation: Optional[torch.tensor] = None, orientation: Optional[torch.tensor] = None, ) -> None: self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Robots/ShadowHand/shadow_hand_instanceable.usd" self._position = torch.tensor([0.0, 0.0, 0.5]) if translation is None else translation self._orientation = torch.tensor([1.0, 0.0, 0.0, 0.0]) if orientation is None else orientation add_reference_to_stage(self._usd_path, prim_path) super().__init__( prim_path=prim_path, name=name, translation=self._position, orientation=self._orientation, articulation_controller=None, ) def set_shadow_hand_properties(self, stage, shadow_hand_prim): for link_prim in shadow_hand_prim.GetChildren(): if link_prim.HasAPI(PhysxSchema.PhysxRigidBodyAPI): rb = PhysxSchema.PhysxRigidBodyAPI.Get(stage, link_prim.GetPrimPath()) rb.GetDisableGravityAttr().Set(True) rb.GetRetainAccelerationsAttr().Set(True) def set_motor_control_mode(self, stage, shadow_hand_path): joints_config = { "robot0_WRJ1": {"stiffness": 5, "damping": 0.5, "max_force": 4.785}, "robot0_WRJ0": {"stiffness": 5, "damping": 0.5, "max_force": 2.175}, "robot0_FFJ3": {"stiffness": 1, "damping": 0.1, "max_force": 0.9}, "robot0_FFJ2": {"stiffness": 1, "damping": 0.1, "max_force": 0.9}, "robot0_FFJ1": {"stiffness": 1, "damping": 0.1, "max_force": 0.7245}, "robot0_MFJ3": {"stiffness": 1, "damping": 0.1, "max_force": 0.9}, "robot0_MFJ2": {"stiffness": 1, "damping": 0.1, "max_force": 0.9}, "robot0_MFJ1": {"stiffness": 1, "damping": 0.1, "max_force": 0.7245}, "robot0_RFJ3": {"stiffness": 1, "damping": 0.1, "max_force": 0.9}, "robot0_RFJ2": {"stiffness": 1, "damping": 0.1, "max_force": 0.9}, "robot0_RFJ1": {"stiffness": 1, "damping": 0.1, "max_force": 0.7245}, "robot0_LFJ4": {"stiffness": 1, "damping": 0.1, "max_force": 0.9}, "robot0_LFJ3": {"stiffness": 1, "damping": 0.1, "max_force": 0.9}, "robot0_LFJ2": {"stiffness": 1, "damping": 0.1, "max_force": 0.9}, "robot0_LFJ1": {"stiffness": 1, "damping": 0.1, "max_force": 0.7245}, "robot0_THJ4": {"stiffness": 1, "damping": 0.1, "max_force": 2.3722}, "robot0_THJ3": {"stiffness": 1, "damping": 0.1, "max_force": 1.45}, "robot0_THJ2": {"stiffness": 1, "damping": 0.1, "max_force": 0.99}, "robot0_THJ1": {"stiffness": 1, "damping": 0.1, "max_force": 0.99}, "robot0_THJ0": {"stiffness": 1, "damping": 0.1, "max_force": 0.81}, } for joint_name, config in joints_config.items(): set_drive( f"{self.prim_path}/joints/{joint_name}", "angular", "position", 0.0, config["stiffness"] * np.pi / 180, config["damping"] * np.pi / 180, config["max_force"], )
5,517
Python
46.982608
103
0.623527
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/crazyflie.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional import carb import numpy as np import torch from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage class Crazyflie(Robot): def __init__( self, prim_path: str, name: Optional[str] = "crazyflie", usd_path: Optional[str] = None, translation: Optional[np.ndarray] = None, orientation: Optional[np.ndarray] = None, scale: Optional[np.array] = None, ) -> None: """[summary]""" self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Robots/Crazyflie/cf2x.usd" add_reference_to_stage(self._usd_path, prim_path) scale = torch.tensor([5, 5, 5]) super().__init__(prim_path=prim_path, name=name, translation=translation, orientation=orientation, scale=scale)
2,720
Python
40.861538
119
0.718015
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/cabinet.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from typing import Optional import numpy as np import torch from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage class Cabinet(Robot): def __init__( self, prim_path: str, name: Optional[str] = "cabinet", usd_path: Optional[str] = None, translation: Optional[torch.tensor] = None, orientation: Optional[torch.tensor] = None, ) -> None: """[summary]""" self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Props/Sektion_Cabinet/sektion_cabinet_instanceable.usd" add_reference_to_stage(self._usd_path, prim_path) self._position = torch.tensor([0.0, 0.0, 0.4]) if translation is None else translation self._orientation = torch.tensor([0.1, 0.0, 0.0, 0.0]) if orientation is None else orientation super().__init__( prim_path=prim_path, name=name, translation=self._position, orientation=self._orientation, articulation_controller=None, )
1,819
Python
35.399999
111
0.660803
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/humanoid.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional import carb import numpy as np import torch from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage class Humanoid(Robot): def __init__( self, prim_path: str, name: Optional[str] = "Humanoid", usd_path: Optional[str] = None, translation: Optional[np.ndarray] = None, orientation: Optional[np.ndarray] = None, ) -> None: self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Robots/Humanoid/humanoid_instanceable.usd" add_reference_to_stage(self._usd_path, prim_path) super().__init__( prim_path=prim_path, name=name, translation=translation, orientation=orientation, articulation_controller=None, )
2,716
Python
38.955882
98
0.71134
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/franka.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import math from typing import Optional import numpy as np import torch from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.prims import get_prim_at_path from omni.isaac.core.utils.stage import add_reference_to_stage from omniisaacgymenvs.tasks.utils.usd_utils import set_drive from pxr import PhysxSchema class Franka(Robot): def __init__( self, prim_path: str, name: Optional[str] = "franka", usd_path: Optional[str] = None, translation: Optional[torch.tensor] = None, orientation: Optional[torch.tensor] = None, ) -> None: """[summary]""" self._usd_path = usd_path self._name = name self._position = torch.tensor([1.0, 0.0, 0.0]) if translation is None else translation self._orientation = torch.tensor([0.0, 0.0, 0.0, 1.0]) if orientation is None else orientation if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Robots/Franka/franka_instanceable.usd" add_reference_to_stage(self._usd_path, prim_path) super().__init__( prim_path=prim_path, name=name, translation=self._position, orientation=self._orientation, articulation_controller=None, ) dof_paths = [ "panda_link0/panda_joint1", "panda_link1/panda_joint2", "panda_link2/panda_joint3", "panda_link3/panda_joint4", "panda_link4/panda_joint5", "panda_link5/panda_joint6", "panda_link6/panda_joint7", "panda_hand/panda_finger_joint1", "panda_hand/panda_finger_joint2", ] drive_type = ["angular"] * 7 + ["linear"] * 2 default_dof_pos = [math.degrees(x) for x in [0.0, -1.0, 0.0, -2.2, 0.0, 2.4, 0.8]] + [0.02, 0.02] stiffness = [400 * np.pi / 180] * 7 + [10000] * 2 damping = [80 * np.pi / 180] * 7 + [100] * 2 max_force = [87, 87, 87, 87, 12, 12, 12, 200, 200] max_velocity = [math.degrees(x) for x in [2.175, 2.175, 2.175, 2.175, 2.61, 2.61, 2.61]] + [0.2, 0.2] for i, dof in enumerate(dof_paths): set_drive( prim_path=f"{self.prim_path}/{dof}", drive_type=drive_type[i], target_type="position", target_value=default_dof_pos[i], stiffness=stiffness[i], damping=damping[i], max_force=max_force[i], ) PhysxSchema.PhysxJointAPI(get_prim_at_path(f"{self.prim_path}/{dof}")).CreateMaxJointVelocityAttr().Set( max_velocity[i] ) def set_franka_properties(self, stage, prim): for link_prim in prim.GetChildren(): if link_prim.HasAPI(PhysxSchema.PhysxRigidBodyAPI): rb = PhysxSchema.PhysxRigidBodyAPI.Get(stage, link_prim.GetPrimPath()) rb.GetDisableGravityAttr().Set(True)
3,653
Python
37.0625
116
0.599781
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/ant.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional import carb import numpy as np import torch from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage class Ant(Robot): def __init__( self, prim_path: str, name: Optional[str] = "Ant", usd_path: Optional[str] = None, translation: Optional[np.ndarray] = None, orientation: Optional[np.ndarray] = None, ) -> None: self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Robots/Ant/ant_instanceable.usd" add_reference_to_stage(self._usd_path, prim_path) super().__init__( prim_path=prim_path, name=name, translation=translation, orientation=orientation, articulation_controller=None, )
2,696
Python
38.661764
88
0.709199
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/cartpole.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional import carb import numpy as np import torch from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage class Cartpole(Robot): def __init__( self, prim_path: str, name: Optional[str] = "Cartpole", usd_path: Optional[str] = None, translation: Optional[np.ndarray] = None, orientation: Optional[np.ndarray] = None, ) -> None: self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Robots/Cartpole/cartpole.usd" add_reference_to_stage(self._usd_path, prim_path) super().__init__( prim_path=prim_path, name=name, translation=translation, orientation=orientation, articulation_controller=None, )
2,703
Python
38.764705
85
0.710322
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/factory_franka.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import math from typing import Optional import numpy as np import torch from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.prims import get_prim_at_path from omni.isaac.core.utils.stage import add_reference_to_stage from omniisaacgymenvs.tasks.utils.usd_utils import set_drive from pxr import PhysxSchema class FactoryFranka(Robot): def __init__( self, prim_path: str, name: Optional[str] = "franka", usd_path: Optional[str] = None, translation: Optional[torch.tensor] = None, orientation: Optional[torch.tensor] = None, ) -> None: """[summary]""" self._usd_path = usd_path self._name = name self._position = torch.tensor([1.0, 0.0, 0.0]) if translation is None else translation self._orientation = torch.tensor([0.0, 0.0, 0.0, 1.0]) if orientation is None else orientation if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Robots/FactoryFranka/factory_franka.usd" add_reference_to_stage(self._usd_path, prim_path) super().__init__( prim_path=prim_path, name=name, translation=self._position, orientation=self._orientation, articulation_controller=None, ) dof_paths = [ "panda_link0/panda_joint1", "panda_link1/panda_joint2", "panda_link2/panda_joint3", "panda_link3/panda_joint4", "panda_link4/panda_joint5", "panda_link5/panda_joint6", "panda_link6/panda_joint7", "panda_hand/panda_finger_joint1", "panda_hand/panda_finger_joint2", ] drive_type = ["angular"] * 7 + ["linear"] * 2 default_dof_pos = [math.degrees(x) for x in [0.0, -1.0, 0.0, -2.2, 0.0, 2.4, 0.8]] + [0.02, 0.02] stiffness = [40 * np.pi / 180] * 7 + [500] * 2 damping = [80 * np.pi / 180] * 7 + [20] * 2 max_force = [87, 87, 87, 87, 12, 12, 12, 200, 200] max_velocity = [math.degrees(x) for x in [2.175, 2.175, 2.175, 2.175, 2.61, 2.61, 2.61]] + [0.2, 0.2] for i, dof in enumerate(dof_paths): set_drive( prim_path=f"{self.prim_path}/{dof}", drive_type=drive_type[i], target_type="position", target_value=default_dof_pos[i], stiffness=stiffness[i], damping=damping[i], max_force=max_force[i], ) PhysxSchema.PhysxJointAPI(get_prim_at_path(f"{self.prim_path}/{dof}")).CreateMaxJointVelocityAttr().Set( max_velocity[i] )
3,356
Python
36.719101
116
0.596544
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/quadcopter.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional import numpy as np import torch from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage class Quadcopter(Robot): def __init__( self, prim_path: str, name: Optional[str] = "Quadcopter", usd_path: Optional[str] = None, translation: Optional[np.ndarray] = None, orientation: Optional[np.ndarray] = None, ) -> None: """[summary]""" self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = assets_root_path + "/Isaac/Robots/Quadcopter/quadcopter.usd" add_reference_to_stage(self._usd_path, prim_path) super().__init__( prim_path=prim_path, name=name, position=translation, orientation=orientation, articulation_controller=None, )
2,719
Python
39.597014
89
0.706878
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/ingenuity.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional import numpy as np import torch from omni.isaac.core.prims import RigidPrimView from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage class Ingenuity(Robot): def __init__( self, prim_path: str, name: Optional[str] = "ingenuity", usd_path: Optional[str] = None, translation: Optional[np.ndarray] = None, orientation: Optional[np.ndarray] = None, scale: Optional[np.array] = None, ) -> None: """[summary]""" self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") self._usd_path = ( assets_root_path + "/Isaac/Robots/Ingenuity/ingenuity.usd" ) add_reference_to_stage(self._usd_path, prim_path) scale = torch.tensor([0.01, 0.01, 0.01]) super().__init__(prim_path=prim_path, name=name, translation=translation, orientation=orientation, scale=scale)
2,802
Python
40.83582
119
0.711991
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/anymal.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional import numpy as np import torch from omni.isaac.core.prims import RigidPrimView from omni.isaac.core.robots.robot import Robot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage from pxr import PhysxSchema class Anymal(Robot): def __init__( self, prim_path: str, name: Optional[str] = "Anymal", usd_path: Optional[str] = None, translation: Optional[np.ndarray] = None, orientation: Optional[np.ndarray] = None, ) -> None: """[summary]""" self._usd_path = usd_path self._name = name if self._usd_path is None: assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find nucleus server with /Isaac folder") self._usd_path = assets_root_path + "/Isaac/Robots/ANYbotics/anymal_instanceable.usd" add_reference_to_stage(self._usd_path, prim_path) super().__init__( prim_path=prim_path, name=name, translation=translation, orientation=orientation, articulation_controller=None, ) self._dof_names = [ "LF_HAA", "LH_HAA", "RF_HAA", "RH_HAA", "LF_HFE", "LH_HFE", "RF_HFE", "RH_HFE", "LF_KFE", "LH_KFE", "RF_KFE", "RH_KFE", ] @property def dof_names(self): return self._dof_names def set_anymal_properties(self, stage, prim): for link_prim in prim.GetChildren(): if link_prim.HasAPI(PhysxSchema.PhysxRigidBodyAPI): rb = PhysxSchema.PhysxRigidBodyAPI.Get(stage, link_prim.GetPrimPath()) rb.GetDisableGravityAttr().Set(False) rb.GetRetainAccelerationsAttr().Set(False) rb.GetLinearDampingAttr().Set(0.0) rb.GetMaxLinearVelocityAttr().Set(1000.0) rb.GetAngularDampingAttr().Set(0.0) rb.GetMaxAngularVelocityAttr().Set(64 / np.pi * 180) def prepare_contacts(self, stage, prim): for link_prim in prim.GetChildren(): if link_prim.HasAPI(PhysxSchema.PhysxRigidBodyAPI): if "_HIP" not in str(link_prim.GetPrimPath()): rb = PhysxSchema.PhysxRigidBodyAPI.Get(stage, link_prim.GetPrimPath()) rb.CreateSleepThresholdAttr().Set(0) cr_api = PhysxSchema.PhysxContactReportAPI.Apply(link_prim) cr_api.CreateThresholdAttr().Set(0)
4,273
Python
38.943925
97
0.648022
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/views/cabinet_view.py
from typing import Optional from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.prims import RigidPrimView class CabinetView(ArticulationView): def __init__( self, prim_paths_expr: str, name: Optional[str] = "CabinetView", ) -> None: """[summary]""" super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False) self._drawers = RigidPrimView( prim_paths_expr="/World/envs/.*/cabinet/drawer_top", name="drawers_view", reset_xform_properties=False )
586
Python
28.349999
114
0.653584
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/views/shadow_hand_view.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional import torch from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.prims import RigidPrimView class ShadowHandView(ArticulationView): def __init__( self, prim_paths_expr: str, name: Optional[str] = "ShadowHandView", ) -> None: super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False) self._fingers = RigidPrimView( prim_paths_expr="/World/envs/.*/shadow_hand/robot0.*distal", name="finger_view", reset_xform_properties=False, ) @property def actuated_dof_indices(self): return self._actuated_dof_indices def initialize(self, physics_sim_view): super().initialize(physics_sim_view) self.actuated_joint_names = [ "robot0_WRJ1", "robot0_WRJ0", "robot0_FFJ3", "robot0_FFJ2", "robot0_FFJ1", "robot0_MFJ3", "robot0_MFJ2", "robot0_MFJ1", "robot0_RFJ3", "robot0_RFJ2", "robot0_RFJ1", "robot0_LFJ4", "robot0_LFJ3", "robot0_LFJ2", "robot0_LFJ1", "robot0_THJ4", "robot0_THJ3", "robot0_THJ2", "robot0_THJ1", "robot0_THJ0", ] self._actuated_dof_indices = list() for joint_name in self.actuated_joint_names: self._actuated_dof_indices.append(self.get_dof_index(joint_name)) self._actuated_dof_indices.sort() limit_stiffness = torch.tensor([30.0] * self.num_fixed_tendons, device=self._device) damping = torch.tensor([0.1] * self.num_fixed_tendons, device=self._device) self.set_fixed_tendon_properties(dampings=damping, limit_stiffnesses=limit_stiffness) fingertips = ["robot0_ffdistal", "robot0_mfdistal", "robot0_rfdistal", "robot0_lfdistal", "robot0_thdistal"] self._sensor_indices = torch.tensor([self._body_indices[j] for j in fingertips], device=self._device, dtype=torch.long)
3,681
Python
38.591397
127
0.669383
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/views/franka_view.py
from typing import Optional from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.prims import RigidPrimView class FrankaView(ArticulationView): def __init__( self, prim_paths_expr: str, name: Optional[str] = "FrankaView", ) -> None: """[summary]""" super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False) self._hands = RigidPrimView( prim_paths_expr="/World/envs/.*/franka/panda_link7", name="hands_view", reset_xform_properties=False ) self._lfingers = RigidPrimView( prim_paths_expr="/World/envs/.*/franka/panda_leftfinger", name="lfingers_view", reset_xform_properties=False ) self._rfingers = RigidPrimView( prim_paths_expr="/World/envs/.*/franka/panda_rightfinger", name="rfingers_view", reset_xform_properties=False, ) def initialize(self, physics_sim_view): super().initialize(physics_sim_view) self._gripper_indices = [self.get_dof_index("panda_finger_joint1"), self.get_dof_index("panda_finger_joint2")] @property def gripper_indices(self): return self._gripper_indices
1,241
Python
32.567567
120
0.637389
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/views/factory_franka_view.py
from typing import Optional from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.prims import RigidPrimView class FactoryFrankaView(ArticulationView): def __init__( self, prim_paths_expr: str, name: Optional[str] = "FactoryFrankaView", ) -> None: """Initialize articulation view.""" super().__init__( prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False ) self._hands = RigidPrimView( prim_paths_expr="/World/envs/.*/franka/panda_hand", name="hands_view", reset_xform_properties=False, ) self._lfingers = RigidPrimView( prim_paths_expr="/World/envs/.*/franka/panda_leftfinger", name="lfingers_view", reset_xform_properties=False, track_contact_forces=True, ) self._rfingers = RigidPrimView( prim_paths_expr="/World/envs/.*/franka/panda_rightfinger", name="rfingers_view", reset_xform_properties=False, track_contact_forces=True, ) self._fingertip_centered = RigidPrimView( prim_paths_expr="/World/envs/.*/franka/panda_fingertip_centered", name="fingertips_view", reset_xform_properties=False, ) def initialize(self, physics_sim_view): """Initialize physics simulation view.""" super().initialize(physics_sim_view)
1,488
Python
31.369565
84
0.598118
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/views/anymal_view.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.prims import RigidPrimView class AnymalView(ArticulationView): def __init__( self, prim_paths_expr: str, name: Optional[str] = "AnymalView", track_contact_forces=False, prepare_contact_sensors=False, ) -> None: """[summary]""" super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False) self._knees = RigidPrimView( prim_paths_expr="/World/envs/.*/anymal/.*_THIGH", name="knees_view", reset_xform_properties=False, track_contact_forces=track_contact_forces, prepare_contact_sensors=prepare_contact_sensors, ) self._base = RigidPrimView( prim_paths_expr="/World/envs/.*/anymal/base", name="base_view", reset_xform_properties=False, track_contact_forces=track_contact_forces, prepare_contact_sensors=prepare_contact_sensors, ) def get_knee_transforms(self): return self._knees.get_world_poses() def is_knee_below_threshold(self, threshold, ground_heights=None): knee_pos, _ = self._knees.get_world_poses() knee_heights = knee_pos.view((-1, 4, 3))[:, :, 2] if ground_heights is not None: knee_heights -= ground_heights return ( (knee_heights[:, 0] < threshold) | (knee_heights[:, 1] < threshold) | (knee_heights[:, 2] < threshold) | (knee_heights[:, 3] < threshold) ) def is_base_below_threshold(self, threshold, ground_heights): base_pos, _ = self.get_world_poses() base_heights = base_pos[:, 2] base_heights -= ground_heights return base_heights[:] < threshold
3,433
Python
41.395061
98
0.678415
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/views/quadcopter_view.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.prims import RigidPrimView class QuadcopterView(ArticulationView): def __init__(self, prim_paths_expr: str, name: Optional[str] = "QuadcopterView") -> None: """[summary]""" super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False) self.rotors = RigidPrimView( prim_paths_expr=f"/World/envs/.*/Quadcopter/rotor[0-3]", name="rotors_view", reset_xform_properties=False )
2,121
Python
47.227272
117
0.759547
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/views/allegro_hand_view.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional import torch from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.prims import RigidPrimView class AllegroHandView(ArticulationView): def __init__( self, prim_paths_expr: str, name: Optional[str] = "AllegroHandView", ) -> None: super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False) self._actuated_dof_indices = list() @property def actuated_dof_indices(self): return self._actuated_dof_indices def initialize(self, physics_sim_view): super().initialize(physics_sim_view) self._actuated_dof_indices = [i for i in range(self.num_dof)]
2,275
Python
41.148147
98
0.74989
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/views/crazyflie_view.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.prims import RigidPrimView class CrazyflieView(ArticulationView): def __init__(self, prim_paths_expr: str, name: Optional[str] = "CrazyflieView") -> None: """[summary]""" super().__init__( prim_paths_expr=prim_paths_expr, name=name, ) self.physics_rotors = [ RigidPrimView(prim_paths_expr=f"/World/envs/.*/Crazyflie/m{i}_prop", name=f"m{i}_prop_view") for i in range(1, 5) ]
2,140
Python
42.693877
104
0.737383
NVIDIA-Omniverse/OmniIsaacGymEnvs/omniisaacgymenvs/robots/articulations/views/ingenuity_view.py
# Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from typing import Optional from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.prims import RigidPrimView class IngenuityView(ArticulationView): def __init__(self, prim_paths_expr: str, name: Optional[str] = "IngenuityView") -> None: """[summary]""" super().__init__(prim_paths_expr=prim_paths_expr, name=name, reset_xform_properties=False) self.physics_rotors = [ RigidPrimView( prim_paths_expr=f"/World/envs/.*/Ingenuity/rotor_physics_{i}", name=f"physics_rotor_{i}_view", reset_xform_properties=False, ) for i in range(2) ] self.visual_rotors = [ RigidPrimView( prim_paths_expr=f"/World/envs/.*/Ingenuity/rotor_visual_{i}", name=f"visual_rotor_{i}_view", reset_xform_properties=False, ) for i in range(2) ]
2,524
Python
42.534482
98
0.70206
NVIDIA-Omniverse/OmniIsaacGymEnvs/docs/release_notes.md
Release Notes ============= 2023.1.1a - March 14, 2024 -------------------------- Fixes ----- - Add workaround for nucleus hang issue on startup - Fix USD update flags being reset after creating new stage. This should fix the long hang when running the Humanoid environment with `headless=False`. Known Issues ------------ - A segmentation fault may occasionally occur at the end of a training run. This does not prevent the training from completing successfully. 2023.1.1 - December 12, 2023 ---------------------------- Additions --------- - Add support for viewport recording during training/inferencing using gym wrapper class `RecordVideo` - Add `enable_recording`, `recording_interval`, `recording_length`, and `recording_fps`, `recording_dir` arguments to config/command-line for video recording - Add `moviepy` as dependency for video recording - Add video tutorial for extension workflow, available at [docs/framework/extension_workflow.md](docs/framework/extension_workflow.md) - Add camera clipping for CartpoleCamera to avoid seeing other environments in the background Changes ------- - Use rl_device for sampling random policy (https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs/pull/51) - Add FPS printouts for random policy - Use absolute path for default checkpoint folder for consistency between Python and extension workflows - Change camera creation API in CartpoleCamera to use USD APIs instead of `rep.create` Fixes ----- - Fix missing device in warp kernel launch for Ant and Humanoid - Fix typo for velocity iteration (https://github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs/pull/111) - Clean up private variable access in task classes in favour of property getters - Clean up private variable access in extension.py in favour of setter methods - Unregister replicator in extension workflow on training completion to allow for restart 2023.1.0b - November 02, 2023 ----------------------------- Changes ------- - Update docker scripts to Isaac Sim docker image 2023.1.0-hotfix.1 - Use omniisaacgymenvs module root for app file parsing - Update FrankaDeformable physics dt for better training stability Fixes ----- - Fix CartpoleCamera num_observations value - Fix missing import in startup randomization for mass and density 2023.1.0a - October 20, 2023 ---------------------------- Fixes ----- - Fix extension loading error in camera app file 2023.1.0 - October 18, 2023 --------------------------- Additions --------- - Add support for Warp backend task implementation - Add Warp-based RL examples: Cartpole, Ant, Humanoid - Add new Factory environments for place and screw: FactoryTaskNutBoltPlace and FactoryTaskNutBoltScrew - Add new camera-based Cartpole example: CartpoleCamera - Add new deformable environment showing Franka picking up a deformable tube: FrankaDeformable - Add support for running OIGE as an extension in Isaac Sim - Add options to filter collisions between environments and specify global collision filter paths to `RLTask.set_to_scene()` - Add multinode training support - Add dockerfile with OIGE - Add option to select kit app file from command line argument `kit_app` - Add `rendering_dt` parameter to the task config file for setting rendering dt. Defaults to the same value as the physics dt. Changes ------- - `use_flatcache` flag has been renamed to `use_fabric` - Update hydra-core version to 1.3.2, omegaconf version to 2.3.0 - Update rlgames to version 1.6.1. - The `get_force_sensor_forces` API for articulations is now deprecated and replaced with `get_measured_joint_forces` - Remove unnecessary cloning of buffers in VecEnv classes - Only enable omni.replicator.isaac when domain randomization or cameras are enabled - The multi-threaded launch script `rlgames_train_mt.py` has been re-designed to support the extension workflow. This script can no longer be used to launch a training run from python. Please use `rlgames_train.py` instead. - Restructures for environments to support the new extension-based workflow - Add async workflow to factory pick environment to support extension-based workflow - Update docker scripts with cache directories Fixes ----- - Fix errors related to setting velocities to kinematic markers in Ingenuity and Quadcopter environments - Fix contact-related issues with quadruped assets - Fix errors in physics APIs when returning empty tensors - Fix orientation correctness issues when using some assets with omni.isaac.core. Additional orientations applied to accommodate for the error are no longer required (i.e. ShadowHand) - Updated the deprecated config name `seq_len` used with RNN networks to `seq_length` 2022.2.1 - March 16, 2023 ------------------------- Additions --------- - Add FactoryTaskNutBoltPick example - Add Ant and Humanoid SAC training examples - Add multi-GPU support for training - Add utility scripts for launching Isaac Sim docker with OIGE - Add support for livestream through the Omniverse Streaming Client Changes ------- - Change rigid body fixed_base option to make_kinematic, avoiding creation of unnecessary articulations - Update ShadowHand, Ingenuity, Quadcopter and Crazyflie marker objects to use kinematics - Update ShadowHand GPU buffer parameters - Disable PyTorch nvFuser for better performance - Enable viewport and replicator extensions dynamically to maintain order of extension startup - Separate app files for headless environments with rendering (requires Isaac Sim update) - Update rl-games to v1.6.0 Fixes ----- - Fix material property randomization at run-time, including friction and restitution (requires Isaac Sim update) - Fix a bug in contact reporting API where incorrect values were being reported (requires Isaac Sim update) - Enable render flag in Isaac Sim when enable_cameras is set to True - Add root pose and velocity reset to BallBalance environment 2.0.0 - December 15, 2022 ------------------------- Additions --------- - Update to Viewport 2.0 - Allow for runtime mass randomization on GPU pipeline - Add runtime mass randomization to ShadowHand environments - Introduce `disable_contact_processing` simulation parameter for faster contact processing - Use physics replication for cloning by default for faster load time Changes ------- - Update AnymalTerrain environment to use contact forces - Update Quadcopter example to apply local forces - Update training parameters for ShadowHandOpenAI_FF environment - Rename rlgames_play.py to rlgames_demo.py Fixes ----- - Remove fix_base option from articulation configs - Fix in_hand_manipulation random joint position sampling on reset - Fix mass and density randomization in MT training script - Fix actions/observations noise randomization in MT training script - Fix random seed when domain randomization is enabled - Check whether simulation is running before executing pre_physics_step logic 1.1.0 - August 22, 2022 ----------------------- Additions --------- - Additional examples: Anymal, AnymalTerrain, BallBalance, Crazyflie, FrankaCabinet, Ingenuity, Quadcopter - Add OpenAI variantions for Feed-Forward and LSTM networks for ShadowHand - Add domain randomization framework `using omni.replicator.isaac` - Add AnymalTerrain interactable demo - Automatically disable `omni.kit.window.viewport` and `omni.physx.flatcache` extensions in headless mode to improve start-up load time - Introduce `reset_xform_properties` flag for initializing Views of cloned environments to reduce load time - Add WandB support - Update RL-Games version to 1.5.2 Fixes ----- - Correctly sets simulation device for GPU simulation - Fix omni.client import order - Fix episode length reset condition for ShadowHand and AllegroHand 1.0.0 - June 03, 2022 ---------------------- - Initial release for RL examples with Isaac Sim - Examples provided: AllegroHand, Ant, Cartpole, Humanoid, ShadowHand
7,825
Markdown
40.850267
223
0.764089
NVIDIA-Omniverse/OmniIsaacGymEnvs/docs/examples/training_with_camera.md
## Reinforcement Learning with Vision in the Loop Some reinforcement learning tasks can benefit from having image data in the pipeline by collecting sensor data from cameras to use as observations. However, high fidelity rendering can be expensive when scaled up towards thousands of environments during training. Although Isaac Sim does not currently have the capability to scale towards thousands of environments, we are continually working on improvements to reach the goal. As a starting point, we are providing a simple example showcasing a proof-of-concept for reinforcement learning with vision in the loop. ### CartpoleCamera [cartpole_camera.py](../../omniisaacgymenvs/tasks/cartpole_camera.py) As an example showcasing the possiblity of reinforcmenet learning with vision in the loop, we provide a variation of the Cartpole task, which uses RGB image data as observations. This example can be launched with command line argument `task=CartpoleCamera`. Config files used for this task are: - **Task config**: [CartpoleCamera.yaml](../../omniisaacgymenvs/cfg/task/CartpoleCamera.yaml) - **rl_games training config**: [CartpoleCameraPPO.yaml](../../omniisaacgymenvs/cfg/train/CartpoleCameraPPO.yaml) ### Working with Cameras We have provided an individual app file `apps/omni.isaac.sim.python.gym.camera.kit`, designed specifically towards vision-based RL tasks. This app file provides necessary settings to enable multiple cameras to be rendered each frame. Additional settings are also applied to increase performance when rendering cameras across multiple environments. In addition, the following settings can be added to the app file to increase performance at a cost of accuracy. By setting these flags to `false`, data collected from the cameras may have a 1 to 2 frame delay. ``` app.renderer.waitIdle=false app.hydraEngine.waitIdle=false ``` We can also render in white-mode by adding the following line: ``` rtx.debugMaterialType=0 ``` ### Config Settings In order for rendering to occur during training, tasks using camera rendering must have the `enable_cameras` flag set to `True` in the task config file. By default, the `omni.isaac.sim.python.gym.camera.kit` app file will be used automatically when `enable_cameras` is set to `True`. This flag is located in the task config file, under the `sim` section. In addition, the `rendering_dt` parameter can be used to specify the rendering frequency desired. Similar to `dt` for physics simulation frequency, the `rendering_dt` specifies the amount of time in `s` between each rendering step. The `rendering_dt` should be larger or equal to the physics `dt`, and be a multiple of physics `dt`. Note that specifying the `controlFrequencyInv` flag will reduce the control frequency in terms of the physics simulation frequency. For example, assume control frequency is 30hz, physics simulation frequency is 120 hz, and rendering frequency is 10hz. In the task config file, we can set `dt: 1/120`, `controlFrequencyInv: 4`, such that control is applied every 4 physics steps, and `rendering_dt: 1/10`. In this case, render data will only be updated once every 12 physics steps. Note that both `dt` and `rendering_dt` parameters are under the `sim` section of the config file, while `controlFrequencyInv` is under the `env` section. ### Environment Setup To set up a task for vision-based RL, we will first need to add a camera to each environment in the scene and wrap it in a Replicator `render_product` to use the vectorized rendering API available in Replicator. This can be done with the following code in `set_up_scene`: ```python self.render_products = [] env_pos = self._env_pos.cpu() for i in range(self._num_envs): camera = self.rep.create.camera( position=(-4.2 + env_pos[i][0], env_pos[i][1], 3.0), look_at=(env_pos[i][0], env_pos[i][1], 2.55)) render_product = self.rep.create.render_product(camera, resolution=(self.camera_width, self.camera_height)) self.render_products.append(render_product) ``` Next, we need to initialize Replicator and the PytorchListener, which will be used to collect rendered data. ```python # start replicator to capture image data self.rep.orchestrator._orchestrator._is_started = True # initialize pytorch writer for vectorized collection self.pytorch_listener = self.PytorchListener() self.pytorch_writer = self.rep.WriterRegistry.get("PytorchWriter") self.pytorch_writer.initialize(listener=self.pytorch_listener, device="cuda") self.pytorch_writer.attach(self.render_products) ``` Then, we can simply collect rendered data from each environment using a single API call: ```python # retrieve RGB data from all render products images = self.pytorch_listener.get_rgb_data() ```
4,737
Markdown
58.974683
502
0.776019
NVIDIA-Omniverse/OmniIsaacGymEnvs/docs/examples/rl_examples.md
## Reinforcement Learning Examples We introduce the following reinforcement learning examples that are implemented using Isaac Sim's RL framework. Pre-trained checkpoints can be found on the Nucleus server. To set up localhost, please refer to the [Isaac Sim installation guide](https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_workstation.html). *Note: All commands should be executed from `omniisaacgymenvs/omniisaacgymenvs`.* - [Reinforcement Learning Examples](#reinforcement-learning-examples) - [Cartpole cartpole.py](#cartpole-cartpolepy) - [Ant ant.py](#ant-antpy) - [Humanoid humanoid.py](#humanoid-humanoidpy) - [Shadow Hand Object Manipulation shadow_hand.py](#shadow-hand-object-manipulation-shadow_handpy) - [OpenAI Variant](#openai-variant) - [LSTM Training Variant](#lstm-training-variant) - [Allegro Hand Object Manipulation allegro_hand.py](#allegro-hand-object-manipulation-allegro_handpy) - [ANYmal anymal.py](#anymal-anymalpy) - [Anymal Rough Terrain anymal_terrain.py](#anymal-rough-terrain-anymal_terrainpy) - [NASA Ingenuity Helicopter ingenuity.py](#nasa-ingenuity-helicopter-ingenuitypy) - [Quadcopter quadcopter.py](#quadcopter-quadcopterpy) - [Crazyflie crazyflie.py](#crazyflie-crazyfliepy) - [Ball Balance ball_balance.py](#ball-balance-ball_balancepy) - [Franka Cabinet franka_cabinet.py](#franka-cabinet-franka_cabinetpy) - [Franka Deformable franka_deformable.py](#franka-deformablepy) - [Factory: Fast Contact for Robotic Assembly](#factory-fast-contact-for-robotic-assembly) ### Cartpole [cartpole.py](../../omniisaacgymenvs/tasks/cartpole.py) Cartpole is a simple example that demonstrates getting and setting usage of DOF states using `ArticulationView` from `omni.isaac.core`. The goal of this task is to move a cart horizontally such that the pole, which is connected to the cart via a revolute joint, stays upright. Joint positions and joint velocities are retrieved using `get_joint_positions` and `get_joint_velocities` respectively, which are required in computing observations. Actions are applied onto the cartpoles via `set_joint_efforts`. Cartpoles are reset by using `set_joint_positions` and `set_joint_velocities`. Training can be launched with command line argument `task=Cartpole`. Training using the Warp backend can be launched with `task=Cartpole warp=True`. Running inference with pre-trained model can be launched with command line argument `task=Cartpole test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/cartpole.pth` Config files used for this task are: - **Task config**: [Cartpole.yaml](../../omniisaacgymenvs/cfg/task/Cartpole.yaml) - **rl_games training config**: [CartpolePPO.yaml](../../omniisaacgymenvs/cfg/train/CartpolePPO.yaml) #### CartpoleCamera [cartpole_camera.py](../../omniisaacgymenvs/tasks/cartpole_camera.py) A variation of the Cartpole task showcases the usage of RGB image data as observations. This example can be launched with command line argument `task=CartpoleCamera`. Note that to use camera data as observations, `enable_cameras` must be set to `True` in the task config file. In addition, the example must be run with the `omni.isaac.sim.python.gym.camera.kit` app file provided under `apps`, which applies necessary settings to enable camera training. By default, this app file will be used automatically when `enable_cameras` is set to `True`. Due to this limitation, this example is currently not available in the extension workflow. Config files used for this task are: - **Task config**: [CartpoleCamera.yaml](../../omniisaacgymenvs/cfg/task/CartpoleCamera.yaml) - **rl_games training config**: [CartpoleCameraPPO.yaml](../../omniisaacgymenvs/cfg/train/CartpoleCameraPPO.yaml) For more details on training with camera data, please visit [here](training_with_camera.md). <img src="https://user-images.githubusercontent.com/34286328/171454189-6afafbff-bb61-4aac-b518-24646007cb9f.gif" width="300" height="150"/> ### Ant [ant.py](../../omniisaacgymenvs/tasks/ant.py) Ant is an example of a simple locomotion task. The goal of this task is to train quadruped robots (ants) to run forward as fast as possible. This example inherets from [LocomotionTask](../../omniisaacgymenvs/tasks/shared/locomotion.py), which is a shared class between this example and the humanoid example; this simplifies implementations for both environemnts since they compute rewards, observations, and resets in a similar manner. This framework allows us to easily switch between robots used in the task. The Ant task includes more examples of utilizing `ArticulationView` from `omni.isaac.core`, which provides various functions to get and set both DOF states and articulation root states in a tensorized fashion across all of the actors in the environment. `get_world_poses`, `get_linear_velocities`, and `get_angular_velocities`, can be used to determine whether the ants have been moving towards the desired direction and whether they have fallen or flipped over. Actions are applied onto the ants via `set_joint_efforts`, which moves the ants by setting torques to the DOFs. Note that the previously used force sensors and `get_force_sensor_forces` API are now deprecated. Force sensors can now be retrieved directly using `get_measured_joint_forces` from `ArticulationView`. Training with PPO can be launched with command line argument `task=Ant`. Training with SAC with command line arguments `task=AntSAC train=AntSAC`. Training using the Warp backend can be launched with `task=Ant warp=True`. Running inference with pre-trained model can be launched with command line argument `task=Ant test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/ant.pth` Config files used for this task are: - **PPO task config**: [Ant.yaml](../../omniisaacgymenvs/cfg/task/Ant.yaml) - **rl_games PPO training config**: [AntPPO.yaml](../../omniisaacgymenvs/cfg/train/AntPPO.yaml) <img src="https://user-images.githubusercontent.com/34286328/171454182-0be1b830-bceb-4cfd-93fb-e1eb8871ec68.gif" width="300" height="150"/> ### Humanoid [humanoid.py](../../omniisaacgymenvs/tasks/humanoid.py) Humanoid is another environment that uses [LocomotionTask](../../omniisaacgymenvs/tasks/shared/locomotion.py). It is conceptually very similar to the Ant example, where the goal for the humanoid is to run forward as fast as possible. Training can be launched with command line argument `task=Humanoid`. Training with SAC with command line arguments `task=HumanoidSAC train=HumanoidSAC`. Training using the Warp backend can be launched with `task=Humanoid warp=True`. Running inference with pre-trained model can be launched with command line argument `task=Humanoid test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/humanoid.pth` Config files used for this task are: - **PPO task config**: [Humanoid.yaml](../../omniisaacgymenvs/cfg/task/Humanoid.yaml) - **rl_games PPO training config**: [HumanoidPPO.yaml](../../omniisaacgymenvs/cfg/train/HumanoidPPO.yaml) <img src="https://user-images.githubusercontent.com/34286328/171454193-e027885d-1510-4ef4-b838-06b37f70c1c7.gif" width="300" height="150"/> ### Shadow Hand Object Manipulation [shadow_hand.py](../../omniisaacgymenvs/tasks/shadow_hand.py) The Shadow Hand task is an example of a challenging dexterity manipulation task with complex contact dynamics. It resembles OpenAI's [Learning Dexterity](https://openai.com/blog/learning-dexterity/) project and [Robotics Shadow Hand](https://github.com/openai/gym/tree/v0.21.0/gym/envs/robotics) training environments. The goal of this task is to orient the object in the robot hand to match a random target orientation, which is visually displayed by a goal object in the scene. This example inherets from [InHandManipulationTask](../../omniisaacgymenvs/tasks/shared/in_hand_manipulation.py), which is a shared class between this example and the Allegro Hand example. The idea of this shared [InHandManipulationTask](../../omniisaacgymenvs/tasks/shared/in_hand_manipulation.py) class is similar to that of the [LocomotionTask](../../omniisaacgymenvs/tasks/shared/locomotion.py); since the Shadow Hand example and the Allegro Hand example only differ by the robot hand used in the task, using this shared class simplifies implementation across the two. In this example, motion of the hand is controlled using position targets with `set_joint_position_targets`. The object and the goal object are reset using `set_world_poses`; their states are retrieved via `get_world_poses` for computing observations. It is worth noting that the Shadow Hand model in this example also demonstrates the use of tendons, which are imported using the `omni.isaac.mjcf` extension. Training can be launched with command line argument `task=ShadowHand`. Training with Domain Randomization can be launched with command line argument `task.domain_randomization.randomize=True`. For best training results with DR, use `num_envs=16384`. Running inference with pre-trained model can be launched with command line argument `task=ShadowHand test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/shadow_hand.pth` Config files used for this task are: - **Task config**: [ShadowHand.yaml](../../omniisaacgymenvs/cfg/task/ShadowHand.yaml) - **rl_games training config**: [ShadowHandPPO.yaml](../../omniisaacgymenvs/cfg/train/ShadowHandPPO.yaml) #### OpenAI Variant In addition to the basic version of this task, there is an additional variant matching OpenAI's [Learning Dexterity](https://openai.com/blog/learning-dexterity/) project. This variant uses the **openai** observations in the policy network, but asymmetric observations of the **full_state** in the value network. This can be launched with command line argument `task=ShadowHandOpenAI_FF`. Running inference with pre-trained model can be launched with command line argument `task=ShadowHandOpenAI_FF test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/shadow_hand_openai_ff.pth` Config files used for this are: - **Task config**: [ShadowHandOpenAI_FF.yaml](../../omniisaacgymenvs/cfg/task/ShadowHandOpenAI_FF.yaml) - **rl_games training config**: [ShadowHandOpenAI_FFPPO.yaml](../../omniisaacgymenvs/cfg/train/ShadowHandOpenAI_FFPPO.yaml). #### LSTM Training Variant This variant uses LSTM policy and value networks instead of feed forward networks, and also asymmetric LSTM critic designed for the OpenAI variant of the task. This can be launched with command line argument `task=ShadowHandOpenAI_LSTM`. Running inference with pre-trained model can be launched with command line argument `task=ShadowHandOpenAI_LSTM test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/shadow_hand_openai_lstm.pth` Config files used for this are: - **Task config**: [ShadowHandOpenAI_LSTM.yaml](../../omniisaacgymenvs/cfg/task/ShadowHandOpenAI_LSTM.yaml) - **rl_games training config**: [ShadowHandOpenAI_LSTMPPO.yaml](../../omniisaacgymenvs/cfg/train/ShadowHandOpenAI_LSTMPPO.yaml). <img src="https://user-images.githubusercontent.com/34286328/171454160-8cb6739d-162a-4c84-922d-cda04382633f.gif" width="300" height="150"/> ### Allegro Hand Object Manipulation [allegro_hand.py](../../omniisaacgymenvs/tasks/allegro_hand.py) This example performs the same object orientation task as the Shadow Hand example, but using the Allegro hand instead of the Shadow hand. Training can be launched with command line argument `task=AllegroHand`. Running inference with pre-trained model can be launched with command line argument `task=AllegroHand test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/allegro_hand.pth` Config files used for this task are: - **Task config**: [AllegroHand.yaml](../../omniisaacgymenvs/cfg/task/Allegro.yaml) - **rl_games training config**: [AllegroHandPPO.yaml](../../omniisaacgymenvs/cfg/train/AllegroHandPPO.yaml) <img src="https://user-images.githubusercontent.com/34286328/171454176-ce08f6d0-3087-4ecc-9273-7d30d8f73f6d.gif" width="300" height="150"/> ### ANYmal [anymal.py](../../omniisaacgymenvs/tasks/anymal.py) This example trains a model of the ANYmal quadruped robot from ANYbotics to follow randomly chosen x, y, and yaw target velocities. Training can be launched with command line argument `task=Anymal`. Running inference with pre-trained model can be launched with command line argument `task=Anymal test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/anymal.pth` Config files used for this task are: - **Task config**: [Anymal.yaml](../../omniisaacgymenvs/cfg/task/Anymal.yaml) - **rl_games training config**: [AnymalPPO.yaml](../../omniisaacgymenvs/cfg/train/AnymalPPO.yaml) <img src="https://user-images.githubusercontent.com/34286328/184168200-152567a8-3354-4947-9ae0-9443a56fee4c.gif" width="300" height="150"/> ### Anymal Rough Terrain [anymal_terrain.py](../../omniisaacgymenvs/tasks/anymal_terrain.py) A more complex version of the above Anymal environment that supports traversing various forms of rough terrain. Training can be launched with command line argument `task=AnymalTerrain`. Running inference with pre-trained model can be launched with command line argument `task=AnymalTerrain test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/anymal_terrain.pth` - **Task config**: [AnymalTerrain.yaml](../../omniisaacgymenvs/cfg/task/AnymalTerrain.yaml) - **rl_games training config**: [AnymalTerrainPPO.yaml](../../omniisaacgymenvs/cfg/train/AnymalTerrainPPO.yaml) **Note** during test time use the last weights generated, rather than the usual best weights. Due to curriculum training, the reward goes down as the task gets more challenging, so the best weights do not typically correspond to the best outcome. **Note** if you use the ANYmal rough terrain environment in your work, please ensure you cite the following work: ``` @misc{rudin2021learning, title={Learning to Walk in Minutes Using Massively Parallel Deep Reinforcement Learning}, author={Nikita Rudin and David Hoeller and Philipp Reist and Marco Hutter}, year={2021}, journal = {arXiv preprint arXiv:2109.11978} ``` **Note** The OmniIsaacGymEnvs implementation slightly differs from the implementation used in the paper above, which also uses a different RL library and PPO implementation. The original implementation is made available [here](https://github.com/leggedrobotics/legged_gym). Results reported in the Isaac Gym technical paper are based on that repository, not this one. <img src="https://user-images.githubusercontent.com/34286328/184170040-3f76f761-e748-452e-b8c8-3cc1c7c8cb98.gif" width="300" height="150"/> ### NASA Ingenuity Helicopter [ingenuity.py](../../omniisaacgymenvs/tasks/ingenuity.py) This example trains a simplified model of NASA's Ingenuity helicopter to navigate to a moving target. It showcases the use of velocity tensors and applying force vectors to rigid bodies. Note that we are applying force directly to the chassis, rather than simulating aerodynamics. This example also demonstrates using different values for gravitational forces. Ingenuity Helicopter visual 3D Model courtesy of NASA: https://mars.nasa.gov/resources/25043/mars-ingenuity-helicopter-3d-model/. Training can be launched with command line argument `task=Ingenuity`. Running inference with pre-trained model can be launched with command line argument `task=Ingenuity test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/ingenuity.pth` Config files used for this task are: - **Task config**: [Ingenuity.yaml](../../omniisaacgymenvs/cfg/task/Ingenuity.yaml) - **rl_games training config**: [IngenuityPPO.yaml](../../omniisaacgymenvs/cfg/train/IngenuityPPO.yaml) <img src="https://user-images.githubusercontent.com/34286328/184176312-df7d2727-f043-46e3-b537-48a583d321b9.gif" width="300" height="150"/> ### Quadcopter [quadcopter.py](../../omniisaacgymenvs/tasks/quadcopter.py) This example trains a very simple quadcopter model to reach and hover near a fixed position. Lift is achieved by applying thrust forces to the "rotor" bodies, which are modeled as flat cylinders. In addition to thrust, the pitch and roll of each rotor is controlled using DOF position targets. Training can be launched with command line argument `task=Quadcopter`. Running inference with pre-trained model can be launched with command line argument `task=Quadcopter test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/quadcopter.pth` Config files used for this task are: - **Task config**: [Quadcopter.yaml](../../omniisaacgymenvs/cfg/task/Quadcopter.yaml) - **rl_games training config**: [QuadcopterPPO.yaml](../../omniisaacgymenvs/cfg/train/QuadcopterPPO.yaml) <img src="https://user-images.githubusercontent.com/34286328/184178817-9c4b6b3c-c8a2-41fb-94be-cfc8ece51d5d.gif" width="300" height="150"/> ### Crazyflie [crazyflie.py](../../omniisaacgymenvs/tasks/crazyflie.py) This example trains the Crazyflie drone model to hover near a fixed position. It is achieved by applying thrust forces to the four rotors. Training can be launched with command line argument `task=Crazyflie`. Running inference with pre-trained model can be launched with command line argument `task=Crazyflie test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/crazyflie.pth` Config files used for this task are: - **Task config**: [Crazyflie.yaml](../../omniisaacgymenvs/cfg/task/Crazyflie.yaml) - **rl_games training config**: [CrazyfliePPO.yaml](../../omniisaacgymenvs/cfg/train/CrazyfliePPO.yaml) <img src="https://user-images.githubusercontent.com/6352136/185715165-b430a0c7-948b-4dce-b3bb-7832be714c37.gif" width="300" height="150"/> ### Ball Balance [ball_balance.py](../../omniisaacgymenvs/tasks/ball_balance.py) This example trains balancing tables to balance a ball on the table top. This is a great example to showcase the use of force and torque sensors, as well as DOF states for the table and root states for the ball. In this example, the three-legged table has a force sensor attached to each leg. We use the force sensor APIs to collect force and torque data on the legs, which guide position target outputs produced by the policy. Training can be launched with command line argument `task=BallBalance`. Running inference with pre-trained model can be launched with command line argument `task=BallBalance test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/ball_balance.pth` Config files used for this task are: - **Task config**: [BallBalance.yaml](../../omniisaacgymenvs/cfg/task/BallBalance.yaml) - **rl_games training config**: [BallBalancePPO.yaml](../../omniisaacgymenvs/cfg/train/BallBalancePPO.yaml) <img src="https://user-images.githubusercontent.com/34286328/184172037-cdad9ee8-f705-466f-bbde-3caa6c7dea37.gif" width="300" height="150"/> ### Franka Cabinet [franka_cabinet.py](../../omniisaacgymenvs/tasks/franka_cabinet.py) This Franka example demonstrates interaction between Franka arm and cabinet, as well as setting states of objects inside the drawer. It also showcases control of the Franka arm using position targets. In this example, we use DOF state tensors to retrieve the state of the Franka arm, as well as the state of the drawer on the cabinet. Actions are applied as position targets to the Franka arm DOFs. Training can be launched with command line argument `task=FrankaCabinet`. Running inference with pre-trained model can be launched with command line argument `task=FrankaCabinet test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/franka_cabinet.pth` Config files used for this task are: - **Task config**: [FrankaCabinet.yaml](../../omniisaacgymenvs/cfg/task/FrankaCabinet.yaml) - **rl_games training config**: [FrankaCabinetPPO.yaml](../../omniisaacgymenvs/cfg/train/FrankaCabinetPPO.yaml) <img src="https://user-images.githubusercontent.com/34286328/184174894-03767aa0-936c-4bfe-bbe9-a6865f539bb4.gif" width="300" height="150"/> ### Franka Deformable [franka_deformable.py](../../omniisaacgymenvs/tasks/franka_deformable.py) This Franka example demonstrates interaction between Franka arm and a deformable tube. It demonstrates the manipulation of deformable objects, using nodal positions and velocities of the simulation mesh as observations. Training can be launched with command line argument `task=FrankaDeformable`. Running inference with pre-trained model can be launched with command line argument `task=FrankaDeformable test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/franka_deformable.pth` Config files used for this task are: - **Task config**: [FrankaDeformable.yaml](../../omniisaacgymenvs/cfg/task/FrankaDeformable.yaml) - **rl_games training config**: [FrankaCabinetFrankaDeformable.yaml](../../omniisaacgymenvs/cfg/train/FrankaDeformablePPO.yaml) ### Factory: Fast Contact for Robotic Assembly We provide a set of Factory example tasks, [**FactoryTaskNutBoltPick**](../../omniisaacgymenvs/tasks/factory/factory_task_nut_bolt_pick.py), [**FactoryTaskNutBoltPlace**](../../omniisaacgymenvs/tasks/factory/factory_task_nut_bolt_place.py), and [**FactoryTaskNutBoltScrew**](../../omniisaacgymenvs/tasks/factory/factory_task_nut_bolt_screw.py), `FactoryTaskNutBoltPick` can be executed with `python train.py task=FactoryTaskNutBoltPick`. This task trains policy for the Pick task, a simplified version of the corresponding task in the Factory paper. The policy may take ~1 hour to achieve high success rates on a modern GPU. - The general configuration file for the above task is [FactoryTaskNutBoltPick.yaml](../../omniisaacgymenvs/cfg/task/FactoryTaskNutBoltPick.yaml). - The training configuration file for the above task is [FactoryTaskNutBoltPickPPO.yaml](../../omniisaacgymenvs/cfg/train/FactoryTaskNutBoltPickPPO.yaml). Running inference with pre-trained model can be launched with command line argument `task=FactoryTaskNutBoltPick test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/factory_task_nut_bolt_pick.pth` `FactoryTaskNutBoltPlace` can be executed with `python train.py task=FactoryTaskNutBoltPlace`. This task trains policy for the Place task. - The general configuration file for the above task is [FactoryTaskNutBoltPlace.yaml](../../omniisaacgymenvs/cfg/task/FactoryTaskNutBoltPlace.yaml). - The training configuration file for the above task is [FactoryTaskNutBoltPlacePPO.yaml](../../omniisaacgymenvs/cfg/train/FactoryTaskNutBoltPlacePPO.yaml). Running inference with pre-trained model can be launched with command line argument `task=FactoryTaskNutBoltPlace test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/factory_task_nut_bolt_place.pth` `FactoryTaskNutBoltScrew` can be executed with `python train.py task=FactoryTaskNutBoltScrew`. This task trains policy for the Screw task. - The general configuration file for the above task is [FactoryTaskNutBoltScrew.yaml](../../omniisaacgymenvs/cfg/task/FactoryTaskNutBoltScrew.yaml). - The training configuration file for the above task is [FactoryTaskNutBoltScrewPPO.yaml](../../omniisaacgymenvs/cfg/train/FactoryTaskNutBoltScrewPPO.yaml). Running inference with pre-trained model can be launched with command line argument `task=FactoryTaskNutBoltScrew test=True checkpoint=omniverse://localhost/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Samples/OmniIsaacGymEnvs/Checkpoints/factory_task_nut_bolt_screw.pth` If you use the Factory simulation methods (e.g., SDF collisions, contact reduction) or Factory learning tools (e.g., assets, environments, or controllers) in your work, please cite the following paper: ``` @inproceedings{ narang2022factory, author = {Yashraj Narang and Kier Storey and Iretiayo Akinola and Miles Macklin and Philipp Reist and Lukasz Wawrzyniak and Yunrong Guo and Adam Moravanszky and Gavriel State and Michelle Lu and Ankur Handa and Dieter Fox}, title = {Factory: Fast contact for robotic assembly}, booktitle = {Robotics: Science and Systems}, year = {2022} } ``` Also note that our original formulations of SDF collisions and contact reduction were developed by [Macklin, et al.](https://dl.acm.org/doi/abs/10.1145/3384538) and [Moravanszky and Terdiman](https://scholar.google.com/scholar?q=Game+Programming+Gems+4%2C+chapter+Fast+Contact+Reduction+for+Dynamics+Simulation), respectively. <img src="https://user-images.githubusercontent.com/6352136/205978286-fa2ae714-a3cb-4acd-9f5f-a467338a8bb3.gif"/>
25,398
Markdown
64.46134
377
0.787188
NVIDIA-Omniverse/OmniIsaacGymEnvs/docs/examples/transfering_policies_from_isaac_gym.md
## Transfering Policies from Isaac Gym Preview Releases This section delineates some of the differences between the standalone [Isaac Gym Preview Releases](https://developer.nvidia.com/isaac-gym) and Isaac Sim reinforcement learning extensions, in hopes of facilitating the process of transferring policies trained in the standalone preview releases to Isaac Sim. ### Isaac Sim RL Extensions Unlike the monolithic standalone Isaac Gym Preview Releases, Omniverse is a highly modular system, with functionality split between various [Extensions](https://docs.omniverse.nvidia.com/extensions/latest/index.html). The APIs used by typical robotics RL systems are split between a handful of extensions in Isaac Sim. These include `omni.isaac.core`, which provides tensorized access to physics simulation state as well as a task management framework, the `omni.isaac.cloner` extension for creating many copies of your environments, and the `omni.isaac.gym` extension for interfacing with external RL training libraries. For naming clarity, we'll refer collectively to the extensions used for RL within Isaac Sim as the **Isaac Sim RL extensions**, in contrast with the older **Isaac Gym Preview Releases**. ### Quaternion Convention The Isaac Sim RL extensions use various classes and methods in `omni.isaac.core`, which adopts `wxyz` as the quaternion convention. However, the quaternion convention used in Isaac Gym Preview Releases is `xyzw`. Therefore, if a policy trained in one of the Isaac Gym Preview Releases takes in quaternions as part of its observations, remember to switch all quaternions to use the `xyzw` convention in the observation buffer `self.obs_buf`. Similarly, please ensure all quaternions are in `wxyz` before passing them in any of the utility functions in `omni.isaac.core`. ### Assets Isaac Sim provides [URDF](https://docs.omniverse.nvidia.com/isaacsim/latest/advanced_tutorials/tutorial_advanced_import_urdf.html) and [MJCF](https://docs.omniverse.nvidia.com/isaacsim/latest/advanced_tutorials/tutorial_advanced_import_mjcf.html) importers for translating URDF and MJCF assets into USD format. Any robot or object assets must be in .usd, .usda, or .usdc format for Isaac Sim and Omniverse. For more details on working with USD, please see https://docs.omniverse.nvidia.com/isaacsim/latest/reference_glossary.html#usd. Importer tools are also available for other common geometry file formats, such as .obj, .fbx, and more. Please see [Asset Importer](https://docs.omniverse.nvidia.com/extensions/latest/ext_asset-importer.html) for more details. ### Joint Order Isaac Sim's `ArticulationView` in `omni.isaac.core` assumes a breadth-first ordering for the joints in a given kinematic tree. Specifically, for the following kinematic tree, the method `ArticulationView.get_joint_positions` returns a tensor of shape `(number of articulations in the view, number of joints in the articulation)`. Along the second dimension of this tensor, the values represent the articulation's joint positions in the following order: `[Joint 1, Joint 2, Joint 4, Joint 3, Joint 5]`. On the other hand, the Isaac Gym Preview Releases assume a depth-first ordering for the joints in the kinematic tree; In the example below, the joint orders would be the following: `[Joint 1, Joint 2, Joint 3, Joint 4, Joint 5]`. <img src="./media/KinematicTree.png" height="300"/> With this in mind, it is important to change the joint order to depth-first in the observation buffer before feeding it into an existing policy trained in one of the Isaac Gym Preview Releases. Similarly, you would also need to change the joint order in the output (the action buffer) of the Isaac Gym Preview Release trained policy to breadth-first before applying joint actions to articulations via methods in `ArticulationView`. ### Physics Parameters One factor that could dictate the success of policy transfer from Isaac Gym Preview Releases to Isaac Sim is to ensure the physics parameters used in both simulations are identical or very similar. In general, the `sim` parameters specified in the task configuration `yaml` file overwrite the corresponding parameters in the USD asset. However, there are additional parameters in the USD asset that are not included in the task configuration `yaml` file. These additional parameters may sometimes impact the performance of Isaac Gym Preview Release trained policies and hence need modifications in the USD asset itself to match the values set in Isaac Gym Preview Releases. For instance, the following parameters in the `RigidBodyAPI` could be modified in the USD asset to yield better policy transfer performance: | RigidBodyAPI Parameter | Default Value in Isaac Sim | Default Value in Isaac Gym Preview Releases | |:----------------------:|:--------------------------:|:--------------------------:| | Linear Damping | 0.00 | 0.00 | | Angular Damping | 0.05 | 0.00 | | Max Linear Velocity | inf | 1000 | | Max Angular Velocity | 5729.58008 (deg/s) | 64 (rad/s) | | Max Contact Impulse | inf | 1e32 | <img src="./media/RigidBodyAPI.png" width="500"/> Parameters in the `JointAPI` as well as the `DriveAPI` could be altered as well. Note that the Isaac Sim UI assumes the unit of angle to be degrees. It is particularly worth noting that the `Damping` and `Stiffness` paramters in the `DriveAPI` have the unit of `1/deg` in the Isaac Sim UI but `1/rad` in Isaac Gym Preview Releases. | Joint Parameter | Default Value in Isaac Sim | Default Value in Isaac Gym Preview Releases | |:----------------------:|:--------------------------:|:--------------------------:| | Maximum Joint Velocity | 1000000.0 (deg) | 100.0 (rad) | <img src="./media/JointAPI.png" width="500"/> ### Differences in APIs APIs for accessing physics states in Isaac Sim require the creation of an ArticulationView or RigidPrimView object. Multiple view objects can be initialized for different articulations or bodies in the scene by defining a regex expression that matches the paths of the desired objects. This approach eliminates the need of retrieving body handles to slice states for specific bodies in the scene. We have also removed `acquire` and `refresh` APIs in Isaac Sim. Physics states can be directly applied or retrieved by using `set`/`get` APIs defined for the views. New APIs provided in Isaac Sim no longer require explicit wrapping and un-wrapping of underlying buffers. APIs can now work with tensors directly for reading and writing data. Most APIs in Isaac Sim also provide the option to specify an `indices` parameter, which can be used when reading or writing data for a subset of environments. Note that when setting states with the `indices` parameter, the shape of the states buffer should match with the dimension of the `indices` list. Note some naming differences between APIs in Isaac Gym Preview Release and Isaac Sim. Most `dof` related APIs have been named to `joint` in Isaac Sim. `root_states` is now separated into different APIs for `world_poses` and `velocities`. Similary, `dof_states` are retrieved individually in Isaac Sim as `joint_positions` and `joint_velocities`. APIs in Isaac Sim also no longer follow the explicit `_tensors` or `_tensor_indexed` suffixes in naming. Indexed versions of APIs now happen implicitly through the optional `indices` parameter. ### Task Configuration Files There are a few modifications that need to be made to an existing Isaac Gym Preview Release task `yaml` file in order for it to be compatible with the Isaac Sim RL extensions. #### Frequencies of Physics Simulation and RL Policy The way in which physics simulation frequency and RL policy frequency are specified is different between Isaac Gym Preview Releases and Isaac Sim, dictated by the following three parameters: `dt`, `substeps`, and `controlFrequencyInv`. - `dt`: The simulation time difference between each simulation step. - `substeps`: The number of physics steps within one simulation step. *i.e.* if `dt: 1/60` and `substeps: 4`, physics is simulated at 240 hz. - `controlFrequencyInv`: The control decimation of the RL policy, which is the number of simulation steps between RL actions. *i.e.* if `dt: 1/60` and `controlFrequencyInv: 2`, RL policy is running at 30 hz. In Isaac Gym Preview Releases, all three of the above parameters are used to specify the frequencies of physics simulation and RL policy. However, Isaac Sim only uses `controlFrequencyInv` and `dt` as `substeps` is always fixed at `1`. Note that despite only using two parameters, Isaac Sim can still achieve the same substeps definition as Isaac Gym. For example, if in an Isaac Gym Preview Release policy, we set `substeps: 2`, `dt: 1/60` and `controlFrequencyInv: 1`, we can achieve the equivalent in Isaac Sim by setting `controlFrequencyInv: 2` and `dt: 1/120`. In the Isaac Sim RL extensions, `dt` is specified in the task configuration `yaml` file under `sim`, whereas `controlFrequencyInv` is a parameter under `env`. #### Physx Parameters Parameters under `physx` in the task configuration `yaml` file remain mostly unchanged. In Isaac Gym Preview Releases, `use_gpu` is frequently set to `${contains:"cuda",${....sim_device}}`. For Isaac Sim, please ensure this is changed to `${eq:${....sim_device},"gpu"}`. In Isaac Gym Preview Releases, GPU buffer sizes are specified using the following two parameters: `default_buffer_size_multiplier` and `max_gpu_contact_pairs`. With the Isaac Sim RL extensions, these two parameters are no longer used; instead, the various GPU buffer sizes can be set explicitly. For instance, in the [Humanoid task configuration file](../omniisaacgymenvs/cfg/task/Humanoid.yaml), GPU buffer sizes are specified as follows: ```yaml gpu_max_rigid_contact_count: 524288 gpu_max_rigid_patch_count: 81920 gpu_found_lost_pairs_capacity: 8192 gpu_found_lost_aggregate_pairs_capacity: 262144 gpu_total_aggregate_pairs_capacity: 8192 gpu_max_soft_body_contacts: 1048576 gpu_max_particle_contacts: 1048576 gpu_heap_capacity: 67108864 gpu_temp_buffer_capacity: 16777216 gpu_max_num_partitions: 8 ``` Please refer to the [Troubleshooting](./troubleshoot.md#simulation) documentation should you encounter errors related to GPU buffer sizes. #### Articulation Parameters The articulation parameters of each actor can now be individually specified tn the Isaac Sim task configuration `yaml` file. The following is an example template for setting these parameters: ```yaml ARTICULATION_NAME: # -1 to use default values override_usd_defaults: False fixed_base: False enable_self_collisions: True enable_gyroscopic_forces: True # per-actor solver_position_iteration_count: 4 solver_velocity_iteration_count: 0 sleep_threshold: 0.005 stabilization_threshold: 0.001 # per-body density: -1 max_depenetration_velocity: 10.0 ``` These articulation parameters can be parsed using the `parse_actor_config` method in the [SimConfig](../omniisaacgymenvs/utils/config_utils/sim_config.py) class, which can then be applied to a prim in simulation via the `apply_articulation_settings` method. A concrete example of this is the following code snippet from the [HumanoidTask](../omniisaacgymenvs/tasks/humanoid.py#L75): ```python self._sim_config.apply_articulation_settings("Humanoid", get_prim_at_path(humanoid.prim_path), self._sim_config.parse_actor_config("Humanoid")) ``` #### Additional Simulation Parameters - `use_fabric`: Setting this paramter to `True` enables [PhysX Fabric](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_physics.html#flatcache), which offers a significant increase in simulation speed. However, this parameter must be set to `False` if soft-body simulation is required because `PhysX Fabric` curently only supports rigid-body simulation. - `enable_scene_query_support`: Setting this paramter to `True` allows the user to interact with prims in the scene. Keeping this setting to `False` during training improves simulation speed. Note that this parameter is always set to `True` if in test/inference mode to enable user interaction with trained models. ### Training Configuration Files The Omniverse Isaac Gym RL Environments are trained using a third-party highly-optimized RL library, [rl_games](https://github.com/Denys88/rl_games), which is also used to train the Isaac Gym Preview Release examples in [IsaacGymEnvs](https://github.com/NVIDIA-Omniverse/IsaacGymEnvs). Therefore, the rl_games training configuration `yaml` files in Isaac Sim are compatible with those from IsaacGymEnvs. However, please add the following lines under `config` in the training configuration `yaml` files (*i.e.* line 41-42 in [HumanoidPPO.yaml](../omniisaacgymenvs/cfg/train/HumanoidPPO.yaml#L41)) to ensure RL training runs on the intended device. ```yaml device: ${....rl_device} device_name: ${....rl_device} ```
13,250
Markdown
55.387234
252
0.749585
NVIDIA-Omniverse/OmniIsaacGymEnvs/docs/framework/domain_randomization.md
Domain Randomization ==================== Overview -------- We sometimes need our reinforcement learning agents to be robust to different physics than they are trained with, such as when attempting a sim2real policy transfer. Using domain randomization (DR), we repeatedly randomize the simulation dynamics during training in order to learn a good policy under a wide range of physical parameters. OmniverseIsaacGymEnvs supports "on the fly" domain randomization, allowing dynamics to be changed without requiring reloading of assets. This allows us to efficiently apply domain randomizations without common overheads like re-parsing asset files. The OmniverseIsaacGymEnvs DR framework utilizes the `omni.replicator.isaac` extension in its backend to perform "on the fly" randomization. Users can add domain randomization by either directly using methods provided in `omni.replicator.isaac` in python, or specifying DR settings in the task configuration `yaml` file. The following sections will focus on setting up DR using the `yaml` file interface. For more detailed documentations regarding methods provided in the `omni.replicator.isaac` extension, please visit [here](https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.replicator.isaac/docs/index.html). Domain Randomization Options ------------------------------- We will first explain what can be randomized in the scene and the sampling distributions. There are five main parameter groups that support randomization. They are: - `observations`: Add noise directly to the agent observations - `actions`: Add noise directly to the agent actions - `simulation`: Add noise to physical parameters defined for the entire scene, such as `gravity` - `rigid_prim_views`: Add noise to properties belonging to rigid prims, such as `material_properties`. - `articulation_views`: Add noise to properties belonging to articulations, such as `stiffness` of joints. For each parameter you wish to randomize, you can specify two ways that determine when the randomization is applied: - `on_reset`: Adds correlated noise to a parameter of an environment when that environment gets reset. This correlated noise will remain with an environment until that environemnt gets reset again, which will then set a new correlated noise. To trigger `on_reset`, the indices for the environemnts that need to be reset must be passed in to `omni.replicator.isaac.physics_view.step_randomization(reset_inds)`. - `on_interval`: Adds uncorrelated noise to a parameter at a frequency specified by `frequency_interval`. If a parameter also has `on_reset` randomization, the `on_interval` noise is combined with the noise applied at `on_reset`. - `on_startup`: Applies randomization once prior to the start of the simulation. Only available to rigid prim scale, mass, density and articulation scale parameters. For `on_reset`, `on_interval`, and `on_startup`, you can specify the following settings: - `distribution`: The distribution to generate a sample `x` from. The available distributions are listed below. Note that parameters `a` and `b` are defined by the `distribution_parameters` setting. - `uniform`: `x ~ unif(a, b)` - `loguniform`: `x ~ exp(unif(log(a), log(b)))` - `gaussian`: `x ~ normal(a, b)` - `distribution_parameters`: The parameters to the distribution. - For observations and actions, this setting is specified as a tuple `[a, b]` of real values. - For simulation and view parameters, this setting is specified as a nested tuple in the form of `[[a_1, a_2, ..., a_n], [[b_1, b_2, ..., b_n]]`, where the `n` is the dimension of the parameter (*i.e.* `n` is 3 for position). It can also be specified as a tuple in the form of `[a, b]`, which will be broadcasted to the correct dimensions. - For `uniform` and `loguniform` distributions, `a` and `b` are the lower and upper bounds. - For `gaussian`, `a` is the distribution mean and `b` is the variance. - `operation`: Defines how the generated sample `x` will be applied to the original simulation parameter. The options are `additive`, `scaling`, `direct`. - `additive`:, add the sample to the original value. - `scaling`: multiply the original value by the sample. - `direct`: directly sets the sample as the parameter value. - `frequency_interval`: Specifies the number of steps to apply randomization. - Only used with `on_interval`. - Steps of each environemnt are incremented with each `omni.replicator.isaac.physics_view.step_randomization(reset_inds)` call and reset if the environment index is in `reset_inds`. - `num_buckets`: Only used for `material_properties` randomization - Physx only allows 64000 unique physics materials in the scene at once. If more than 64000 materials are needed, increase `num_buckets` to allow materials to be shared between prims. YAML Interface -------------- Now that we know what options are available for domain randomization, let's put it all together in the YAML config. In your `omniverseisaacgymenvs/cfg/task` yaml file, you can specify your domain randomization parameters under the `domain_randomization` key. First, we turn on domain randomization by setting `randomize` to `True`: ```yaml domain_randomization: randomize: True randomization_params: ... ``` This can also be set as a command line argument at launch time with `task.domain_randomization.randomize=True`. Next, we will define our parameters under the `randomization_params` keys. Here you can see how we used the previous settings to define some randomization parameters for a ShadowHand cube manipulation task: ```yaml randomization_params: randomization_params: observations: on_reset: operation: "additive" distribution: "gaussian" distribution_parameters: [0, .0001] on_interval: frequency_interval: 1 operation: "additive" distribution: "gaussian" distribution_parameters: [0, .002] actions: on_reset: operation: "additive" distribution: "gaussian" distribution_parameters: [0, 0.015] on_interval: frequency_interval: 1 operation: "additive" distribution: "gaussian" distribution_parameters: [0., 0.05] simulation: gravity: on_reset: operation: "additive" distribution: "gaussian" distribution_parameters: [[0.0, 0.0, 0.0], [0.0, 0.0, 0.4]] rigid_prim_views: object_view: material_properties: on_reset: num_buckets: 250 operation: "scaling" distribution: "uniform" distribution_parameters: [[0.7, 1, 1], [1.3, 1, 1]] articulation_views: shadow_hand_view: stiffness: on_reset: operation: "scaling" distribution: "uniform" distribution_parameters: [0.75, 1.5] ``` Note how we structured `rigid_prim_views` and `articulation_views`. When creating a `RigidPrimView` or `ArticulationView` in the task python file, you have the option to pass in `name` as an argument. **To use domain randomization, the name of the `RigidPrimView` or `ArticulationView` must match the name provided in the randomization `yaml` file.** In the example above, `object_view` is the name of a `RigidPrimView` and `shadow_hand_view` is the name of the `ArticulationView`. The exact parameters that can be randomized are listed below: **simulation**: - gravity (dim=3): The gravity vector of the entire scene. **rigid\_prim\_views**: - position (dim=3): The position of the rigid prim. In meters. - orientation (dim=3): The orientation of the rigid prim, specified with euler angles. In radians. - linear_velocity (dim=3): The linear velocity of the rigid prim. In m/s. **CPU pipeline only** - angular_velocity (dim=3): The angular velocity of the rigid prim. In rad/s. **CPU pipeline only** - velocity (dim=6): The linear + angular velocity of the rigid prim. - force (dim=3): Apply a force to the rigid prim. In N. - mass (dim=1): Mass of the rigid prim. In kg. **CPU pipeline only during runtime**. - inertia (dim=3): The diagonal values of the inertia matrix. **CPU pipeline only** - material_properties (dim=3): Static friction, Dynamic friction, and Restitution. - contact_offset (dim=1): A small distance from the surface of the collision geometry at which contacts start being generated. - rest_offset (dim=1): A small distance from the surface of the collision geometry at which the effective contact with the shape takes place. - scale (dim=1): The scale of the rigid prim. `on_startup` only. - density (dim=1): Density of the rigid prim. `on_startup` only. **articulation\_views**: - position (dim=3): The position of the articulation root. In meters. - orientation (dim=3): The orientation of the articulation root, specified with euler angles. In radians. - linear_velocity (dim=3): The linear velocity of the articulation root. In m/s. **CPU pipeline only** - angular_velocity (dim=3): The angular velocity of the articulation root. In rad/s. **CPU pipeline only** - velocity (dim=6): The linear + angular velocity of the articulation root. - stiffness (dim=num_dof): The stiffness of the joints. - damping (dim=num_dof): The damping of the joints - joint_friction (dim=num_dof): The friction coefficient of the joints. - joint_positions (dim=num_dof): The joint positions. In radians or meters. - joint_velocities (dim=num_dof): The joint velocities. In rad/s or m/s. - lower_dof_limits (dim=num_dof): The lower limit of the joints. In radians or meters. - upper_dof_limits (dim=num_dof): The upper limit of the joints. In radians or meters. - max_efforts (dim=num_dof): The maximum force or torque that the joints can exert. In N or Nm. - joint_armatures (dim=num_dof): A value added to the diagonal of the joint-space inertia matrix. Physically, it corresponds to the rotating part of a motor - joint_max_velocities (dim=num_dof): The maximum velocity allowed on the joints. In rad/s or m/s. - joint_efforts (dim=num_dof): Applies a force or a torque on the joints. In N or Nm. - body_masses (dim=num_bodies): The mass of each body in the articulation. In kg. **CPU pipeline only** - body_inertias (dim=num_bodies×3): The diagonal values of the inertia matrix of each body. **CPU pipeline only** - material_properties (dim=num_bodies×3): The static friction, dynamic friction, and restitution of each body in the articulation, specified in the following order: [body_1_static_friciton, body_1_dynamic_friciton, body_1_restitution, body_1_static_friciton, body_2_dynamic_friciton, body_2_restitution, ... ] - tendon_stiffnesses (dim=num_tendons): The stiffness of the fixed tendons in the articulation. - tendon_dampings (dim=num_tendons): The damping of the fixed tendons in the articulation. - tendon_limit_stiffnesses (dim=num_tendons): The limit stiffness of the fixed tendons in the articulation. - tendon_lower_limits (dim=num_tendons): The lower limits of the fixed tendons in the articulation. - tendon_upper_limits (dim=num_tendons): The upper limits of the fixed tendons in the articulation. - tendon_rest_lengths (dim=num_tendons): The rest lengths of the fixed tendons in the articulation. - tendon_offsets (dim=num_tendons): The offsets of the fixed tendons in the articulation. - scale (dim=1): The scale of the articulation. `on_startup` only. Applying Domain Randomization ------------------------------ To parse the domain randomization configurations in the task `yaml` file and set up the DR pipeline, it is necessary to call `self._randomizer.set_up_domain_randomization(self)`, where `self._randomizer` is the `Randomizer` object created in RLTask's `__init__`. It is worth noting that the names of the views provided under `rigid_prim_views` or `articulation_views` in the task `yaml` file must match the names passed into `RigidPrimView` or `ArticulationView` objects in the python task file. In addition, all `RigidPrimView` and `ArticulationView` that would have domain randomizaiton applied must be added to the scene in the task's `set_up_scene()` via `scene.add()`. To trigger `on_startup` randomizations, call `self._randomizer.apply_on_startup_domain_randomization(self)` in `set_up_scene()` after all views are added to the scene. Note that `on_startup` randomizations are only availble to rigid prim scale, mass, density and articulation scale parameters since these parameters cannot be randomized after the simulation begins on GPU pipeline. Therefore, randomizations must be applied to these parameters in `set_up_scene()` prior to the start of the simulation. To trigger `on_reset` and `on_interval` randomizations, it is required to step the interal counter of the DR pipeline in `pre_physics_step()`: ```python if self._randomizer.randomize: omni.replicator.isaac.physics_view.step_randomization(reset_inds) ``` `reset_inds` is a list of indices of the environments that need to be reset. For those environments, it will trigger the randomizations defined with `on_reset`. All other environments will follow randomizations defined with `on_interval`. Randomization Scheduling ---------------------------- We provide methods to modify distribution parameters defined in the `yaml` file during training, which allows custom DR scheduling. There are three methods from the `Randomizer` class that are relevant to DR scheduling: - `get_initial_dr_distribution_parameters`: returns a numpy array of the initial parameters (as defined in the `yaml` file) of a specified distribution - `get_dr_distribution_parameters`: returns a numpy array of the current parameters of a specified distribution - `set_dr_distribution_parameters`: sets new parameters to a specified distribution Using the DR configuration example defined above, we can get the current parameters and set new parameters to gravity randomization and shadow hand joint stiffness randomization as follows: ```python current_gravity_dr_params = self._randomizer.get_dr_distribution_parameters( "simulation", "gravity", "on_reset", ) self._randomizer.set_dr_distribution_parameters( [[0.0, 0.0, 0.0], [0.0, 0.0, 0.5]], "simulation", "gravity", "on_reset", ) current_joint_stiffness_dr_params = self._randomizer.get_dr_distribution_parameters( "articulation_views", "shadow_hand_view", "stiffness", "on_reset", ) self._randomizer.set_dr_distribution_parameters( [0.7, 1.55], "articulation_views", "shadow_hand_view", "stiffness", "on_reset", ) ``` The following is an example of using these methods to perform linear scheduling of gaussian noise that is added to observations and actions in the above shadow hand example. The following method linearly adds more noise to observations and actions every epoch up until the `schedule_epoch`. This method can be added to the Task python class and be called in `pre_physics_step()`. ```python def apply_observations_actions_noise_linear_scheduling(self, schedule_epoch=100): current_epoch = self._env.sim_frame_count // self._cfg["task"]["env"]["controlFrequencyInv"] // self._cfg["train"]["params"]["config"]["horizon_length"] if current_epoch <= schedule_epoch: if (self._env.sim_frame_count // self._cfg["task"]["env"]["controlFrequencyInv"]) % self._cfg["train"]["params"]["config"]["horizon_length"] == 0: for distribution_path in [("observations", "on_reset"), ("observations", "on_interval"), ("actions", "on_reset"), ("actions", "on_interval")]: scheduled_params = self._randomizer.get_initial_dr_distribution_parameters(*distribution_path) scheduled_params[1] = (1/schedule_epoch) * current_epoch * scheduled_params[1] self._randomizer.set_dr_distribution_parameters(scheduled_params, *distribution_path) ```
16,889
Markdown
51.453416
156
0.68814
NVIDIA-Omniverse/OmniIsaacGymEnvs/docs/framework/instanceable_assets.md
## A Note on Instanceable USD Assets The following section presents a method that modifies existing USD assets which allows Isaac Sim to load significantly more environments. This is currently an experimental method and has thus not been completely integrated into the framework. As a result, this section is reserved for power users who wish to maxmimize the performance of the Isaac Sim RL framework. ### Motivation One common issue in Isaac Sim that occurs when we try to increase the number of environments `numEnvs` is running out of RAM. This occurs because the Isaac Sim RL framework uses `omni.isaac.cloner` to duplicate environments. As a result, there are `numEnvs` number of identical copies of the visual and collision meshes in the scene, which consumes lots of memory. However, only one copy of the meshes are needed on stage since prims in all other environments could merely reference that one copy, thus reducing the amount of memory used for loading environments. To enable this functionality, USD assets need to be modified to be `instanceable`. ### Creating Instanceable Assets Assets can now be directly imported as Instanceable assets through the URDF and MJCF importers provided in Isaac Sim. By selecting this option, imported assets will be split into two separate USD files that follow the above hierarchy definition. Any mesh data will be written to an USD stage to be referenced by the main USD stage, which contains the main robot definition. To use the Instanceable option in the importers, first check the `Create Instanceable Asset` option. Then, specify a file path to indicate the location for saving the mesh data in the `Instanceable USD Path` textbox. This will default to `./instanceable_meshes.usd`, which will generate a file `instanceable_meshes.usd` that is saved to the current directory. Once the asset is imported with these options enabled, you will see the robot definition in the stage - we will refer to this stage as the master stage. If we expand the robot hierarchy in the Stage, we will notice that the parent prims that have mesh decendants have been marked as Instanceable and they reference a prim in our `Instanceable USD Path` USD file. We are also no longer able to modify attributes of descendant meshes. To add the instanced asset into a new stage, we will simply need to add the master USD file. ### Converting Existing Assets We provide the utility function `convert_asset_instanceable`, which creates an instanceable version of a given USD asset in `/omniisaacgymenvs/utils/usd_utils/create_instanceable_assets.py`. To run this function, launch Isaac Sim and open the script editor via `Window -> Script Editor`. Enter the following script and press `Run (Ctrl + Enter)`: ```bash from omniisaacgymenvs.utils.usd_utils.create_instanceable_assets import convert_asset_instanceable convert_asset_instanceable( asset_usd_path=ASSET_USD_PATH, source_prim_path=SOURCE_PRIM_PATH, save_as_path=SAVE_AS_PATH ) ``` Note that `ASSET_USD_PATH` is the file path to the USD asset (*e.g.* robot_asset.usd). `SOURCE_PRIM_PATH` is the USD path of the root prim of the asset on stage. `SAVE_AS_PATH` is the file path of the generated instanceable version of the asset (*e.g.* robot_asset_instanceable.usd). Assuming that `SAVE_AS_PATH` is `OUTPUT_NAME.usd`, the above script will generate two files: `OUTPUT_NAME.usd` and `OUTPUT_NAME_meshes.usd`. `OUTPUT_NAME.usd` is the instanceable version of the asset that can be imported to stage and used by `omni.isaac.cloner` to create numerous duplicates without consuming much memory. `OUTPUT_NAME_meshes.usd` contains all the visual and collision meshes that `OUTPUT_NAME.usd` references. It is worth noting that any [USD Relationships](https://graphics.pixar.com/usd/dev/api/class_usd_relationship.html) on the referenced meshes are removed in `OUTPUT_NAME.usd`. This is because those USD Relationships originally have targets set to prims in `OUTPUT_NAME_meshes.usd` and hence cannot be accessed from `OUTPUT_NAME.usd`. Common examples of USD Relationships that could exist on the meshes are visual materials, physics materials, and filtered collision pairs. Therefore, it is recommanded to set these USD Relationships on the meshes' parent Xforms instead of the meshes themselves. In a case where we would like to update the main USD file where the instanceable USD file is being referenced from, we also provide a utility method to update all references in the stage that matches a source reference path to a new USD file path. ```bash from omniisaacgymenvs.utils.usd_utils.create_instanceable_assets import update_reference update_reference( source_prim_path=SOURCE_PRIM_PATH, source_reference_path=SOURCE_REFERENCE_PATH, target_reference_path=TARGET_REFERENCE_PATH ) ``` ### Limitations USD requires a specific structure in the asset tree definition in order for the instanceable flag to take action. To mark any mesh or primitive geometry prim in the asset as instanceable, the mesh prim requires a parent Xform prim to be present, which will be used to add a reference to a master USD file containing definition of the mesh prim. For example, the following definition: ``` World |_ Robot |_ Collisions |_ Sphere |_ Box ``` would have to be modified to: ``` World |_ Robot |_ Collisions |_ Sphere_Xform | |_ Sphere |_ Box_Xform |_ Box ``` Any references that exist on the original `Sphere` and `Box` prims would have to be moved to `Sphere_Xform` and `Box_Xform` prims. To help with the process of creating new parent prims, we provide a utility method `create_parent_xforms()` in `omniisaacgymenvs/utils/usd_utils/create_instanceable_assets.py` to automatically insert a new Xform prim as a parent of every mesh prim in the stage. This method can be run on an existing non-instanced USD file for an asset from the script editor: ```bash from omniisaacgymenvs.utils.usd_utils.create_instanceable_assets import create_parent_xforms create_parent_xforms( asset_usd_path=ASSET_USD_PATH, source_prim_path=SOURCE_PRIM_PATH, save_as_path=SAVE_AS_PATH ) ``` This method can also be run as part of `convert_asset_instanceable()` method, by passing in the argument `create_xforms=True`. It is also worth noting that once an instanced asset is added to the stage, we can no longer modify USD attributes on the instanceable prims. For example, to modify attributes of collision meshes that are set as instanceable, we have to first modify the attributes on the corresponding prims in the master prim which our instanced asset references from. Then, we can allow the instanced asset to pick up the updated values from the master prim.
6,846
Markdown
56.058333
444
0.76804
NVIDIA-Omniverse/OmniIsaacGymEnvs/docs/framework/reproducibility.md
Reproducibility and Determinism =============================== Seeds ----- To achieve deterministic behavior on multiple training runs, a seed value can be set in the training config file for each task. This will potentially allow for individual runs of the same task to be deterministic when executed on the same machine and system setup. Alternatively, a seed can also be set via command line argument `seed=<seed>` to override any settings in config files. If no seed is specified in either config files or command line arguments, we default to generating a random seed. In this case, individual runs of the same task should not be expected to be deterministic. For convenience, we also support setting `seed=-1` to generate a random seed, which will override any seed values set in config files. By default, we have explicitly set all seed values in config files to be 42. PyTorch Deterministic Training ------------------------------ We also include a `torch_deterministic` argument for use when running RL training. Enabling this flag (by passing `torch_deterministic=True`) will apply additional settings to PyTorch that can force the usage of deterministic algorithms in PyTorch, but may also negatively impact runtime performance. For more details regarding PyTorch reproducibility, refer to <https://pytorch.org/docs/stable/notes/randomness.html>. If both `torch_deterministic=True` and `seed=-1` are set, the seed value will be fixed to 42. Runtime Simulation Changes / Domain Randomization ------------------------------------------------- Note that using a fixed seed value will only **potentially** allow for deterministic behavior. Due to GPU work scheduling, it is possible that runtime changes to simulation parameters can alter the order in which operations take place, as environment updates can happen while the GPU is doing other work. Because of the nature of floating point numeric storage, any alteration of execution ordering can cause small changes in the least significant bits of output data, leading to divergent execution over the simulation of thousands of environments and simulation frames. As an example of this, runtime domain randomization of object scales is known to cause both determinancy and simulation issues when running on the GPU due to the way those parameters are passed from CPU to GPU in lower level APIs. Therefore, this is only supported at setup time before starting simulation, which is specified by the `on_startup` condition for Domain Randomization. At this time, we do not believe that other domain randomizations offered by this framework cause issues with deterministic execution when running GPU simulation, but directly manipulating other simulation parameters outside of the omni.isaac.core View APIs may induce similar issues. Also due to floating point precision, states across different environments in the simulation may be non-deterministic when the same set of actions are applied to the same initial states. This occurs as environments are placed further apart from the world origin at (0, 0, 0). As actors get placed at different origins in the world, floating point errors may build up and result in slight variance in results even when starting from the same initial states. One possible workaround for this issue is to place all actors/environments at the world origin at (0, 0, 0) and filter out collisions between the environments. Note that this may induce a performance degradation of around 15-50%, depending on the complexity of actors and environment. Another known cause of non-determinism is from resetting actors into contact states. If actors within a scene is reset to a state where contacts are registered between actors, the simulation may not be able to produce deterministic results. This is because contacts are not recorded and will be re-computed from scratch for each reset scenario where actors come into contact, which cannot guarantee deterministic behavior across different computations.
4,017
Markdown
53.297297
96
0.787155
NVIDIA-Omniverse/OmniIsaacGymEnvs/docs/framework/framework.md
## RL Framework ### Overview Our RL examples are built on top of Isaac Sim's RL framework provided in `omni.isaac.gym`. Tasks are implemented following `omni.isaac.core`'s Task structure. PPO training is performed using the [rl_games](https://github.com/Denys88/rl_games) library, but we provide the flexibility to use other RL libraries for training. For a list of examples provided, refer to the [RL List of Examples](../examples/rl_examples.md) ### Class Definition The RL ecosystem can be viewed as three main pieces: the Task, the RL policy, and the Environment wrapper that provides an interface for communication between the task and the RL policy. #### Task The Task class is where main task logic is implemented, such as computing observations and rewards. This is where we can collect states of actors in the scene and apply controls or actions to our actors. For convenience, we provide a base Task class, `RLTask`, which inherits from the `BaseTask` class in `omni.isaac.core`. This class is responsible for dealing with common configuration parsing, buffer initialization, and environment creation. Note that some config parameters and buffers in this class are specific to the rl_games library, and it is not necessary to inherit new tasks from `RLTask`. A few key methods in `RLTask` include: * `__init__(self, name: str, env: VecEnvBase, offset: np.ndarray = None)` - Parses config values common to all tasks and initializes action/observation spaces if not defined in the child class. Defines a GridCloner by default and creates a base USD scope for holding all environment prims. Can be called from child class. * `set_up_scene(self, scene: Scene, replicate_physics=True, collision_filter_global_paths=[], filter_collisions=True)` - Adds ground plane and creates clones of environment 0 based on values specifid in config. Can be called from child class `set_up_scene()`. * `pre_physics_step(self, actions: torch.Tensor)` - Takes in actions buffer from RL policy. Can be overriden by child class to process actions. * `post_physics_step(self)` - Controls flow of RL data processing by triggering APIs to compute observations, retrieve states, compute rewards, resets, and extras. Will return observation, reward, reset, and extras buffers. #### Environment Wrappers As part of the RL framework in Isaac Sim, we have introduced environment wrapper classes in `omni.isaac.gym` for RL policies to communicate with simulation in Isaac Sim. This class provides a vectorized interface for common RL APIs used by `gym.Env` and can be easily extended towards RL libraries that require additional APIs. We show an example of this extension process in this repository, where we extend `VecEnvBase` as provided in `omni.isaac.gym` to include additional APIs required by the rl_games library. Commonly used APIs provided by the base wrapper class `VecEnvBase` include: * `render(self, mode: str = "human")` - renders the current frame * `close(self)` - closes the simulator * `seed(self, seed: int = -1)` - sets a seed. Use `-1` for a random seed. * `step(self, actions: Union[np.ndarray, torch.Tensor])` - triggers task `pre_physics_step` with actions, steps simulation and renderer, computes observations, rewards, dones, and returns state buffers * `reset(self)` - triggers task `reset()`, steps simulation, and re-computes observations ##### Multi-Threaded Environment Wrapper for Extension Workflows `VecEnvBase` is a simple interface that’s designed to provide commonly used `gym.Env` APIs required by RL libraries. Users can create an instance of this class, attach your task to the interface, and provide your wrapper instance to the RL policy. Since the RL algorithm maintains the main loop of execution, interaction with the UI and environments in the scene can be limited and may interfere with the training loop. We also provide another environment wrapper class called `VecEnvMT`, which is designed to isolate the RL policy in a new thread, separate from the main simulation and rendering thread. This class provides the same set of interface as `VecEnvBase`, but also provides threaded queues for sending and receiving actions and states between the RL policy and the task. In order to use this wrapper interface, users have to implement a `TrainerMT` class, which should implement a `run()` method that initiates the RL loop on a new thread. We show an example of this in OmniIsaacGymEnvs under `omniisaacgymenvs/utils/rlgames/rlgames_train_mt.py`. The setup for using `VecEnvMT` is more involved compared to the single-threaded `VecEnvBase` interface, but will allow users to have more control over starting and stopping the training loop through interaction with the UI. Note that `VecEnvMT` has a timeout variable, which defaults to 90 seconds. If either the RL thread waiting for physics state exceeds the timeout amount or the simulation thread waiting for RL actions exceeds the timeout amount, the threaded queues will throw an exception and terminate training. For larger scenes that require longer simulation or training time, try increasing the timeout variable in `VecEnvMT` to prevent unnecessary timeouts. This can be done by passing in a `timeout` argument when calling `VecEnvMT.initialize()`. This wrapper is currently only supported with the [extension workflow](extension_workflow.md). ### Creating New Examples For simplicity, we will focus on using the single-threaded `VecEnvBase` interface in this tutorial. To run any example, first make sure an instance of `VecEnvBase` or descendant of `VecEnvBase` is initialized. This will be required as an argumet to our new Task. For example: ``` python env = VecEnvBase(headless=False) ``` The headless parameter indicates whether a viewer should be created for visualizing results. Then, create our task class, extending it from `RLTask`: ```python class MyNewTask(RLTask): def __init__( self, name: str, # name of the Task sim_config: SimConfig, # SimConfig instance for parsing cfg env: VecEnvBase, # env instance of VecEnvBase or inherited class offset=None # transform offset in World ) -> None: # parse configurations, set task-specific members ... self._num_observations = 4 self._num_actions = 1 # call parent class’s __init__ RLTask.__init__(self, name, env) ``` The `__init__` method should take 4 arguments: * `name`: a string for the name of the task (required by BaseTask) * `sim_config`: an instance of `SimConfig` used for config parsing, can be `None`. This object is created in `omniisaacgymenvs/utils/task_utils.py`. * `env`: an instance of `VecEnvBase` or an inherited class of `VecEnvBase` * `offset`: any offset required to place the `Task` in `World` (required by `BaseTask`) In the `__init__` method of `MyNewTask`, we can populate any task-specific parameters, such as dimension of observations and actions, and retrieve data from config dictionaries. Make sure to make a call to `RLTask`’s `__init__` at the end of the method to perform additional data initialization. Next, we can implement the methods required by the RL framework. These methods follow APIs defined in `omni.isaac.core` `BaseTask` class. Below is an example of a simple implementation for each method. ```python def set_up_scene(self, scene: Scene) -> None: # implement environment setup here add_prim_to_stage(my_robot) # add a robot actor to the stage super().set_up_scene(scene) # pass scene to parent class - this method in RLTask also uses GridCloner to clone the robot and adds a ground plane if desired self._my_robots = ArticulationView(...) # create a view of robots scene.add(self._my_robots) # add view to scene for initialization def post_reset(self): # implement any logic required for simulation on-start here pass def pre_physics_step(self, actions: torch.Tensor) -> None: # implement logic to be performed before physics steps self.perform_reset() self.apply_action(actions) def get_observations(self) -> dict: # implement logic to retrieve observation states self.obs_buf = self.compute_observations() def calculate_metrics(self) -> None: # implement logic to compute rewards self.rew_buf = self.compute_rewards() def is_done(self) -> None: # implement logic to update dones/reset buffer self.reset_buf = self.compute_resets() ``` To launch the new example from one of our training scripts, add `MyNewTask` to `omniisaacgymenvs/utils/task_util.py`. In `initialize_task()`, add an import to the `MyNewTask` class and add an instance to the `task_map` dictionary to register it into the command line parsing. To use the Hydra config parsing system, also add a task and train config files into `omniisaacgymenvs/cfg`. The config files should be named `cfg/task/MyNewTask.yaml` and `cfg/train/MyNewTaskPPO.yaml`. Finally, we can launch `MyNewTask` with: ```bash PYTHON_PATH random_policy.py task=MyNewTask ``` ### Using a New RL Library In this repository, we provide an example of extending Isaac Sim's environment wrapper classes to work with the rl_games library, which can be found at `omniisaacgymenvs/envs/vec_env_rlgames.py` and `omniisaacgymenvs/envs/vec_env_rlgames_mt.py`. The first script, `omniisaacgymenvs/envs/vec_env_rlgames.py`, extends from `VecEnvBase`. ```python from omni.isaac.gym.vec_env import VecEnvBase class VecEnvRLGames(VecEnvBase): ``` One of the features in rl_games is the support for asymmetrical actor-critic policies, which requires a `states` buffer in addition to the `observations` buffer. Thus, we have overriden a few of the class in `VecEnvBase` to incorporate this requirement. ```python def set_task( self, task, backend="numpy", sim_params=None, init_sim=True ) -> None: super().set_task(task, backend, sim_params, init_sim) # class VecEnvBase's set_task to register task to the environment instance # special variables required by rl_games self.num_states = self._task.num_states self.state_space = self._task.state_space def step(self, actions): # we clamp the actions so that values are within a defined range actions = torch.clamp(actions, -self._task.clip_actions, self._task.clip_actions).to(self._task.device).clone() # pass actions buffer to task for processing self._task.pre_physics_step(actions) # allow users to specify the control frequency through config for _ in range(self._task.control_frequency_inv): self._world.step(render=self._render) self.sim_frame_count += 1 # compute new buffers self._obs, self._rew, self._resets, self._extras = self._task.post_physics_step() self._states = self._task.get_states() # special buffer required by rl_games # return buffers in format required by rl_games obs_dict = {"obs": self._obs, "states": self._states} return obs_dict, self._rew, self._resets, self._extras ``` Similarly, we also have a multi-threaded version of the rl_games environment wrapper implementation, `omniisaacgymenvs/envs/vec_env_rlgames_mt.py`. This class extends from `VecEnvMT` and `VecEnvRLGames`: ```python from omni.isaac.gym.vec_env import VecEnvMT from .vec_env_rlgames import VecEnvRLGames class VecEnvRLGamesMT(VecEnvRLGames, VecEnvMT): ``` In this class, we also have a special method `_parse_data(self, data)`, which is required to be implemented to parse dictionary values passed through queues. Since multiple buffers of data are required by the RL policy, we concatenate all of the buffers in a single dictionary, and send that to the queue to be received by the RL thread. ```python def _parse_data(self, data): self._obs = torch.clamp(data["obs"], -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device).clone() self._rew = data["rew"].to(self._task.rl_device).clone() self._states = torch.clamp(data["states"], -self._task.clip_obs, self._task.clip_obs).to(self._task.rl_device).clone() self._resets = data["reset"].to(self._task.rl_device).clone() self._extras = data["extras"].copy() ```
12,172
Markdown
60.791878
862
0.747453
NVIDIA-Omniverse/OmniIsaacGymEnvs/docs/framework/limitations.md
### API Limitations #### omni.isaac.core Setter APIs Setter APIs in omni.isaac.core for ArticulationView, RigidPrimView, and RigidContactView should only be called once per simulation step for each view instance per API. This means that for use cases where multiple calls to the same setter API from the same view instance is required, users will need to cache the states to be set for intermmediate calls, and make only one call to the setter API prior to stepping physics with the complete buffer containing all cached states. If multiple calls to the same setter API from the same view object are made within the simulation step, subsequent calls will override the states that have been set by prior calls to the same API, voiding the previous calls to the API. The API can be called again once a simulation step is made. For example, the below code will override states. ```python my_view.set_world_poses(positions=[[0, 0, 1]], orientations=[[1, 0, 0, 0]], indices=[0]) # this call will void the previous call my_view.set_world_poses(positions=[[0, 1, 1]], orientations=[[1, 0, 0, 0]], indices=[1]) my_world.step() ``` Instead, the below code should be used. ```python my_view.set_world_poses(positions=[[0, 0, 1], [0, 1, 1]], orientations=[[1, 0, 0, 0], [1, 0, 0, 0]], indices=[0, 1]) my_world.step() ``` #### omni.isaac.core Getter APIs Getter APIs for cloth simulation may return stale states when used with the GPU pipeline. This is because the physics simulation requires a simulation step to occur in order to refresh the GPU buffers with new states. Therefore, when a getter API is called after a setter API before a simulation step, the states returned from the getter API may not reflect the values that were set using the setter API. For example: ```python my_view.set_world_positions(positions=[[0, 0, 1]], indices=[0]) # Values may be stale when called before step positions = my_view.get_world_positions() # positions may not match [[0, 0, 1]] my_world.step() # Values will be updated when called after step positions = my_view.get_world_positions() # positions will reflect the new states ``` #### Performing Resets When resetting the states of actors, impulses generated by previous target or effort controls will continue to be carried over from the previous states in simulation. Therefore, depending on the time step, the masses of the objects, and the magnitude of the impulses, the difference between the desired reset state and the observed first state after reset can be large. To eliminate this issue, users should also reset any position/velocity targets or effort controllers to the reset state or zero state when resetting actor states. For setting joint positions and velocities using the omni.isaac.core ArticulationView APIs, position targets and velocity targets will automatically be set to the same states as joint positions and velocities. #### Massless Links It may be helpful in some scenarios to introduce dummy bodies into articulations for retrieving transformations at certain locations of the articulation. Although it is possible to introduce rigid bodies with no mass and colliders APIs and attach them to the articulation with fixed joints, this can sometimes cause physics instabilities in simulation. To prevent instabilities from occurring, it is recommended to add a dummy geometry to the rigid body and include both Mass and Collision APIs. The mass of the geometry can be set to a very small value, such as 0.0001, to avoid modifying physical behaviors of the articulation. Similarly, we can also disable collision on the Collision API of the geometry to preserve contact behavior of the articulation.
3,685
Markdown
52.420289
155
0.775577
NVIDIA-Omniverse/Blender-Addon-OmniPanel/README.md
# DEPRECATED This repo has been deprecated. Please see [NVIDIA-Omniverse/blender_omniverse_addons](https://github.com/NVIDIA-Omniverse/blender_omniverse_addons)
164
Markdown
31.999994
148
0.804878
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. bl_info = { "name": "Omni Panel", "author": "NVIDIA Corporation", "version": (1, 0, 0), "blender": (3, 0, 0), "location": "View3D > Toolbar > Omniverse", "description": "Nvidia Omniverse bake materials for export to usd", "warning": "", "doc_url": "", "category": "Omniverse", } import bpy #Import classes from .material_bake.operators import (OBJECT_OT_omni_bake_mapbake, OBJECT_OT_omni_bake_bgbake_status, OBJECT_OT_omni_bake_bgbake_import, OBJECT_OT_omni_bake_bgbake_clear) from .ui import (OBJECT_PT_omni_bake_panel, OmniBakePreferences) from .particle_bake.operators import(MyProperties, PARTICLES_OT_omni_hair_bake) #Classes list for register #List of all classes that will be registered classes = ([OBJECT_OT_omni_bake_mapbake, OBJECT_PT_omni_bake_panel, OmniBakePreferences, OBJECT_OT_omni_bake_bgbake_status, OBJECT_OT_omni_bake_bgbake_import, OBJECT_OT_omni_bake_bgbake_clear, MyProperties, PARTICLES_OT_omni_hair_bake]) def ShowMessageBox(message = "", title = "Message Box", icon = 'INFO'): def draw(self, context): self.layout.label(text=message) bpy.context.window_manager.popup_menu(draw, title = title, icon = icon) #---------------------UPDATE FUNCTIONS-------------------------------------------- def prepmesh_update(self, context): if context.scene.prepmesh == False: context.scene.hidesourceobjects = False else: context.scene.hidesourceobjects = True def texture_res_update(self, context): if context.scene.texture_res == "0.5k": context.scene.imgheight = 1024/2 context.scene.imgwidth = 1024/2 context.scene.render.bake.margin = 6 elif context.scene.texture_res == "1k": context.scene.imgheight = 1024 context.scene.imgwidth = 1024 context.scene.render.bake.margin = 10 elif context.scene.texture_res == "2k": context.scene.imgheight = 1024*2 context.scene.imgwidth = 1024*2 context.scene.render.bake.margin = 14 elif context.scene.texture_res == "4k": context.scene.imgheight = 1024*4 context.scene.imgwidth = 1024*4 context.scene.render.bake.margin = 20 elif context.scene.texture_res == "8k": context.scene.imgheight = 1024*8 context.scene.imgwidth = 1024*8 context.scene.render.bake.margin = 32 def newUVoption_update(self, context): if bpy.context.scene.newUVoption == True: bpy.context.scene.prefer_existing_sbmap = False def all_maps_update(self,context): bpy.context.scene.selected_col = True bpy.context.scene.selected_metal = True bpy.context.scene.selected_rough = True bpy.context.scene.selected_normal = True bpy.context.scene.selected_trans = True bpy.context.scene.selected_transrough = True bpy.context.scene.selected_emission = True bpy.context.scene.selected_specular = True bpy.context.scene.selected_alpha = True bpy.context.scene.selected_sss = True bpy.context.scene.selected_ssscol = True #-------------------END UPDATE FUNCTIONS---------------------------------------------- def register(): #Register classes global classes for cls in classes: bpy.utils.register_class(cls) global bl_info version = bl_info["version"] version = str(version[0]) + str(version[1]) + str(version[2]) OBJECT_PT_omni_bake_panel.version = f"{str(version[0])}.{str(version[1])}.{str(version[2])}" #Global variables des = "Texture Resolution" bpy.types.Scene.texture_res = bpy.props.EnumProperty(name="Texture Resolution", default="1k", description=des, items=[ ("0.5k", "0.5k", f"Texture Resolution of {1024/2} x {1024/2}"), ("1k", "1k", f"Texture Resolution of 1024 x 1024"), ("2k", "2k", f"Texture Resolution of {1024*2} x {1024*2}"), ("4k", "4k", f"Texture Resolution of {1024*4} x {1024*4}"), ("8k", "8k", f"Texture Resolution of {1024*8} x {1024*8}") ], update = texture_res_update) des = "Distance to cast rays from target object to selected object(s)" bpy.types.Scene.ray_distance = bpy.props.FloatProperty(name="Ray Distance", default = 0.2, description=des) bpy.types.Scene.ray_warning_given = bpy.props.BoolProperty(default = False) #--- MAPS ----------------------- des = "Bake all maps (Diffuse, Metal, SSS, SSS Col. Roughness, Normal, Transmission, Transmission Roughness, Emission, Specular, Alpha, Displacement)" bpy.types.Scene.all_maps = bpy.props.BoolProperty(name="Bake All Maps", default = True, description=des, update = all_maps_update) des = "Bake a PBR Colour map" bpy.types.Scene.selected_col = bpy.props.BoolProperty(name="Diffuse", default = True, description=des) des = "Bake a PBR Metalness map" bpy.types.Scene.selected_metal = bpy.props.BoolProperty(name="Metal", description=des, default= True) des = "Bake a PBR Roughness or Glossy map" bpy.types.Scene.selected_rough = bpy.props.BoolProperty(name="Roughness", description=des, default= True) des = "Bake a Normal map" bpy.types.Scene.selected_normal = bpy.props.BoolProperty(name="Normal", description=des, default= True) des = "Bake a PBR Transmission map" bpy.types.Scene.selected_trans = bpy.props.BoolProperty(name="Transmission", description=des, default= True) des = "Bake a PBR Transmission Roughness map" bpy.types.Scene.selected_transrough = bpy.props.BoolProperty(name="TR Rough", description=des, default= True) des = "Bake an Emission map" bpy.types.Scene.selected_emission = bpy.props.BoolProperty(name="Emission", description=des, default= True) des = "Bake a Subsurface map" bpy.types.Scene.selected_sss = bpy.props.BoolProperty(name="SSS", description=des, default= True) des = "Bake a Subsurface colour map" bpy.types.Scene.selected_ssscol = bpy.props.BoolProperty(name="SSS Col", description=des, default= True) des = "Bake a Specular/Reflection map" bpy.types.Scene.selected_specular = bpy.props.BoolProperty(name="Specular", description=des, default= True) des = "Bake a PBR Alpha map" bpy.types.Scene.selected_alpha = bpy.props.BoolProperty(name="Alpha", description=des, default= True) #------------------------------------------UVs----------------------------------------- des = "Use Smart UV Project to create a new UV map for your objects (or target object if baking to a target). See Blender Market FAQs for more details" bpy.types.Scene.newUVoption = bpy.props.BoolProperty(name="New UV(s)", description=des, update=newUVoption_update, default= False) des = "If one exists for the object being baked, use any existing UV maps called 'OmniBake' for baking (rather than the active UV map)" bpy.types.Scene.prefer_existing_sbmap = bpy.props.BoolProperty(name="Prefer existing UV maps called OmniBake", description=des) des = "New UV Method" bpy.types.Scene.newUVmethod = bpy.props.EnumProperty(name="New UV Method", default="SmartUVProject_Individual", description=des, items=[ ("SmartUVProject_Individual", "Smart UV Project (Individual)", "Each object gets a new UV map using Smart UV Project")]) des = "Margin between islands to use for Smart UV Project" bpy.types.Scene.unwrapmargin = bpy.props.FloatProperty(name="Margin", default=0.03, description=des) des = "Bake to normal UVs" bpy.types.Scene.uv_mode = bpy.props.EnumProperty(name="UV Mode", default="normal", description=des, items=[ ("normal", "Normal", "Normal UV maps")]) #--------------------------------Prep/CleanUp---------------------------------- des = "Create a copy of your selected objects in Blender (or target object if baking to a target) and apply the baked textures to it. If you are baking in the background, this happens after you import" bpy.types.Scene.prepmesh = bpy.props.BoolProperty(name="Copy objects and apply bakes", default = True, description=des, update=prepmesh_update) des = "Hide the source object that you baked from in the viewport after baking. If you are baking in the background, this happens after you import" bpy.types.Scene.hidesourceobjects = bpy.props.BoolProperty(name="Hide source objects after bake", default = True, description=des) des = "Set the height of the baked image that will be produced" bpy.types.Scene.imgheight = bpy.props.IntProperty(name="Height", default=1024, description=des) des = "Set the width of the baked image that will be produced" bpy.types.Scene.imgwidth = bpy.props.IntProperty(name="Width", default=1024, description=des) des="Name to apply to these bakes (is incorporated into the bakes file name, provided you have included this in the image format string - see addon preferences). NOTE: To maintain compatibility, only MS Windows acceptable characters will be used" bpy.types.Scene.batchName = bpy.props.StringProperty(name="Batch name", description=des, default="Bake1", maxlen=20) #---------------------Where To Bake?------------------------------------------- bpy.types.Scene.bgbake = bpy.props.EnumProperty(name="Background Bake", default="fg", items=[ ("fg", "Foreground", "Perform baking in the foreground. Blender will lock up until baking is complete"), ("bg", "Background", "Perform baking in the background, leaving you free to continue to work in Blender while the baking is being carried out") ]) #---------------------Filehanding & Particles------------------------------------------ bpy.types.Scene.particle_options = bpy.props.PointerProperty(type= MyProperties) #-------------------Additional Shaders------------------------------------------- des = "Allows for use of Add, Diffuse, Glossy, Glass, Refraction, Transparent, Anisotropic Shaders. May cause inconsistent results" bpy.types.Scene.more_shaders = bpy.props.BoolProperty(name="Use Additional Shader Types", default=False, description=des) def unregister(): #User preferences global classes for cls in classes: bpy.utils.unregister_class(cls) del bpy.types.Scene.particle_options del bpy.types.Scene.more_shaders del bpy.types.Scene.newUVoption del bpy.types.Scene.prepmesh del bpy.types.Scene.unwrapmargin del bpy.types.Scene.texture_res del bpy.types.Scene.hidesourceobjects del bpy.types.Scene.batchName del bpy.types.Scene.bgbake del bpy.types.Scene.imgheight del bpy.types.Scene.imgwidth
11,397
Python
47.918455
250
0.675529
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/ui.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import bpy from .particle_bake.operators import* from .material_bake.background_bake import bgbake_ops from os.path import join, dirname import bpy.utils.previews #---------------Custom ICONs---------------------- def get_icons_directory(): icons_directory = join(dirname(__file__), "icons") return icons_directory #------------------------PANEL--------------------- class OBJECT_PT_omni_bake_panel(bpy.types.Panel): bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category = "Omniverse" bl_label = "NVIDIA OMNIVERSE" version = "0.0.0" #retrieve icons icons = bpy.utils.previews.new() icons_directory = get_icons_directory() icons.load("OMNIBLEND", join(icons_directory, "BlenderOMNI.png"), 'IMAGE') icons.load("OMNI", join(icons_directory, "ICON.png"), 'IMAGE') icons.load("BAKE",join(icons_directory, "Oven.png"), 'IMAGE') #draw the panel def draw(self, context): layout = self.layout #--------File Handling------------------- layout.label(text="Omniverse", icon_value=self.icons["OMNI"].icon_id) impExpCol = self.layout.column(align=True) impExpCol.label(text= "File Handling", icon='FILEBROWSER') impExpCol.operator('wm.usd_import', text='Import USD', icon='IMPORT') impExpCol.operator('wm.usd_export', text='Export USD', icon='EXPORT') #--------Particle Collection Instancing------------------- layout.separator() particleOptions = context.scene.particle_options particleCol = self.layout.column(align=True) particleCol.label(text = "Omni Particles", icon='PARTICLES') box = particleCol.box() column= box.column(align= True) column.prop(particleOptions, "deletePSystemAfterBake") row = column.row() row.prop(particleOptions, "animateData") if particleOptions.animateData: row = column.row(align=True) row.prop(particleOptions, "selectedStartFrame") row.prop(particleOptions, "selectedEndFrame") row = column.row() row.enabled = False row.label(text="Increased Calculation Time", icon= 'ERROR') row = column.row() row.scale_y = 1.5 row.operator('omni.hair_bake', text='Convert', icon='MOD_PARTICLE_INSTANCE') #Does not update while running. Set in "particle_bake.operators.py" # row = column.row() # row.scale_y = 1.2 # row.prop(particleOptions, "progressBar") #--------PBR Bake Settings------------------- layout.separator() column = layout.column(align= True) header = column.row() header.label(text = "Material Bake", icon = 'UV_DATA') box = column.box() row = box.row() if context.scene.all_maps == True: row.prop(context.scene, "all_maps", icon = 'CHECKBOX_HLT') if context.scene.all_maps == False: row.prop(context.scene, "all_maps", icon = 'CHECKBOX_DEHLT') column = box.column(align= True) row = column.row() row.prop(context.scene, "selected_col") row.prop(context.scene, "selected_metal") row = column.row() row.prop(context.scene, "selected_sss") row.prop(context.scene, "selected_ssscol") row = column.row() row.prop(context.scene, "selected_rough") row.prop(context.scene, "selected_normal") row = column.row() row.prop(context.scene, "selected_trans") row.prop(context.scene, "selected_transrough") row = column.row() row.prop(context.scene, "selected_emission") row.prop(context.scene, "selected_specular") row = column.row() row.prop(context.scene, "selected_alpha") row = column.row() colm = box.column(align=True) colm.prop(context.scene, "more_shaders") row = colm.row() row.enabled = False if context.scene.more_shaders: row.label(text="Inconsistent Results", icon= 'ERROR') #--------Texture Settings------------------- row = box.row() row.label(text="Texture Resolution:") row.scale_y = 0.5 row = box.row() row.prop(context.scene, "texture_res", expand=True) row.scale_y = 1 if context.scene.texture_res == "8k" or context.scene.texture_res == "4k": row = box.row() row.enabled = False row.label(text="Long Bake Times", icon= 'ERROR') #--------UV Settings------------------- column = box.column(align = True) row = column.row() row.prop(context.scene, "newUVoption") row.prop(context.scene, "unwrapmargin") #--------Other Settings------------------- column= box.column(align=True) row = column.row() if bpy.context.scene.bgbake == "fg": text = "Copy objects and apply bakes" else: text = "Copy objects and apply bakes (after import)" row.prop(context.scene, "prepmesh", text=text) if (context.scene.prepmesh == True): if bpy.context.scene.bgbake == "fg": text = "Hide source objects after bake" else: text = "Hide source objects after bake (after import)" row = column.row() row.prop(context.scene, "hidesourceobjects", text=text) #-------------Buttons------------------------- row = box.row() row.scale_y = 1.5 row.operator("object.omni_bake_mapbake", icon_value=self.icons["BAKE"].icon_id) row = column.row() row.scale_y = 1 row.prop(context.scene, "bgbake", expand=True) if context.scene.bgbake == "bg": row = column.row(align= True) # - BG status button col = row.column() if len(bgbake_ops.bgops_list) == 0: enable = False icon = "TIME" else: enable = True icon = "TIME" col.operator("object.omni_bake_bgbake_status", text="", icon=icon) col.enabled = enable # - BG import button col = row.column() if len(bgbake_ops.bgops_list_finished) != 0: enable = True icon = "IMPORT" else: enable = False icon = "IMPORT" col.operator("object.omni_bake_bgbake_import", text="", icon=icon) col.enabled = enable #BG erase button col = row.column() if len(bgbake_ops.bgops_list_finished) != 0: enable = True icon = "TRASH" else: enable = False icon = "TRASH" col.operator("object.omni_bake_bgbake_clear", text="", icon=icon) col.enabled = enable row.alignment = 'CENTER' row.label(text=f"Running {len(bgbake_ops.bgops_list)} | Finished {len(bgbake_ops.bgops_list_finished)}") #-------------Other material options------------------------- if len(bpy.context.selected_objects) != 0 and bpy.context.active_object != None: if bpy.context.active_object.select_get() and bpy.context.active_object.type == "MESH": layout.separator() column= layout.column(align= True) column.label(text= "Convert Material to:", icon= 'SHADING_RENDERED') box = column.box() materialCol = box.column(align=True) materialCol.operator('universalmaterialmap.create_template_omnipbr', text='OmniPBR') materialCol.operator('universalmaterialmap.create_template_omniglass', text='OmniGlass') class OmniBakePreferences(bpy.types.AddonPreferences): # this must match the add-on name, use '__package__' # when defining this in a submodule of a python package. bl_idname = __package__ img_name_format: bpy.props.StringProperty(name="Image format string", default="%OBJ%_%BATCH%_%BAKEMODE%_%BAKETYPE%") #Aliases diffuse_alias: bpy.props.StringProperty(name="Diffuse", default="diffuse") metal_alias: bpy.props.StringProperty(name="Metal", default="metalness") roughness_alias: bpy.props.StringProperty(name="Roughness", default="roughness") glossy_alias: bpy.props.StringProperty(name="Glossy", default="glossy") normal_alias: bpy.props.StringProperty(name="Normal", default="normal") transmission_alias: bpy.props.StringProperty(name="Transmission", default="transparency") transmissionrough_alias: bpy.props.StringProperty(name="Transmission Roughness", default="transparencyroughness") clearcoat_alias: bpy.props.StringProperty(name="Clearcost", default="clearcoat") clearcoatrough_alias: bpy.props.StringProperty(name="Clearcoat Roughness", default="clearcoatroughness") emission_alias: bpy.props.StringProperty(name="Emission", default="emission") specular_alias: bpy.props.StringProperty(name="Specular", default="specular") alpha_alias: bpy.props.StringProperty(name="Alpha", default="alpha") sss_alias: bpy.props.StringProperty(name="SSS", default="sss") ssscol_alias: bpy.props.StringProperty(name="SSS Colour", default="ssscol") @classmethod def reset_img_string(self): prefs = bpy.context.preferences.addons[__package__].preferences prefs.property_unset("img_name_format") bpy.ops.wm.save_userpref()
10,922
Python
37.192308
117
0.568211
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/particle_bake/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
858
Python
44.210524
74
0.7331
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/particle_bake/operators.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import time import bpy import numpy as np class MyProperties(bpy.types.PropertyGroup): deletePSystemAfterBake: bpy.props.BoolProperty( name = "Delete PS after converting", description = "Delete selected particle system after conversion", default = False ) progressBar: bpy.props.StringProperty( name = "Progress", description = "Progress of Particle Conversion", default = "RUNNING" ) animateData: bpy.props.BoolProperty( name = "Keyframe Animation", description = "Add a keyframe for each particle for each of the specified frames", default = False ) selectedStartFrame: bpy.props.IntProperty( name = "Start", description = "Frame to begin keyframes", default = 1 ) selectedEndFrame: bpy.props.IntProperty( name = "End", description = "Frame to stop keyframes", default = 3 ) # def fixEndFrame(): # particleOptions = context.particle_options # particleOptions.selectedEndFrame = particleOptions.selectedStartFrame particleSystemVisibility = [] particleSystemRender = [] def getOriginalModifiers(parent): particleSystemVisibility.clear() particleSystemRender.clear() for mod in parent.modifiers: if mod.type == 'PARTICLE_SYSTEM': particleSystemVisibility.append(mod.show_viewport) particleSystemRender.append(mod.show_render) def restoreOriginalModifiers(parent): count = 0 for mod in parent.modifiers: if mod.type == 'PARTICLE_SYSTEM': mod.show_viewport = particleSystemVisibility[count] mod.show_render = particleSystemRender[count] count+=1 def hideOtherModifiers(parent, countH): count = 0 for mod in parent.modifiers: if mod.type == 'PARTICLE_SYSTEM': if countH != count: mod.show_viewport = False count += 1 def particleSystemVisible(parent, countP): countS = 0 for mod in parent.modifiers: if mod.type == 'PARTICLE_SYSTEM': if countP == countS: return mod.show_viewport else: countS += 1 # Omni Hair Bake class PARTICLES_OT_omni_hair_bake(bpy.types.Operator): """Convert blender particles for Omni scene instancing""" bl_idname = "omni.hair_bake" bl_label = "Omni Hair Bake" bl_options = {'REGISTER', 'UNDO'} # create undo state def execute(self, context): particleOptions = context.scene.particle_options startTime= time.time() print() print("____BEGINING PARTICLE CONVERSION______") #Deselect Non-meshes for obj in bpy.context.selected_objects: if obj.type != "MESH": obj.select_set(False) print("not mesh") #Do we still have an active object? if bpy.context.active_object == None: #Pick arbitary bpy.context.view_layer.objects.active = bpy.context.selected_objects[0] for parentObj in bpy.context.selected_objects: print() print("--Staring " + parentObj.name + ":") getOriginalModifiers(parentObj) countH = 0 countP = 0 countPS = 0 showEmmiter = False hasPS = False for currentPS in parentObj.particle_systems: hideOtherModifiers(parentObj, countH) countH+=1 hasVisible = particleSystemVisible(parentObj, countP) countP+=1 if currentPS != None and hasVisible: hasPS = True bpy.ops.object.select_all(action='DESELECT') renderType = currentPS.settings.render_type emmitOrHair = currentPS.settings.type if parentObj.show_instancer_for_viewport == True: showEmmiter = True if renderType == 'OBJECT' or renderType == 'COLLECTION': count = 0 listInst = [] listInstScale = [] # For Object Instances if renderType == 'OBJECT': instObj = currentPS.settings.instance_object # Duplicate Instanced Object dupInst = instObj.copy() bpy.context.collection.objects.link(dupInst) dupInst.select_set(True) dupInst.location = (0,0,0) bpy.ops.object.move_to_collection(collection_index=0, is_new=True, new_collection_name="INST_"+str(dupInst.name)) dupInst.select_set(False) count += 1 listInst.append(dupInst) listInstScale.append(instObj.scale) # For Collection Instances if renderType == 'COLLECTION': instCol = currentPS.settings.instance_collection.objects countW = 0 weight = 1 for obj in instCol: # Duplicate Instanced Object dupInst = obj.copy() bpy.context.collection.objects.link(dupInst) dupInst.select_set(True) dupInst.location = (0,0,0) bpy.ops.object.move_to_collection(collection_index=0, is_new=True, new_collection_name="INST_"+str(dupInst.name)) dupInst.select_set(False) if parentObj.particle_systems.active.settings.use_collection_count: weight = currentPS.settings.instance_weights[countW].count print("Instance Count: " + str(weight)) for i in range(weight): count += 1 listInst.append(dupInst) listInstScale.append(obj.scale) countW += 1 # For Path Instances *NOT SUPPORTED if renderType == 'PATH': print("path no good") return {'FINISHED'} if renderType == 'NONE': print("no instances") return {'FINISHED'} #DOES NOTHING RIGHT NOW #if overwriteExsisting: #bpy.ops.outliner.delete(hierarchy=True) # Variables parentObj.select_set(True) parentCollection = parentObj.users_collection[0] nameP = parentObj.particle_systems[countPS].name # get name of object's particle system # Create Empty as child o = bpy.data.objects.new( "empty", None) o.name = "EM_" + nameP o.parent = parentObj parentCollection.objects.link( o ) # FOR ANIMATED EMITTER DATA if particleOptions.animateData and emmitOrHair == 'EMITTER': print("--ANIMATED EMITTER--") #Prep for Keyframing collectionInstances = [] # Calculate Dependency Graph degp = bpy.context.evaluated_depsgraph_get() # Evaluate the depsgraph (Important step) particle_systems = parentObj.evaluated_get(degp).particle_systems # All particles of selected particle system activePS = particle_systems[countPS] particles = activePS.particles # Total Particles totalParticles = len(particles) #Currently does NOT work # if activePS.type == 'HAIR': # hairLength = particles[0].hair_length # print(hairLength) # print(bpy.types.ParticleHairKey.co_object(parentObj,parentObj.modifiers[0], particles[0])) # key = particles[0].hair_keys # print(key) # coo = key.co # print(coo) # print(particles[0].location) #Beginings of supporting use random, requires more thought # obInsttt = parentObj.evaluated_get(degp).object_instances # for i in obInsttt: # obj = i.object # print(obj.name) # for obj in degp.object_instances: # print(obj.instance_object) # print(obj.particle_system) # Handle instances for construction of scene collections **Fast** for i in range(totalParticles): childObj = particles[i] calculateChild = False if childObj.birth_time <= particleOptions.selectedEndFrame and childObj.die_time > particleOptions.selectedStartFrame: calculateChild = True if calculateChild: modInst = i % count #Works for "use count" but not "pick random" dupColName = str(listInst[modInst].users_collection[0].name) #Create Collection Instance source_collection = bpy.data.collections[dupColName] instance_obj = bpy.data.objects.new( name= "Inst_" + listInst[modInst].name + "." + str(i), object_data=None ) instance_obj.empty_display_type = 'SINGLE_ARROW' instance_obj.empty_display_size = .1 instance_obj.instance_collection = source_collection instance_obj.instance_type = 'COLLECTION' parentCollection.objects.link(instance_obj) instance_obj.parent = o instance_obj.matrix_parent_inverse = o.matrix_world.inverted() collectionInstances.append(instance_obj) print("Using " + str(len(collectionInstances))) print("Out of " + str(totalParticles) + " instances") collectionCount = len(collectionInstances) startFrame = particleOptions.selectedStartFrame endFrame = particleOptions.selectedEndFrame #Do we need to swap start and end frame? if particleOptions.selectedStartFrame > particleOptions.selectedEndFrame: endFrame = startFrame startFrame = particleOptions.selectedEndFrame for frame in range(startFrame, endFrame + 1): print("frame = " + str(frame)) bpy.context.scene.frame_current = frame # Calculate Dependency Graph for each frame degp = bpy.context.evaluated_depsgraph_get() particle_systems = parentObj.evaluated_get(degp).particle_systems particles = particle_systems[countPS].particles for i in range(collectionCount): activeCol = collectionInstances[i] activeDup = particles[i] #Keyframe Visibility, Scale, Location, and Rotation if activeDup.alive_state == 'UNBORN' or activeDup.alive_state == 'DEAD': activeCol.scale = (0,0,0) activeCol.keyframe_insert(data_path='scale') activeCol.hide_viewport = True activeCol.hide_render = True activeCol.keyframe_insert("hide_viewport") activeCol.keyframe_insert("hide_render") else: activeCol.hide_viewport = False activeCol.hide_render = False scale = activeDup.size activeCol.location = activeDup.location activeCol.rotation_mode = 'QUATERNION' activeCol.rotation_quaternion = activeDup.rotation activeCol.rotation_mode = 'XYZ' activeCol.scale = (scale, scale, scale) activeCol.keyframe_insert(data_path='location') activeCol.keyframe_insert(data_path='rotation_euler') activeCol.keyframe_insert(data_path='scale') activeCol.keyframe_insert("hide_viewport") activeCol.keyframe_insert("hide_render") # FOR ANIMATED HAIR DATA elif particleOptions.animateData and emmitOrHair == 'HAIR': print("--ANIMATED HAIR--") #Prep for Keyframing bpy.ops.object.duplicates_make_real(use_base_parent=True, use_hierarchy=True) # bake particles dups = bpy.context.selected_objects lengthDups = len(dups) collectionInstances = [] # Handle instances for construction of scene collections **Fast** for i in range(lengthDups): childObj = dups.pop(0) modInst = i % count #Works for "use count" but not "pick random" dupColName = str(listInst[modInst].users_collection[0].name) #Create Collection Instance source_collection = bpy.data.collections[dupColName] instance_obj = bpy.data.objects.new( name= "Inst_" + childObj.name, object_data=None ) instance_obj.empty_display_type = 'SINGLE_ARROW' instance_obj.empty_display_size = .1 instance_obj.instance_collection = source_collection instance_obj.instance_type = 'COLLECTION' parentCollection.objects.link(instance_obj) instance_obj.parent = o bpy.data.objects.remove(childObj, do_unlink=True) collectionInstances.append(instance_obj) print(str(len(collectionInstances)) + " instances") collectionCount = len(collectionInstances) startFrame = particleOptions.selectedStartFrame endFrame = particleOptions.selectedEndFrame #Do we need to swap start and end frame? if particleOptions.selectedStartFrame > particleOptions.selectedEndFrame: endFrame = startFrame startFrame = particleOptions.selectedEndFrame for frame in range(startFrame, endFrame + 1): print("frame = " + str(frame)) bpy.context.scene.frame_current = frame # Calculate hairs for each frame parentObj.select_set(True) bpy.ops.object.duplicates_make_real(use_base_parent=True, use_hierarchy=True) # bake particles tempdups = bpy.context.selected_objects for i in range(collectionCount): activeDup = tempdups.pop(0) activeCol = collectionInstances[i] #Keyframe Scale, Location, and Rotation activeCol.location = activeDup.location activeCol.rotation_euler = activeDup.rotation_euler activeCol.scale = activeDup.scale activeCol.keyframe_insert(data_path='location') activeCol.keyframe_insert(data_path='rotation_euler') activeCol.keyframe_insert(data_path='scale') bpy.data.objects.remove(activeDup, do_unlink=True) # FOR SINGLE FRAME CONVERSION else: print("--SINGLE FRAME--") bpy.ops.object.duplicates_make_real(use_base_parent=True, use_hierarchy=True) # bake particles dups = bpy.context.selected_objects lengthDups = len(dups) # Handle instances for construction of scene collections **Fast** for i in range(lengthDups): childObj = dups.pop(0) modInst = i % count dupColName = str(listInst[modInst].users_collection[0].name) loc=childObj.location rot=childObj.rotation_euler newScale = np.divide(childObj.scale, listInstScale[modInst]) #Create Collection Instance source_collection = bpy.data.collections[dupColName] instance_obj = bpy.data.objects.new( name= "Inst_" + childObj.name, object_data=None ) instance_obj.empty_display_type = 'SINGLE_ARROW' instance_obj.empty_display_size = .1 instance_obj.instance_collection = source_collection instance_obj.instance_type = 'COLLECTION' instance_obj.location = loc instance_obj.rotation_euler = rot instance_obj.scale = newScale parentCollection.objects.link(instance_obj) instance_obj.parent = o bpy.data.objects.remove(childObj, do_unlink=True) for obj in listInst: bpy.context.view_layer.layer_collection.children[obj.users_collection[0].name].exclude = True #Make parent object active object again parentObj.select_set(True) bpy.context.view_layer.objects.active = parentObj else: print("Must be object or collection instance") else: print("Object has no active particle system") restoreOriginalModifiers(parentObj) countPS += 1 #Handle PS after converting if particleOptions.deletePSystemAfterBake: if showEmmiter == False and hasPS == True: bpy.context.active_object.hide_render = True bpy.context.active_object.hide_set(True) countI = 0 for ps in range(len(parentObj.particle_systems)): if particleSystemVisibility[ps] == True: parentObj.particle_systems.active_index = countI bpy.ops.object.particle_system_remove() else: countI+=1 else: countI = 0 for mod in parentObj.modifiers: if mod.type == 'PARTICLE_SYSTEM': mod.show_viewport = False if particleSystemVisibility[countI] == True: mod.show_render = False countI+=1 print ("My program took", time.time() - startTime, " seconds to run") # run time return {'FINISHED'}
23,439
Python
46.258064
150
0.462477
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/material_bake/material_setup.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import bpy from . import functions from .data import MasterOperation def find_node_from_label(label, nodes): for node in nodes: if node.label == label: return node return False def find_isocket_from_identifier(idname, node): for inputsocket in node.inputs: if inputsocket.identifier == idname: return inputsocket return False def find_osocket_from_identifier(idname, node): for outputsocket in node.outputs: if outputsocket.identifier == idname: return outputsocket return False def make_link(f_node_label, f_node_ident, to_node_label, to_node_ident, nodetree): fromnode = find_node_from_label(f_node_label, nodetree.nodes) if(fromnode == False): return False fromsocket = find_osocket_from_identifier(f_node_ident, fromnode) tonode = find_node_from_label(to_node_label, nodetree.nodes) if(tonode == False): return False tosocket = find_isocket_from_identifier(to_node_ident, tonode) nodetree.links.new(fromsocket, tosocket) return True def wipe_labels(nodes): for node in nodes: node.label = "" def get_image_from_tag(thisbake, objname): current_bake_op = MasterOperation.current_bake_operation global_mode = current_bake_op.bake_mode objname = functions.untrunc_if_needed(objname) batch_name = bpy.context.scene.batchName result = [] result = [img for img in bpy.data.images if\ ("SB_objname" in img and img["SB_objname"] == objname) and\ ("SB_batch" in img and img["SB_batch"] == batch_name) and\ ("SB_globalmode" in img and img["SB_globalmode"] == global_mode) and\ ("SB_thisbake" in img and img["SB_thisbake"] == thisbake)\ ] if len(result) > 0: return result[0] functions.printmsg(f"ERROR: No image with matching tag ({thisbake}) found for object {objname}") return False def create_principled_setup(nodetree, obj): functions.printmsg("Creating principled material") nodes = nodetree.nodes obj_name = obj.name.replace("_OmniBake", "") obj.active_material.cycles.displacement_method = 'BOTH' #First we wipe out any existing nodes for node in nodes: nodes.remove(node) # Node Frame node = nodes.new("NodeFrame") node.location = (0,0) node.use_custom_color = True node.color = (0.149763, 0.214035, 0.0590617) #Now create the Principled BSDF pnode = nodes.new("ShaderNodeBsdfPrincipled") pnode.location = (-25, 335) pnode.label = "pnode" pnode.use_custom_color = True pnode.color = (0.3375297784805298, 0.4575316309928894, 0.08615386486053467) pnode.parent = nodes["Frame"] #And the output node node = nodes.new("ShaderNodeOutputMaterial") node.location = (500, 200) node.label = "monode" node.show_options = False node.parent = nodes["Frame"] #----------------------------------------------------------------- #Node Image texture types Types if(bpy.context.scene.selected_col): image = get_image_from_tag("diffuse", obj_name) node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, 250) node.label = "col_tex" node.image = image node.parent = nodes["Frame"] if(bpy.context.scene.selected_sss): node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, 210) node.label = "sss_tex" image = get_image_from_tag("sss", obj_name) node.image = image node.parent = nodes["Frame"] if(bpy.context.scene.selected_ssscol): node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, 170) node.label = "ssscol_tex" image = get_image_from_tag("ssscol", obj_name) node.image = image node.parent = nodes["Frame"] if(bpy.context.scene.selected_metal): node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, 130) node.label = "metal_tex" image = get_image_from_tag("metalness", obj_name) node.image = image node.parent = nodes["Frame"] if(bpy.context.scene.selected_specular): node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, 90) node.label = "specular_tex" image = get_image_from_tag("specular", obj_name) node.image = image node.parent = nodes["Frame"] if(bpy.context.scene.selected_rough): node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, 50) node.label = "roughness_tex" image = get_image_from_tag("roughness", obj_name) node.image = image node.parent = nodes["Frame"] if(bpy.context.scene.selected_trans): node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, -90) node.label = "transmission_tex" image = get_image_from_tag("transparency", obj_name) node.image = image node.parent = nodes["Frame"] if(bpy.context.scene.selected_transrough): node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, -130) node.label = "transmissionrough_tex" image = get_image_from_tag("transparencyroughness", obj_name) node.image = image node.parent = nodes["Frame"] if(bpy.context.scene.selected_emission): node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, -170) node.label = "emission_tex" image = get_image_from_tag("emission", obj_name) node.image = image node.parent = nodes["Frame"] if(bpy.context.scene.selected_alpha): node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, -210) node.label = "alpha_tex" image = get_image_from_tag("alpha", obj_name) node.image = image node.parent = nodes["Frame"] if(bpy.context.scene.selected_normal): node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, -318.7) node.label = "normal_tex" image = get_image_from_tag("normal", obj_name) node.image = image node.parent = nodes["Frame"] #----------------------------------------------------------------- # Additional normal map node for normal socket if(bpy.context.scene.selected_normal): node = nodes.new("ShaderNodeNormalMap") node.location = (-220, -240) node.label = "normalmap" node.show_options = False node.parent = nodes["Frame"] #----------------------------------------------------------------- make_link("emission_tex", "Color", "pnode", "Emission", nodetree) make_link("col_tex", "Color", "pnode", "Base Color", nodetree) make_link("metal_tex", "Color", "pnode", "Metallic", nodetree) make_link("roughness_tex", "Color", "pnode", "Roughness", nodetree) make_link("transmission_tex", "Color", "pnode", "Transmission", nodetree) make_link("transmissionrough_tex", "Color", "pnode", "Transmission Roughness", nodetree) make_link("normal_tex", "Color", "normalmap", "Color", nodetree) make_link("normalmap", "Normal", "pnode", "Normal", nodetree) make_link("specular_tex", "Color", "pnode", "Specular", nodetree) make_link("alpha_tex", "Color", "pnode", "Alpha", nodetree) make_link("sss_tex", "Color", "pnode", "Subsurface", nodetree) make_link("ssscol_tex", "Color", "pnode", "Subsurface Color", nodetree) make_link("pnode", "BSDF", "monode", "Surface", nodetree) #--------------------------------------------------- wipe_labels(nodes) node = nodes["Frame"] node.label = "OMNI PBR"
8,828
Python
33.088803
100
0.608518
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/material_bake/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
858
Python
44.210524
74
0.7331
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/material_bake/data.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. from .bake_operation import bakestolist class MasterOperation: current_bake_operation = None total_bake_operations = 0 this_bake_operation_num = 0 orig_UVs_dict = {} baked_textures = [] prepared_mesh_objects = [] batch_name = "" orig_objects = [] orig_active_object = "" orig_sample_count = 0 @staticmethod def clear(): # Master variables called throughout bake process MasterOperation.orig_UVs_dict = {} MasterOperation.total_bake_operations = 0 MasterOperation.current_bake_operation = None MasterOperation.this_bake_operation_num = 0 MasterOperation.prepared_mesh_objects = [] MasterOperation.baked_textures = [] MasterOperation.batch_name = "" # Variables to reset your scene to what it was before bake. MasterOperation.orig_objects = [] MasterOperation.orig_active_object = "" MasterOperation.orig_sample_count = 0 return True class BakeOperation: #Constants PBR = "pbr" def __init__(self): #Mapping of object name to active UVs self.bake_mode = BakeOperation.PBR #So the example in the user prefs will work self.bake_objects = [] self.active_object = None #normal self.uv_mode = "normal" #pbr stuff self.pbr_selected_bake_types = [] def assemble_pbr_bake_list(self): self.pbr_selected_bake_types = bakestolist()
2,334
Python
28.935897
86
0.667095
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/material_bake/operators.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import bpy import sys import subprocess import os from .bake_operation import BakeStatus, bakestolist from .data import MasterOperation, BakeOperation from . import functions from . import bakefunctions from .background_bake import bgbake_ops from pathlib import Path import tempfile class OBJECT_OT_omni_bake_mapbake(bpy.types.Operator): """Start the baking process""" bl_idname = "object.omni_bake_mapbake" bl_label = "Bake" bl_options = {'REGISTER', 'UNDO'} # create undo state def execute(self, context): def commence_bake(needed_bake_modes): #Prepare the BakeStatus tracker for progress bar num_of_objects = 0 num_of_objects = len(bpy.context.selected_objects) total_maps = 0 for need in needed_bake_modes: if need == BakeOperation.PBR: total_maps+=(bakestolist(justcount=True) * num_of_objects) BakeStatus.total_maps = total_maps #Clear the MasterOperation stuff MasterOperation.clear() #Need to know the total operations MasterOperation.total_bake_operations = len(needed_bake_modes) #Master list of all ops bops = [] for need in needed_bake_modes: #Create operation bop = BakeOperation() #Set master level attributes #------------------------------- bop.bake_mode = need #------------------------------- bops.append(bop) functions.printmsg(f"Created operation for {need}") #Run queued operations for bop in bops: MasterOperation.this_bake_operation_num+=1 MasterOperation.current_bake_operation = bop if bop.bake_mode == BakeOperation.PBR: functions.printmsg("Running PBR bake") bakefunctions.doBake() return True ######################TEMP############################################### needed_bake_modes = [] needed_bake_modes.append(BakeOperation.PBR) #Clear the progress stuff BakeStatus.current_map = 0 BakeStatus.total_maps = 0 #If we have been called in background mode, just get on with it. Checks should be done. if "--background" in sys.argv: if "OmniBake_Bakes" in bpy.data.collections: #Remove any prior baked objects bpy.data.collections.remove(bpy.data.collections["OmniBake_Bakes"]) #Bake commence_bake(needed_bake_modes) self.report({"INFO"}, "Bake complete") return {'FINISHED'} functions.deselect_all_not_mesh() #We are in foreground, do usual checks result = True for need in needed_bake_modes: if not functions.startingChecks(bpy.context.selected_objects, need): result = False if not result: return {"CANCELLED"} #If the user requested background mode, fire that up now and exit if bpy.context.scene.bgbake == "bg": bpy.ops.wm.save_mainfile() filepath = filepath = bpy.data.filepath process = subprocess.Popen( [bpy.app.binary_path, "--background",filepath, "--python-expr",\ "import bpy;\ import os;\ from pathlib import Path;\ savepath=Path(bpy.data.filepath).parent / (str(os.getpid()) + \".blend\");\ bpy.ops.wm.save_as_mainfile(filepath=str(savepath), check_existing=False);\ bpy.ops.object.omni_bake_mapbake();"], shell=False) bgbake_ops.bgops_list.append([process, bpy.context.scene.prepmesh, bpy.context.scene.hidesourceobjects]) self.report({"INFO"}, "Background bake process started") return {'FINISHED'} #If we are doing this here and now, get on with it #Create a bake operation commence_bake(needed_bake_modes) self.report({"INFO"}, "Bake complete") return {'FINISHED'} #--------------------BACKGROUND BAKE---------------------------------- class OBJECT_OT_omni_bake_bgbake_status(bpy.types.Operator): bl_idname = "object.omni_bake_bgbake_status" bl_label = "Check on the status of bakes running in the background" def execute(self, context): msg_items = [] #Display remaining if len(bgbake_ops.bgops_list) == 0: msg_items.append("No background bakes are currently running") else: msg_items.append(f"--------------------------") for p in bgbake_ops.bgops_list: t = Path(tempfile.gettempdir()) t = t / f"OmniBake_Bgbake_{str(p[0].pid)}" try: with open(str(t), "r") as progfile: progress = progfile.readline() except: #No file yet, as no bake operation has completed yet. Holding message progress = 0 msg_items.append(f"RUNNING: Process ID: {str(p[0].pid)} - Progress {progress}%") msg_items.append(f"--------------------------") functions.ShowMessageBox(msg_items, "Background Bake Status(es)") return {'FINISHED'} class OBJECT_OT_omni_bake_bgbake_import(bpy.types.Operator): bl_idname = "object.omni_bake_bgbake_import" bl_label = "Import baked objects previously baked in the background" bl_options = {'REGISTER', 'UNDO'} # create undo state def execute(self, context): if bpy.context.mode != "OBJECT": self.report({"ERROR"}, "You must be in object mode") return {'CANCELLED'} for p in bgbake_ops.bgops_list_finished: savepath = Path(bpy.data.filepath).parent pid_str = str(p[0].pid) path = savepath / (pid_str + ".blend") path = str(path) + "\\Collection\\" #Record the objects and collections before append (as append doesn't give us a reference to the new stuff) functions.spot_new_items(initialise=True, item_type="objects") functions.spot_new_items(initialise=True, item_type="collections") functions.spot_new_items(initialise=True, item_type="images") #Append bpy.ops.wm.append(filename="OmniBake_Bakes", directory=path, use_recursive=False, active_collection=False) #If we didn't actually want the objects, delete them if not p[1]: #Delete objects we just imported (leaving only textures) for obj_name in functions.spot_new_items(initialise=False, item_type = "objects"): bpy.data.objects.remove(bpy.data.objects[obj_name]) for col_name in functions.spot_new_items(initialise=False, item_type = "collections"): bpy.data.collections.remove(bpy.data.collections[col_name]) #If we have to hide the source objects, do it if p[2]: #Get the newly introduced objects: objects_before_names = functions.spot_new_items(initialise=False, item_type="objects") for obj_name in objects_before_names: #Try this in case there are issues with long object names.. better than a crash try: bpy.data.objects[obj_name.replace("_Baked", "")].hide_set(True) except: pass #Delete the temp blend file try: os.remove(str(savepath / pid_str) + ".blend") os.remove(str(savepath / pid_str) + ".blend1") except: pass #Clear list for next time bgbake_ops.bgops_list_finished = [] #Confirm back to user self.report({"INFO"}, "Import complete") messagelist = [] messagelist.append(f"{len(functions.spot_new_items(initialise=False, item_type='objects'))} objects imported") messagelist.append(f"{len(functions.spot_new_items(initialise=False, item_type='images'))} textures imported") functions.ShowMessageBox(messagelist, "Import complete", icon = 'INFO') #If we imported an image, and we already had an image with the same name, get rid of the original in favour of the imported new_images_names = functions.spot_new_items(initialise=False, item_type="images") #Find any .001s for imgname in new_images_names: try: int(imgname[-3:]) #Delete the existing version bpy.data.images.remove(bpy.data.images[imgname[0:-4]]) #Rename our version bpy.data.images[imgname].name = imgname[0:-4] except ValueError: pass return {'FINISHED'} class OBJECT_OT_omni_bake_bgbake_clear(bpy.types.Operator): """Delete the background bakes because you don't want to import them into Blender. NOTE: If you chose to save bakes or FBX externally, these are safe and NOT deleted. This is just if you don't want to import into this Blender session""" bl_idname = "object.omni_bake_bgbake_clear" bl_label = "" bl_options = {'REGISTER', 'UNDO'} # create undo state def execute(self, context): savepath = Path(bpy.data.filepath).parent for p in bgbake_ops.bgops_list_finished: pid_str = str(p[0].pid) try: os.remove(str(savepath / pid_str) + ".blend") os.remove(str(savepath / pid_str) + ".blend1") except: pass bgbake_ops.bgops_list_finished = [] return {'FINISHED'}
11,531
Python
38.493151
240
0.540976
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/material_bake/bake_operation.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import bpy # Bake helper method def bakestolist(justcount = False): #Assemble properties into list selectedbakes = [] selectedbakes.append("diffuse") if bpy.context.scene.selected_col else False selectedbakes.append("metalness") if bpy.context.scene.selected_metal else False selectedbakes.append("roughness") if bpy.context.scene.selected_rough else False selectedbakes.append("normal") if bpy.context.scene.selected_normal else False selectedbakes.append("transparency") if bpy.context.scene.selected_trans else False selectedbakes.append("transparencyroughness") if bpy.context.scene.selected_transrough else False selectedbakes.append("emission") if bpy.context.scene.selected_emission else False selectedbakes.append("specular") if bpy.context.scene.selected_specular else False selectedbakes.append("alpha") if bpy.context.scene.selected_alpha else False selectedbakes.append("sss") if bpy.context.scene.selected_sss else False selectedbakes.append("ssscol") if bpy.context.scene.selected_ssscol else False if justcount: return len(selectedbakes) else: return selectedbakes class BakeStatus: total_maps = 0 current_map = 0
2,095
Python
40.919999
101
0.741766
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/material_bake/bakefunctions.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import bpy from . import functions import sys from .bake_operation import BakeStatus from .data import MasterOperation, BakeOperation def optimize(): current_bake_op = MasterOperation.current_bake_operation MasterOperation.orig_sample_count = bpy.context.scene.cycles.samples functions.printmsg("Reducing sample count to 16 for more efficient baking") bpy.context.scene.cycles.samples = 16 return True def undo_optimize(): #Restore sample count bpy.context.scene.cycles.samples = MasterOperation.orig_sample_count def common_bake_prep(): #--------------Set Bake Operation Variables---------------------------- current_bake_op = MasterOperation.current_bake_operation functions.printmsg("================================") functions.printmsg("---------Beginning Bake---------") functions.printmsg(f"{current_bake_op.bake_mode}") functions.printmsg("================================") #Run information op_num = MasterOperation.this_bake_operation_num firstop = False lastop = False if op_num == 1: firstop = True if op_num == MasterOperation.total_bake_operations: lastop = True #If this is a pbr bake, gather the selected maps if current_bake_op.bake_mode in {BakeOperation.PBR}: current_bake_op.assemble_pbr_bake_list() #Record batch name MasterOperation.batch_name = bpy.context.scene.batchName #Set values based on viewport selection current_bake_op.orig_objects = bpy.context.selected_objects.copy() current_bake_op.orig_active_object = bpy.context.active_object current_bake_op.bake_objects = bpy.context.selected_objects.copy() current_bake_op.active_object = bpy.context.active_object current_bake_op.orig_engine = bpy.context.scene.render.engine #Record original UVs for everyone if firstop: for obj in current_bake_op.bake_objects: try: MasterOperation.orig_UVs_dict[obj.name] = obj.data.uv_layers.active.name except AttributeError: MasterOperation.orig_UVs_dict[obj.name] = False #Record the rendering engine if firstop: MasterOperation.orig_engine = bpy.context.scene.render.engine current_bake_op.uv_mode = "normal" #---------------------------------------------------------------------- #Force it to cycles bpy.context.scene.render.engine = "CYCLES" bpy.context.scene.render.bake.use_selected_to_active = False functions.printmsg(f"Selected to active is now {bpy.context.scene.render.bake.use_selected_to_active}") #If the user doesn't have a GPU, but has still set the render device to GPU, set it to CPU if not bpy.context.preferences.addons["cycles"].preferences.has_active_device(): bpy.context.scene.cycles.device = "CPU" #Clear the trunc num for this session functions.trunc_num = 0 functions.trunc_dict = {} #Turn off that dam use clear. bpy.context.scene.render.bake.use_clear = False #Do what we are doing with UVs (only if we are the primary op) if firstop: functions.processUVS() #Optimize optimize() #Make sure the normal y setting is at default bpy.context.scene.render.bake.normal_g = "POS_Y" return True def common_bake_finishing(): #Run information current_bake_op = MasterOperation.current_bake_operation op_num = MasterOperation.this_bake_operation_num firstop = False lastop = False if op_num == 1: firstop = True if op_num == MasterOperation.total_bake_operations: lastop = True #Restore the original rendering engine if lastop: bpy.context.scene.render.engine = MasterOperation.orig_engine undo_optimize() #If prep mesh, or save object is selected, or running in the background, then do it #We do this on primary run only if firstop: if(bpy.context.scene.prepmesh or "--background" in sys.argv): functions.prepObjects(current_bake_op.bake_objects, current_bake_op.bake_mode) #If the user wants it, restore the original active UV map so we don't confuse anyone functions.restore_Original_UVs() #Restore the original object selection so we don't confuse anyone bpy.ops.object.select_all(action="DESELECT") for obj in current_bake_op.orig_objects: obj.select_set(True) bpy.context.view_layer.objects.active = current_bake_op.orig_active_object #Hide all the original objects if bpy.context.scene.prepmesh and bpy.context.scene.hidesourceobjects and lastop: for obj in current_bake_op.bake_objects: obj.hide_set(True) #Delete placeholder material if lastop and "OmniBake_Placeholder" in bpy.data.materials: bpy.data.materials.remove(bpy.data.materials["OmniBake_Placeholder"]) if "--background" in sys.argv: bpy.ops.wm.save_mainfile() def doBake(): current_bake_op = MasterOperation.current_bake_operation #Do the prep we need to do for all bake types common_bake_prep() #Loop over the bake modes we are using def doBake_actual(): IMGNAME = "" for thisbake in current_bake_op.pbr_selected_bake_types: for obj in current_bake_op.bake_objects: #Reset the already processed list mats_done = [] functions.printmsg(f"Baking object: {obj.name}") #Truncate if needed from this point forward OBJNAME = functions.trunc_if_needed(obj.name) #Create the image we need for this bake (Delete if exists) IMGNAME = functions.gen_image_name(obj.name, thisbake) functions.create_Images(IMGNAME, thisbake, obj.name) #Prep the materials one by one materials = obj.material_slots for matslot in materials: mat = bpy.data.materials.get(matslot.name) if mat.name in mats_done: functions.printmsg(f"Skipping material {mat.name}, already processed") #Skip this loop #We don't want to process any materials more than once or bad things happen continue else: mats_done.append(mat.name) #Make sure we are using nodes if not mat.use_nodes: functions.printmsg(f"Material {mat.name} wasn't using nodes. Have enabled nodes") mat.use_nodes = True nodetree = mat.node_tree nodes = nodetree.nodes #Take a copy of material to restore at the end of the process functions.backupMaterial(mat) #Create the image node and set to the bake texutre we are using imgnode = nodes.new("ShaderNodeTexImage") imgnode.image = bpy.data.images[IMGNAME] imgnode.label = "OmniBake" #Remove all disconnected nodes so don't interfere with typing the material functions.removeDisconnectedNodes(nodetree) #Use additional shader types functions.useAdditionalShaderTypes(nodetree, nodes) #Normal and emission bakes require no further material prep. Just skip the rest if(thisbake != "normal" and thisbake != "emission"): #Work out what type of material we are dealing with here and take correct action mat_type = functions.getMatType(nodetree) if(mat_type == "MIX"): functions.setup_mix_material(nodetree, thisbake) elif(mat_type == "PURE_E"): functions.setup_pure_e_material(nodetree, thisbake) elif(mat_type == "PURE_P"): functions.setup_pure_p_material(nodetree, thisbake) #Last action before leaving this material, make the image node selected and active functions.deselectAllNodes(nodes) imgnode.select = True nodetree.nodes.active = imgnode #Select only this object functions.selectOnlyThis(obj) #We are done with this image, set colour space functions.set_image_internal_col_space(bpy.data.images[IMGNAME], thisbake) #Bake the object for this bake mode functions.bakeoperation(thisbake, bpy.data.images[IMGNAME]) #Update tracking BakeStatus.current_map+=1 functions.printmsg(f"Bake maps {BakeStatus.current_map} of {BakeStatus.total_maps} complete") functions.write_bake_progress(BakeStatus.current_map, BakeStatus.total_maps) #Restore the original materials functions.printmsg("Restoring original materials") functions.restoreAllMaterials() functions.printmsg("Restore complete") #Last thing we do with this image is scale it functions.sacle_image_if_needed(bpy.data.images[IMGNAME]) #Do the bake at least once doBake_actual() #Finished baking. Perform wind down actions common_bake_finishing()
10,620
Python
36.932143
109
0.608004
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/material_bake/functions.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. from pathlib import Path from ..ui import OmniBakePreferences import bpy import os import sys import tempfile from . import material_setup from .data import MasterOperation #Global variables psocketname = { "diffuse": "Base Color", "metalness": "Metallic", "roughness": "Roughness", "normal": "Normal", "transparency": "Transmission", "transparencyroughness": "Transmission Roughness", "specular": "Specular", "alpha": "Alpha", "sss": "Subsurface", "ssscol": "Subsurface Color", "displacement": "Displacement" } def printmsg(msg): print(f"BAKE: {msg}") def gen_image_name(obj_name, baketype): current_bake_op = MasterOperation.current_bake_operation #First, let's get the format string we are working with prefs = bpy.context.preferences.addons[OmniBakePreferences.bl_idname].preferences image_name = prefs.img_name_format #The easy ones image_name = image_name.replace("%OBJ%", obj_name) image_name = image_name.replace("%BATCH%", bpy.context.scene.batchName) #Bake mode image_name = image_name.replace("%BAKEMODE%", current_bake_op.bake_mode) #The hard ones if baketype == "diffuse": image_name = image_name.replace("%BAKETYPE%", prefs.diffuse_alias) elif baketype == "metalness": image_name = image_name.replace("%BAKETYPE%", prefs.metal_alias) elif baketype == "roughness": image_name = image_name.replace("%BAKETYPE%", prefs.roughness_alias) elif baketype == "normal": image_name = image_name.replace("%BAKETYPE%", prefs.normal_alias) elif baketype == "transparency": image_name = image_name.replace("%BAKETYPE%", prefs.transmission_alias) elif baketype == "transparencyroughness": image_name = image_name.replace("%BAKETYPE%", prefs.transmissionrough_alias) elif baketype == "emission": image_name = image_name.replace("%BAKETYPE%", prefs.emission_alias) elif baketype == "specular": image_name = image_name.replace("%BAKETYPE%", prefs.specular_alias) elif baketype == "alpha": image_name = image_name.replace("%BAKETYPE%", prefs.alpha_alias) elif baketype == "sss": image_name = image_name.replace("%BAKETYPE%", prefs.sss_alias) elif baketype == "ssscol": image_name = image_name.replace("%BAKETYPE%", prefs.ssscol_alias) #Displacement is not currently Implemented elif baketype == "displacement": image_name = image_name.replace("%BAKETYPE%", prefs.displacement_alias) else: image_name = image_name.replace("%BAKETYPE%", baketype) return image_name def removeDisconnectedNodes(nodetree): nodes = nodetree.nodes #Loop through nodes repeat = False for node in nodes: if node.type == "BSDF_PRINCIPLED" and len(node.outputs[0].links) == 0: #Not a player, delete node nodes.remove(node) repeat = True elif node.type == "EMISSION" and len(node.outputs[0].links) == 0: #Not a player, delete node nodes.remove(node) repeat = True elif node.type == "MIX_SHADER" and len(node.outputs[0].links) == 0: #Not a player, delete node nodes.remove(node) repeat = True elif node.type == "ADD_SHADER" and len(node.outputs[0].links) == 0: #Not a player, delete node nodes.remove(node) repeat = True #Displacement is not currently Implemented elif node.type == "DISPLACEMENT" and len(node.outputs[0].links) == 0: #Not a player, delete node nodes.remove(node) repeat = True #If we removed any nodes, we need to do this again if repeat: removeDisconnectedNodes(nodetree) def backupMaterial(mat): dup = mat.copy() dup.name = mat.name + "_OmniBake" def restoreAllMaterials(): #Not efficient but, if we are going to do things this way, we need to loop over every object in the scene dellist = [] for obj in bpy.data.objects: for slot in obj.material_slots: origname = slot.name #Try to set to the corresponding material that was the backup try: slot.material = bpy.data.materials[origname + "_OmniBake"] #If not already on our list, log the original material (that we messed with) for mass deletion if origname not in dellist: dellist.append(origname) except KeyError: #Not been backed up yet. Must not have processed an object with that material yet pass #Delete the unused materials for matname in dellist: bpy.data.materials.remove(bpy.data.materials[matname]) #Rename all materials to the original name, leaving us where we started for mat in bpy.data.materials: if "_OmniBake" in mat.name: mat.name = mat.name.replace("_OmniBake", "") def create_Images(imgname, thisbake, objname): #thisbake is subtype e.g. diffuse, ao, etc. current_bake_op = MasterOperation.current_bake_operation global_mode = current_bake_op.bake_mode batch = MasterOperation.batch_name printmsg(f"Creating image {imgname}") #Get the image height and width from the interface IMGHEIGHT = bpy.context.scene.imgheight IMGWIDTH = bpy.context.scene.imgwidth #If it already exists, remove it. if(imgname in bpy.data.images): bpy.data.images.remove(bpy.data.images[imgname]) #Create image 32 bit or not 32 bit if thisbake == "normal" : image = bpy.data.images.new(imgname, IMGWIDTH, IMGHEIGHT, float_buffer=True) else: image = bpy.data.images.new(imgname, IMGWIDTH, IMGHEIGHT, float_buffer=False) #Set tags image["SB_objname"] = objname image["SB_batch"] = batch image["SB_globalmode"] = global_mode image["SB_thisbake"] = thisbake #Always mark new images fake user when generated in the background if "--background" in sys.argv: image.use_fake_user = True #Store it at bake operation level MasterOperation.baked_textures.append(image) def deselectAllNodes(nodes): for node in nodes: node.select = False def findSocketConnectedtoP(pnode, thisbake): #Get socket name for this bake mode socketname = psocketname[thisbake] #Get socket of the pnode socket = pnode.inputs[socketname] fromsocket = socket.links[0].from_socket #Return the socket connected to the pnode return fromsocket def createdummynodes(nodetree, thisbake): #Loop through pnodes nodes = nodetree.nodes for node in nodes: if node.type == "BSDF_PRINCIPLED": pnode = node #Get socket name for this bake mode socketname = psocketname[thisbake] #Get socket of the pnode psocket = pnode.inputs[socketname] #If it has something plugged in, we can leave it here if(len(psocket.links) > 0): continue #Get value of the unconnected socket val = psocket.default_value #If this is base col or ssscol, add an RGB node and set it's value to that of the socket if(socketname == "Base Color" or socketname == "Subsurface Color"): rgb = nodetree.nodes.new("ShaderNodeRGB") rgb.outputs[0].default_value = val rgb.label = "OmniBake" nodetree.links.new(rgb.outputs[0], psocket) #If this is anything else, use a value node else: vnode = nodetree.nodes.new("ShaderNodeValue") vnode.outputs[0].default_value = val vnode.label = "OmniBake" nodetree.links.new(vnode.outputs[0], psocket) def bakeoperation(thisbake, img): printmsg(f"Beginning bake for {thisbake}") if(thisbake != "normal"): bpy.ops.object.bake(type="EMIT", save_mode="INTERNAL", use_clear=True) else: bpy.ops.object.bake(type="NORMAL", save_mode="INTERNAL", use_clear=True) #Always pack the image for now img.pack() def startingChecks(objects, bakemode): messages = [] if len(objects) == 0: messages.append("ERROR: Nothing selected for bake") #Are any of our objects hidden? for obj in objects: if (obj.hide_viewport == True) or (obj.hide_get(view_layer=bpy.context.view_layer) == True): messages.append(f"ERROR: Object '{obj.name}' is hidden in viewport (eye icon in outliner) or in the current view lawyer (computer screen icon in outliner)") #What about hidden from rendering? for obj in objects: if obj.hide_render: messages.append(f"ERROR: Object '{obj.name}' is hidden for rendering (camera icon in outliner)") #None of the objects can have zero faces for obj in objects: if len(obj.data.polygons) < 1: messages.append(f"ERROR: Object '{obj.name}' has no faces") if(bpy.context.mode != "OBJECT"): messages.append("ERROR: Not in object mode") #PBR Bake Checks for obj in objects: #Is it mesh? if obj.type != "MESH": messages.append(f"ERROR: Object {obj.name} is not mesh") #Must continue here - other checks will throw exceptions continue #Are UVs OK? if bpy.context.scene.newUVoption == False and len(obj.data.uv_layers) == 0: messages.append(f"ERROR: Object {obj.name} has no UVs, and you aren't generating new ones") continue #Are materials OK? Fix if not if not checkObjectValidMaterialConfig(obj): fix_invalid_material_config(obj) #Do all materials have valid PBR config? if bpy.context.scene.more_shaders == False: for slot in obj.material_slots: mat = slot.material result = checkMatsValidforPBR(mat) if len(result) > 0: for node_name in result: messages.append(f"ERROR: Node '{node_name}' in material '{mat.name}' on object '{obj.name}' is not valid for PBR bake. In order to use more than just Princpled, Emission, and Mix Shaders, turn on 'Use additional Shader Types'!") else: for slot in obj.material_slots: mat = slot.material result = checkExtraMatsValidforPBR(mat) if len(result) > 0: for node_name in result: messages.append(f"ERROR: Node '{node_name}' in material '{mat.name}' on object '{obj.name}' is not supported") #Let's report back if len(messages) != 0: ShowMessageBox(messages, "Errors occured", "ERROR") return False else: #If we get here then everything looks good return True #------------------------------------------ def processUVS(): current_bake_op = MasterOperation.current_bake_operation #------------------NEW UVS ------------------------------------------------------------ if bpy.context.scene.newUVoption: printmsg("We are generating new UVs") printmsg("We are unwrapping each object individually with Smart UV Project") objs = current_bake_op.bake_objects for obj in objs: if("OmniBake" in obj.data.uv_layers): obj.data.uv_layers.remove(obj.data.uv_layers["OmniBake"]) obj.data.uv_layers.new(name="OmniBake") obj.data.uv_layers["OmniBake"].active = True #Will set active object selectOnlyThis(obj) #Blender 2.91 kindly breaks Smart UV Project in object mode so... yeah... thanks bpy.ops.object.mode_set(mode="EDIT", toggle=False) #Unhide any geo that's hidden in edit mode or it'll cause issues. bpy.ops.mesh.reveal() bpy.ops.mesh.select_all(action="SELECT") bpy.ops.mesh.reveal() bpy.ops.uv.smart_project(island_margin=bpy.context.scene.unwrapmargin) bpy.ops.object.mode_set(mode="OBJECT", toggle=False) #------------------END NEW UVS ------------------------------------------------------------ else: #i.e. New UV Option was not selected printmsg("We are working with the existing UVs") if bpy.context.scene.prefer_existing_sbmap: printmsg("We are preferring existing UV maps called OmniBake. Setting them to active") for obj in current_bake_op.bake_objects: if("OmniBake" in obj.data.uv_layers): obj.data.uv_layers["OmniBake"].active = True #Before we finish, restore the original selected and active objects bpy.ops.object.select_all(action="DESELECT") for obj in current_bake_op.orig_objects: obj.select_set(True) bpy.context.view_layer.objects.active = current_bake_op.orig_active_object #Done return True def restore_Original_UVs(): current_bake_op = MasterOperation.current_bake_operation #First the bake objects for obj in current_bake_op.bake_objects: if MasterOperation.orig_UVs_dict[obj. name] != None: original_uv = MasterOperation.orig_UVs_dict[obj.name] obj.data.uv_layers.active = obj.data.uv_layers[original_uv] def setupEmissionRunThrough(nodetree, m_output_node, thisbake, ismix=False): nodes = nodetree.nodes pnode = find_pnode(nodetree) #Create emission shader emissnode = nodes.new("ShaderNodeEmission") emissnode.label = "OmniBake" #Connect to output if(ismix): #Find the existing mix node before we create a new one existing_m_node = find_mnode(nodetree) #Add a mix shader node and label it mnode = nodes.new("ShaderNodeMixShader") mnode.label = "OmniBake" #Connect new mix node to the output fromsocket = mnode.outputs[0] tosocket = m_output_node.inputs[0] nodetree.links.new(fromsocket, tosocket) #Connect new emission node to the first mix slot (leaving second empty) fromsocket = emissnode.outputs[0] tosocket = mnode.inputs[1] nodetree.links.new(fromsocket, tosocket) #If there is one, plug the factor from the original mix node into our new mix node if(len(existing_m_node.inputs[0].links) > 0): fromsocket = existing_m_node.inputs[0].links[0].from_socket tosocket = mnode.inputs[0] nodetree.links.new(fromsocket, tosocket) #If no input, add a value node set to same as the mnode factor else: val = existing_m_node.inputs[0].default_value vnode = nodes.new("ShaderNodeValue") vnode.label = "OmniBake" vnode.outputs[0].default_value = val fromsocket = vnode.outputs[0] tosocket = mnode.inputs[0] nodetree.links.new(fromsocket, tosocket) else: #Just connect our new emission to the output fromsocket = emissnode.outputs[0] tosocket = m_output_node.inputs[0] nodetree.links.new(fromsocket, tosocket) #Create dummy nodes for the socket for this bake if needed createdummynodes(nodetree, pnode, thisbake) #Connect whatever is in Principled Shader for this bakemode to the emission fromsocket = findSocketConnectedtoP(pnode, thisbake) tosocket = emissnode.inputs[0] nodetree.links.new(fromsocket, tosocket) #---------------------Node Finders--------------------------- def find_pnode(nodetree): nodes = nodetree.nodes for node in nodes: if(node.type == "BSDF_PRINCIPLED"): return node #We never found it return False def find_enode(nodetree): nodes = nodetree.nodes for node in nodes: if(node.type == "EMISSION"): return node #We never found it return False def find_mnode(nodetree): nodes = nodetree.nodes for node in nodes: if(node.type == "MIX_SHADER"): return node #We never found it return False def find_onode(nodetree): nodes = nodetree.nodes for node in nodes: if(node.type == "OUTPUT_MATERIAL"): return node #We never found it return False def checkObjectValidMaterialConfig(obj): #Firstly, check it actually has material slots if len(obj.material_slots) == 0: return False #Check the material slots all have a material assigned for slot in obj.material_slots: if slot.material == None: return False #All materials must be using nodes for slot in obj.material_slots: if slot.material.use_nodes == False: return False #If we get here, everything looks good return True def getMatType(nodetree): if (find_pnode(nodetree) and find_mnode(nodetree)): return "MIX" elif(find_pnode(nodetree)): return "PURE_P" elif(find_enode(nodetree)): return "PURE_E" else: return "INVALID" def prepObjects(objs, baketype): current_bake_op = MasterOperation.current_bake_operation printmsg("Creating prepared object") #First we prepare objectes export_objects = [] for obj in objs: #-------------Create the prepared mesh---------------------------------------- #Object might have a truncated name. Should use this if it's there objname = trunc_if_needed(obj.name) new_obj = obj.copy() new_obj.data = obj.data.copy() new_obj["SB_createdfrom"] = obj.name #clear all materials new_obj.data.materials.clear() new_obj.name = objname + "_OmniBake" #Create a collection for our baked objects if it doesn't exist if "OmniBake_Bakes" not in bpy.data.collections: c = bpy.data.collections.new("OmniBake_Bakes") bpy.context.scene.collection.children.link(c) #Make sure it's visible and enabled for current view laywer or it screws things up bpy.context.view_layer.layer_collection.children["OmniBake_Bakes"].exclude = False bpy.context.view_layer.layer_collection.children["OmniBake_Bakes"].hide_viewport = False c = bpy.data.collections["OmniBake_Bakes"] #Link object to our new collection c.objects.link(new_obj) #Append this object to the export list export_objects.append(new_obj) #---------------------------------UVS-------------------------------------- uvlayers = new_obj.data.uv_layers #If we generated new UVs, it will be called "OmniBake" and we are using that. End of. #Same if we are being called for Sketchfab upload, and last bake used new UVs if bpy.context.scene.newUVoption: pass #If there is an existing map called OmniBake, and we are preferring it, use that elif ("OmniBake" in uvlayers) and bpy.context.scene.prefer_existing_sbmap: pass #Even if we are not preferring it, if there is just one map called OmniBake, we are using that elif ("OmniBake" in uvlayers) and len(uvlayers) <2: pass #If there is an existing map called OmniBake, and we are not preferring it, it has to go #Active map becommes OmniBake elif ("OmniBake" in uvlayers) and not bpy.context.scene.prefer_existing_sbmap: uvlayers.remove(uvlayers["OmniBake"]) active_layer = uvlayers.active active_layer.name = "OmniBake" #Finally, if none of the above apply, we are just using the active map #Active map becommes OmniBake else: active_layer = uvlayers.active active_layer.name = "OmniBake" #In all cases, we can now delete everything other than OmniBake deletelist = [] for uvlayer in uvlayers: if (uvlayer.name != "OmniBake"): deletelist.append(uvlayer.name) for uvname in deletelist: uvlayers.remove(uvlayers[uvname]) #---------------------------------END UVS-------------------------------------- #Create a new material #call it same as object + batchname + baked mat = bpy.data.materials.get(objname + "_" + bpy.context.scene.batchName + "_baked") if mat is None: mat = bpy.data.materials.new(name=objname + "_" + bpy.context.scene.batchName +"_baked") # Assign it to object mat.use_nodes = True new_obj.data.materials.append(mat) #Set up the materials for each object for obj in export_objects: #Should only have one material mat = obj.material_slots[0].material nodetree = mat.node_tree material_setup.create_principled_setup(nodetree, obj) #Change object name to avoid collisions obj.name = obj.name.replace("_OmniBake", "_Baked") bpy.ops.object.select_all(action="DESELECT") for obj in export_objects: obj.select_set(state=True) if (not bpy.context.scene.prepmesh) and (not "--background" in sys.argv): #Deleted duplicated objects for obj in export_objects: bpy.data.objects.remove(obj) #Add the created objects to the bake operation list to keep track of them else: for obj in export_objects: MasterOperation.prepared_mesh_objects.append(obj) def selectOnlyThis(obj): bpy.ops.object.select_all(action="DESELECT") obj.select_set(state=True) bpy.context.view_layer.objects.active = obj def setup_pure_p_material(nodetree, thisbake): #Create dummy nodes as needed createdummynodes(nodetree, thisbake) #Create emission shader nodes = nodetree.nodes m_output_node = find_onode(nodetree) loc = m_output_node.location #Create an emission shader emissnode = nodes.new("ShaderNodeEmission") emissnode.label = "OmniBake" emissnode.location = loc emissnode.location.y = emissnode.location.y + 200 #Connect our new emission to the output fromsocket = emissnode.outputs[0] tosocket = m_output_node.inputs[0] nodetree.links.new(fromsocket, tosocket) #Connect whatever is in Principled Shader for this bakemode to the emission fromsocket = findSocketConnectedtoP(find_pnode(nodetree), thisbake) tosocket = emissnode.inputs[0] nodetree.links.new(fromsocket, tosocket) def setup_pure_e_material(nodetree, thisbake): #If baking something other than emission, mute the emission modes so they don't contaiminate our bake if thisbake != "Emission": nodes = nodetree.nodes for node in nodes: if node.type == "EMISSION": node.mute = True node.label = "OmniBakeMuted" def setup_mix_material(nodetree, thisbake): #No need to mute emission nodes. They are automuted by setting the RGBMix to black nodes = nodetree.nodes #Create dummy nodes as needed createdummynodes(nodetree, thisbake) #For every mix shader, create a mixrgb above it #Also connect the factor input to the same thing created_mix_nodes = {} for node in nodes: if node.type == "MIX_SHADER": loc = node.location rgbmix = nodetree.nodes.new("ShaderNodeMixRGB") rgbmix.label = "OmniBake" rgbmix.location = loc rgbmix.location.y = rgbmix.location.y + 200 #If there is one, plug the factor from the original mix node into our new mix node if(len(node.inputs[0].links) > 0): fromsocket = node.inputs[0].links[0].from_socket tosocket = rgbmix.inputs["Fac"] nodetree.links.new(fromsocket, tosocket) #If no input, add a value node set to same as the mnode factor else: val = node.inputs[0].default_value vnode = nodes.new("ShaderNodeValue") vnode.label = "OmniBake" vnode.outputs[0].default_value = val fromsocket = vnode.outputs[0] tosocket = rgbmix.inputs[0] nodetree.links.new(fromsocket, tosocket) #Keep a dictionary with paired shader mix node created_mix_nodes[node.name] = rgbmix.name #Loop over the RGBMix nodes that we created for node in created_mix_nodes: mshader = nodes[node] rgb = nodes[created_mix_nodes[node]] #Mshader - Socket 1 #First, check if there is anything plugged in at all if len(mshader.inputs[1].links) > 0: fromnode = mshader.inputs[1].links[0].from_node if fromnode.type == "BSDF_PRINCIPLED": #Get the socket we are looking for, and plug it into RGB socket 1 fromsocket = findSocketConnectedtoP(fromnode, thisbake) nodetree.links.new(fromsocket, rgb.inputs[1]) elif fromnode.type == "MIX_SHADER": #If it's a mix shader on the other end, connect the equivilent RGB node #Get the RGB node for that mshader fromrgb = nodes[created_mix_nodes[fromnode.name]] fromsocket = fromrgb.outputs[0] nodetree.links.new(fromsocket, rgb.inputs[1]) elif fromnode.type == "EMISSION": #Set this input to black rgb.inputs[1].default_value = (0.0, 0.0, 0.0, 1) else: printmsg("Error, invalid node config") else: rgb.inputs[1].default_value = (0.0, 0.0, 0.0, 1) #Mshader - Socket 2 if len(mshader.inputs[2].links) > 0: fromnode = mshader.inputs[2].links[0].from_node if fromnode.type == "BSDF_PRINCIPLED": #Get the socket we are looking for, and plug it into RGB socket 2 fromsocket = findSocketConnectedtoP(fromnode, thisbake) nodetree.links.new(fromsocket, rgb.inputs[2]) elif fromnode.type == "MIX_SHADER": #If it's a mix shader on the other end, connect the equivilent RGB node #Get the RGB node for that mshader fromrgb = nodes[created_mix_nodes[fromnode.name]] fromsocket = fromrgb.outputs[0] nodetree.links.new(fromsocket, rgb.inputs[2]) elif fromnode.type == "EMISSION": #Set this input to black rgb.inputs[2].default_value = (0.0, 0.0, 0.0, 1) else: printmsg("Error, invalid node config") else: rgb.inputs[2].default_value = (0.0, 0.0, 0.0, 1) #Find the output node with location m_output_node = find_onode(nodetree) loc = m_output_node.location #Create an emission shader emissnode = nodes.new("ShaderNodeEmission") emissnode.label = "OmniBake" emissnode.location = loc emissnode.location.y = emissnode.location.y + 200 #Get the original mix node that was connected to the output node socket = m_output_node.inputs["Surface"] fromnode = socket.links[0].from_node #Find our created mix node that is paired with it rgbmix = nodes[created_mix_nodes[fromnode.name]] #Plug rgbmix into emission nodetree.links.new(rgbmix.outputs[0], emissnode.inputs[0]) #Plug emission into output nodetree.links.new(emissnode.outputs[0], m_output_node.inputs[0]) #------------Long Name Truncation----------------------- trunc_num = 0 trunc_dict = {} def trunc_if_needed(objectname): global trunc_num global trunc_dict #If we already truncated this, just return that if objectname in trunc_dict: printmsg(f"Object name {objectname} was previously truncated. Returning that.") return trunc_dict[objectname] #If not, let's see if we have to truncate it elif len(objectname) >= 38: printmsg(f"Object name {objectname} is too long and will be truncated") trunc_num += 1 truncdobjectname = objectname[0:34] + "~" + str(trunc_num) trunc_dict[objectname] = truncdobjectname return truncdobjectname #If nothing else, just return the original name else: return objectname def untrunc_if_needed(objectname): global trunc_num global trunc_dict for t in trunc_dict: if trunc_dict[t] == objectname: printmsg(f"Returning untruncated value {t}") return t return objectname def ShowMessageBox(messageitems_list, title, icon = 'INFO'): def draw(self, context): for m in messageitems_list: self.layout.label(text=m) bpy.context.window_manager.popup_menu(draw, title = title, icon = icon) #---------------Bake Progress-------------------------------------------- def write_bake_progress(current_operation, total_operations): progress = int((current_operation / total_operations) * 100) t = Path(tempfile.gettempdir()) t = t / f"OmniBake_Bgbake_{os.getpid()}" with open(str(t), "w") as progfile: progfile.write(str(progress)) #---------------End Bake Progress-------------------------------------------- past_items_dict = {} def spot_new_items(initialise=True, item_type="images"): global past_items_dict if item_type == "images": source = bpy.data.images elif item_type == "objects": source = bpy.data.objects elif item_type == "collections": source = bpy.data.collections #First run if initialise: #Set to empty list for this item type past_items_dict[item_type] = [] for source_item in source: past_items_dict[item_type].append(source_item.name) return True else: #Get the list of items for this item type from the dict past_items_list = past_items_dict[item_type] new_item_list_names = [] for source_item in source: if source_item.name not in past_items_list: new_item_list_names.append(source_item.name) return new_item_list_names #---------------Validation Checks------------------------------------------- def checkMatsValidforPBR(mat): nodes = mat.node_tree.nodes valid = True invalid_node_names = [] for node in nodes: if len(node.outputs) > 0: if node.outputs[0].type == "SHADER" and not (node.bl_idname == "ShaderNodeBsdfPrincipled" or node.bl_idname == "ShaderNodeMixShader" or node.bl_idname == "ShaderNodeEmission"): #But is it actually connected to anything? if len(node.outputs[0].links) >0: invalid_node_names.append(node.name) return invalid_node_names def checkExtraMatsValidforPBR(mat): nodes = mat.node_tree.nodes valid = True invalid_node_names = [] for node in nodes: if len(node.outputs) > 0: if node.outputs[0].type == "SHADER" and not (node.bl_idname == "ShaderNodeBsdfPrincipled" or node.bl_idname == "ShaderNodeMixShader" or node.bl_idname == "ShaderNodeAddShader" or node.bl_idname == "ShaderNodeEmission" or node.bl_idname == "ShaderNodeBsdfGlossy" or node.bl_idname == "ShaderNodeBsdfGlass" or node.bl_idname == "ShaderNodeBsdfRefraction" or node.bl_idname == "ShaderNodeBsdfDiffuse" or node.bl_idname == "ShaderNodeBsdfAnisotropic" or node.bl_idname == "ShaderNodeBsdfTransparent"): #But is it actually connected to anything? if len(node.outputs[0].links) >0: invalid_node_names.append(node.name) print(invalid_node_names) return invalid_node_names def deselect_all_not_mesh(): import bpy for obj in bpy.context.selected_objects: if obj.type != "MESH": obj.select_set(False) #Do we still have an active object? if bpy.context.active_object == None: #Pick arbitary bpy.context.view_layer.objects.active = bpy.context.selected_objects[0] def fix_invalid_material_config(obj): if "OmniBake_Placeholder" in bpy.data.materials: mat = bpy.data.materials["OmniBake_Placeholder"] else: mat = bpy.data.materials.new("OmniBake_Placeholder") bpy.data.materials["OmniBake_Placeholder"].use_nodes = True # Assign it to object if len(obj.material_slots) > 0: #Assign it to every empty slot for slot in obj.material_slots: if slot.material == None: slot.material = mat else: # no slots obj.data.materials.append(mat) #All materials must use nodes for slot in obj.material_slots: mat = slot.material if mat.use_nodes == False: mat.use_nodes = True return True def sacle_image_if_needed(img): printmsg("Scaling images if needed") context = bpy.context width = img.size[0] height = img.size[1] proposed_width = 0 proposed_height = 0 if context.scene.texture_res == "0.5k": proposed_width, proposed_height = 512,512 if context.scene.texture_res == "1k": proposed_width, proposed_height = 1024,1024 if context.scene.texture_res == "2k": proposed_width, proposed_height = 1024*2,1024*2 if context.scene.texture_res == "4k": proposed_width, proposed_height = 1024*4,1024*4 if context.scene.texture_res == "8k": proposed_width, proposed_height = 1024*8,1024*8 if width != proposed_width or height != proposed_height: img.scale(proposed_width, proposed_height) def set_image_internal_col_space(image, thisbake): if thisbake != "diffuse": image.colorspace_settings.name = "Non-Color" #------------------------Allow Additional Shaders---------------------------- def findProperInput(OName, pnode): for input in pnode.inputs: if OName == "Anisotropy": OName = "Anisotropic" if OName == "Rotation": OName = "Anisotropic Rotation" if OName == "Color": OName = "Base Color" if input.identifier == OName: return input def useAdditionalShaderTypes(nodetree, nodes): count = 0 for node in nodes: if (node.type == "BSDF_GLOSSY" or node.type == "BSDF_GLASS" or node.type == "BSDF_REFRACTION" or node.type == "BSDF_DIFFUSE" or node.type == "BSDF_ANISOTROPIC" or node.type == "BSDF_TRANSPARENT" or node.type == "ADD_SHADER"): if node.type == "ADD_SHADER": pnode = nodes.new("ShaderNodeMixShader") pnode.label = "mixNew" + str(count) else: pnode = nodes.new("ShaderNodeBsdfPrincipled") pnode.label = "BsdfNew" + str(count) pnode.location = node.location pnode.use_custom_color = True pnode.color = (0.3375297784805298, 0.4575316309928894, 0.08615386486053467) for input in node.inputs: if len(input.links) != 0: fromNode = input.links[0].from_node for output in fromNode.outputs: if len(output.links) != 0: for linkOut in output.links: if linkOut.to_node == node: inSocket = findProperInput(input.identifier, pnode) nodetree.links.new(output, inSocket) else: inSocket = findProperInput(input.identifier, pnode) if inSocket.name != "Shader": inSocket.default_value = input.default_value if len(node.outputs[0].links) != 0: for link in node.outputs[0].links: toNode = link.to_node for input in toNode.inputs: if len(input.links) != 0: if input.links[0].from_node == node: nodetree.links.new(pnode.outputs[0], input) if node.type == "BSDF_REFRACTION" or node.type == "BSDF_GLASS": pnode.inputs[15].default_value = 1 if node.type == "BSDF_DIFFUSE": pnode.inputs[5].default_value = 0 if node.type == "BSDF_ANISOTROPIC" or node.type == "BSDF_GLOSSY": pnode.inputs[4].default_value = 1 pnode.inputs[5].default_value = 0 if node.type == "BSDF_TRANSPARENT": pnode.inputs[7].default_value = 0 pnode.inputs[15].default_value = 1 pnode.inputs[14].default_value = 1 pnode.hide = True pnode.select = False nodetree.nodes.remove(node) count += 1
38,803
Python
36.419479
252
0.592093
NVIDIA-Omniverse/Blender-Addon-OmniPanel/omni_panel/material_bake/background_bake.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import bpy class bgbake_ops(): bgops_list = [] bgops_list_last = [] bgops_list_finished = [] def remove_dead(): #Remove dead processes from current list for p in bgbake_ops.bgops_list: if p[0].poll() == 0: bgbake_ops.bgops_list_finished.append(p) bgbake_ops.bgops_list.remove(p) return 1 #1 second timer bpy.app.timers.register(remove_dead, persistent=True)
1,305
Python
30.853658
74
0.683525
NVIDIA-Omniverse/blender_omniverse_addons/README.md
# blender_omniverse_addons This repository contains the source code for NVIDIA Omniverse Add-ons for Blender, including: * [Omni Panel](https://docs.omniverse.nvidia.com/con_connect/con_connect/blender/omni-panel.html) - Utility functions for particles and material conversions. * [Audio2Face Panel](https://docs.omniverse.nvidia.com/con_connect/con_connect/blender/audio2face.html) - A tool that helps get characters into Audio2Face, as well as assisting in the import of shape keys and animation clips onto rigged Blender characters. * [Scene Optimizer](https://docs.omniverse.nvidia.com/con_connect/con_connect/blender/scene-optimizer.html) - A tool for quickly optimizing meshes, correcting bad geometry, creating automated UVs, and generating collision/proxy geometry. The user can pick any of six optional tools to run, and run them all on either selected meshes or all meshes in a given scene. * UMM - The Universal Material Mapper Add-on for Blender. ## Usage For information on usage, including video tutorials, please see the [Blender Omniverse documentation](https://docs.omniverse.nvidia.com/con_connect/con_connect/blender.html).
1,150
Markdown
70.937496
364
0.797391
NVIDIA-Omniverse/blender_omniverse_addons/omni_audio2face/__init__.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. bl_info = { "name": "Audio2Face Tools", "author": "NVIDIA Corporation", "version": (1, 0, 1), "blender": (3, 4, 0), "location": "View3D > Toolbar > Omniverse", "description": "NVIDIA Omniverse tools for working with Audio2Face", "warning": "", "doc_url": "", "category": "Omniverse", } ## ====================================================================== import sys from importlib import reload import bpy from bpy.props import (BoolProperty, CollectionProperty, EnumProperty, FloatProperty, IntProperty, PointerProperty, StringProperty) from omni_audio2face import (operators, ui) for module in (operators, ui): reload(module) from omni_audio2face.ui import OBJECT_PT_Audio2FacePanel from omni_audio2face.operators import ( OMNI_OT_PrepareScene, OMNI_OT_MarkExportMesh, OMNI_OT_ExportPreparedScene, OMNI_OT_ChooseUSDFile, OMNI_OT_ChooseAnimCache, OMNI_OT_ImportRigFile, OMNI_OT_TransferShapeData, OMNI_OT_ImportAnimation, ) ## ====================================================================== class Audio2FaceToolsSettings(bpy.types.PropertyGroup): ## shapes stuff use_face_selection: BoolProperty(description="Use Face Selection") export_project: BoolProperty(description="Export Project File", default=True) export_filepath: StringProperty(description="Export Path") import_filepath: StringProperty(description="Shapes Import Path") ## anim import settings import_anim_path: StringProperty(description="Anim Cache Path") anim_start_type: EnumProperty( items=[("CURRENT", "At Play Head", "Load Clip at the playhead"), ("CUSTOM", "Custom", "Choose a custom start frame")], default="CURRENT") anim_start_frame: IntProperty(default=0) anim_frame_rate: FloatProperty(default=60.0, min=1.0) anim_apply_scale: BoolProperty(default=True) anim_set_range: BoolProperty(default=False) anim_load_to: EnumProperty( items=[("CURRENT", "Current Action", "Load curves onto current Action"), ("CLIP", "Clip", "Load curves as a new Action for NLE use")], default="CURRENT") anim_overwrite: BoolProperty(default=False, name="Overwrite Existing Clips") ## Store pointers to all the meshes for the full setup. mesh_skin: PointerProperty(type=bpy.types.Object) mesh_tongue: PointerProperty(type=bpy.types.Object) mesh_eye_left: PointerProperty(type=bpy.types.Object) mesh_eye_right: PointerProperty(type=bpy.types.Object) mesh_gums_lower: PointerProperty(type=bpy.types.Object) transfer_apply_fix: BoolProperty(name="Apply Fix", description="Apply Basis to points not part of the head during transfer", default=False) ## ====================================================================== classes = ( Audio2FaceToolsSettings, OBJECT_PT_Audio2FacePanel, OMNI_OT_PrepareScene, OMNI_OT_MarkExportMesh, OMNI_OT_ExportPreparedScene, OMNI_OT_ChooseUSDFile, OMNI_OT_ChooseAnimCache, OMNI_OT_ImportRigFile, OMNI_OT_TransferShapeData, OMNI_OT_ImportAnimation, ) def register(): unregister() for item in classes: bpy.utils.register_class(item) bpy.types.Scene.audio2face = bpy.props.PointerProperty(type=Audio2FaceToolsSettings) bpy.types.Object.a2f_original = bpy.props.PointerProperty(type=bpy.types.Object) version = bl_info["version"] version = str(version[0]) + str(version[1]) + str(version[2]) OBJECT_PT_Audio2FacePanel.version = f"{str(version[0])}.{str(version[1])}.{str(version[2])}" ## ====================================================================== def unregister(): # User preferences for item in classes: try: bpy.utils.unregister_class(item) except: continue if hasattr(bpy.types.Scene, "audio2face"): del bpy.types.Scene.audio2face if hasattr(bpy.types.Object, "a2f_original"): del bpy.types.Object.a2f_original
3,862
Python
30.153226
93
0.682289
NVIDIA-Omniverse/blender_omniverse_addons/omni_audio2face/operators.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import json import os import re import sys from typing import * import numpy as np import bpy import bmesh from bpy.props import (BoolProperty, EnumProperty, FloatProperty, IntProperty, StringProperty) from bpy.types import (Collection, Context, Event, Mesh, Object, Scene) from mathutils import * ## ====================================================================== def _get_filepath(scene:Scene, as_import:bool=False) -> str: if as_import: result = scene.audio2face.import_filepath.strip() else: result = scene.audio2face.export_filepath.strip() return result ## ====================================================================== def _get_or_create_collection(collection:Collection, name:str) -> Collection: """Find a child collection of the specified collection, or create it if it does not exist.""" result = collection.children.get(name, None) if not result: result = bpy.data.collections.new(name) collection.children.link(result) ## Make sure this is visible or things'll break in other ways down the line if result.is_evaluated: result = result.original result.hide_render = result.hide_viewport = result.hide_select = False result_lc = [x for x in bpy.context.view_layer.layer_collection.children if x.collection is result] if len(result_lc): result_lc = result_lc[0] result_lc.exclude = False result_lc.hide_viewport = False else: print(f"-- Warning: No layer collection found for {result.name}") return result ## ====================================================================== def ensure_scene_collections(scene:Scene) -> Tuple[bpy.types.Collection]: """Make sure that all Audio2Face scene collections exist.""" a2f_collection = _get_or_create_collection(scene.collection, "Audio2Face") a2f_export = _get_or_create_collection(a2f_collection, "A2F Export") a2f_export_static = _get_or_create_collection(a2f_export, "A2F Export Static") a2f_export_dynamic = _get_or_create_collection(a2f_export, "A2F Export Dynamic") return a2f_collection, a2f_export, a2f_export_static, a2f_export_dynamic ## ====================================================================== def _get_base_collection() -> Collection: return bpy.data.collections.get("Audio2Face", None) def _get_import_collection() -> Collection: return bpy.data.collections.get("A2F Import", None) def _get_export_collection() -> Collection: return bpy.data.collections.get("A2F Export", None) ## ====================================================================== class OMNI_OT_PrepareScene(bpy.types.Operator): """Prepares the active scene for interaction with Audio2Face""" bl_idname = "audio2face.prepare_scene" bl_label = "Prepare Scene for Audio2Face" bl_options = {"REGISTER", "UNDO"} @classmethod def poll(cls, context:Context) -> bool: return bool(context.scene) def execute(self, context:Context) -> Set[str]: scene = context.scene ensure_scene_collections(scene) self.report({"INFO"}, "A2F: Scene is prepped.") return {'FINISHED'} ## ====================================================================== def selected_mesh_objects(context:Context) -> List[Object]: """Return a filtered list of Mesh objects from the context.""" a2f_collection = bpy.data.collections.get("Audio2Face", None) export_objects = {x.name for x in a2f_collection.all_objects} if a2f_collection else {} result = [x for x in context.selected_objects if x.data and isinstance(x.data, bpy.types.Mesh)] result = list(filter(lambda x: not x.name in export_objects and x.data and isinstance(x.data, bpy.types.Mesh), result)) return result ## ====================================================================== def export_mesh_poll(context:Context) -> bool: """ Check for a mesh object selection if use_face_selection is false, or an edit mode face selection otherwise. """ valid_mesh = len(selected_mesh_objects(context)) is_poly_edit_mode = context.tool_settings.mesh_select_mode[2] if context.scene.audio2face.use_face_selection: if (context.mode == "EDIT_MESH" and is_poly_edit_mode and valid_mesh and len(context.active_object.data.count_selected_items()) and context.active_object.data.count_selected_items()[2]): return True else: if context.mode == "OBJECT" and valid_mesh: return True return False ## ====================================================================== def make_valid_name(name:str) -> str: result = name.replace("-","_").replace(" ","_").replace(".","_") return result ## ====================================================================== def process_export_mesh(orig:Object, target_collection:Collection, is_dynamic:bool, split:bool): """ Processes the selected mesh for export, adding original vertex indices and copying it over into the target collection. """ assert isinstance(orig.data, bpy.types.Mesh) obj_dupe_name = make_valid_name(orig.name) + "__Audio2Face_EX" if obj_dupe_name in bpy.data.objects: bpy.data.objects.remove(bpy.data.objects[obj_dupe_name]) mesh_dupe = orig.data.copy() mesh_dupe.name = make_valid_name(orig.data.name) + "__Audio2Face_EX" obj_dupe = bpy.data.objects.new(obj_dupe_name, mesh_dupe) target_collection.objects.link(obj_dupe) obj_dupe.a2f_original = orig bpy.ops.object.mode_set(mode="OBJECT") orig.select_set(False) obj_dupe.select_set(True) ## Clean out all extraneous data. for item in obj_dupe.modifiers, obj_dupe.vertex_groups: item.clear() obj_dupe.shape_key_clear() ## Add a custom data layer to remember the original point indices. attr = obj_dupe.data.attributes.get("index_orig", obj_dupe.data.attributes.new("index_orig", "INT", "POINT")) vertex_count = len(obj_dupe.data.vertices) attr.data.foreach_set("value", np.arange(vertex_count)) bpy.ops.object.mode_set(mode="OBJECT") if split: ## Delete all unselected faces. deps = bpy.context.evaluated_depsgraph_get() indices = [x.index for x in orig.data.polygons if not x.select] bm = bmesh.new() bm.from_object(obj_dupe, deps) bm.faces.ensure_lookup_table() ## Must convert to list; delete does not accept map objects selected = list(map(lambda x: bm.faces[x], indices)) bpy.ops.object.mode_set(mode="EDIT") bmesh.ops.delete(bm, geom=selected, context="FACES") bpy.ops.object.mode_set(mode="OBJECT") bm.to_mesh(obj_dupe.data) ## Make sure to snap the object into place. obj_dupe.matrix_world = orig.matrix_world.copy() return obj_dupe ## =====================================================a================= class OMNI_OT_MarkExportMesh(bpy.types.Operator): """Tags the selected mesh as static for Audio2Face.""" bl_idname = "audio2face.mark_export_mesh" bl_label = "Mark Mesh for Export" bl_options = {"REGISTER", "UNDO"} is_dynamic: BoolProperty(description="Mesh is Dynamic", default=False) @classmethod def poll(cls, context:Context) -> bool: return export_mesh_poll(context) def execute(self, context:Context) -> Set[str]: a2f_collection, a2f_export, a2f_export_static, a2f_export_dynamic = ensure_scene_collections(context.scene) target_collection = a2f_export_dynamic if self.is_dynamic else a2f_export_static split = context.scene.audio2face.use_face_selection processed_meshes = [] for mesh in selected_mesh_objects(context): context.view_layer.objects.active = mesh result = process_export_mesh(mesh, target_collection, self.is_dynamic, split) processed_meshes.append(result) context.view_layer.objects.active = processed_meshes[-1] return {'FINISHED'} ## ====================================================================== class OMNI_OT_ChooseUSDFile(bpy.types.Operator): """File chooser with proper extensions.""" bl_idname = "collections.usd_choose_file" bl_label = "Choose USD File" bl_options = {"REGISTER"} ## Required for specifying extensions. filepath: StringProperty(subtype="FILE_PATH") operation: EnumProperty(items=[("IMPORT", "Import", ""),("EXPORT", "Export", "")], default="IMPORT", options={"HIDDEN"}) filter_glob: StringProperty(default="*.usd;*.usda;*.usdc", options={"HIDDEN"}) check_existing: BoolProperty(default=True, options={"HIDDEN"}) def execute(self, context:Context): real_path = os.path.abspath(bpy.path.abspath(self.filepath)) real_path = real_path.replace("\\", "/") if self.operation == "EXPORT": context.scene.audio2face.export_filepath = real_path else: context.scene.audio2face.import_filepath = real_path return {"FINISHED"} def invoke(self, context:Context, event:Event) -> Set[str]: if len(self.filepath.strip()) == 0: self.filepath = "untitled.usdc" context.window_manager.fileselect_add(self) return {"RUNNING_MODAL"} ## ====================================================================== class OMNI_OT_ChooseAnimCache(bpy.types.Operator): """File chooser with proper extensions.""" bl_idname = "collections.usd_choose_anim_cache" bl_label = "Choose Animation Cache" bl_options = {"REGISTER"} ## Required for specifying extensions. filepath: StringProperty(subtype="FILE_PATH") filter_glob: StringProperty(default="*.usd;*.usda;*.usdc;*.json", options={"HIDDEN"}) check_existing: BoolProperty(default=True, options={"HIDDEN"}) def execute(self, context:Context): real_path = os.path.abspath(bpy.path.abspath(self.filepath)) real_path = real_path.replace("\\", "/") context.scene.audio2face.import_anim_path = real_path return {"FINISHED"} def invoke(self, context:Context, event:Event) -> Set[str]: context.window_manager.fileselect_add(self) return {"RUNNING_MODAL"} ## ====================================================================== class OMNI_OT_ExportPreparedScene(bpy.types.Operator): """Exports prepared scene as USD for Audio2Face.""" bl_idname = "audio2face.export_prepared_scene" bl_label = "Export Prepared Scene" bl_options = {"REGISTER"} @classmethod def poll(cls, context:Context) -> bool: a2f_export = _get_export_collection() child_count = len(a2f_export.all_objects) if a2f_export else 0 path = _get_filepath(context.scene) return a2f_export and child_count and len(path) def execute(self, context:Context) -> Set[str]: ## Grab filepath before the scene switches scene = context.scene filepath = _get_filepath(scene) export_scene = bpy.data.scenes.get("a2f_export", bpy.data.scenes.new("a2f_export")) for child_collection in list(export_scene.collection.children): export_scene.collection.children.remove(child_collection) export_collection = _get_export_collection() export_scene.collection.children.link(export_collection) context.window.scene = export_scene args = { "filepath": filepath, "start": scene.frame_current, "end": scene.frame_current, "convert_to_cm": False, "export_lights": False, "export_cameras": False, "export_materials": False, "export_textures": False, "default_prim_path": "/World", "root_prim_path": "/World", } result = bpy.ops.wm.usd_export(**args) context.window.scene = scene bpy.data.scenes.remove(export_scene) export_scene = None ## generate the project file if scene.audio2face.export_project: project_filename = os.path.basename(filepath) skin = scene.audio2face.mesh_skin tongue = scene.audio2face.mesh_tongue eye_left = scene.audio2face.mesh_eye_left eye_right= scene.audio2face.mesh_eye_right gums = scene.audio2face.mesh_gums_lower a2f_export_static = bpy.data.collections.get("A2F Export Static", None) static_objects = list(a2f_export_static.objects) if a2f_export_static else [] a2f_export_dynamic = bpy.data.collections.get("A2F Export Dynamic", None) dynamic_objects = list(a2f_export_dynamic.objects) if a2f_export_dynamic else [] for mesh in skin, tongue: if mesh in dynamic_objects: dynamic_objects.pop(dynamic_objects.index(mesh)) for mesh in eye_left, eye_right, gums: if mesh in static_objects: static_objects.pop(static_objects.index(mesh)) transfer_data = "" if skin: transfer_data += '\t\tstring mm:skin = "/World/character_root/{}/{}"\n'.format(make_valid_name(skin.name), make_valid_name(skin.data.name)) if tongue: transfer_data += '\t\tstring mm:tongue = "/World/character_root/{}/{}"\n'.format(make_valid_name(tongue.name), make_valid_name(tongue.data.name)) if eye_left: transfer_data += '\t\tstring[] mm:l_eye = ["/World/character_root/{}/{}"]\n'.format(make_valid_name(eye_left.name), make_valid_name(eye_left.data.name)) if eye_right: transfer_data += '\t\tstring[] mm:r_eye = ["/World/character_root/{}/{}"]\n'.format(make_valid_name(eye_right.name), make_valid_name(eye_right.data.name)) if gums: transfer_data += '\t\tstring[] mm:gums = ["/World/character_root/{}/{}"]\n'.format(make_valid_name(gums.name), make_valid_name(gums.data.name)) if len(static_objects): transfer_data += '\t\tstring[] mm:extra_static = [{}]\n'.format( ', '.join(['"/World/character_root/{}/{}"'.format(make_valid_name(x.name), make_valid_name(x.data.name)) for x in static_objects]) ) if len(dynamic_objects): transfer_data += '\t\tstring[] mm:extra_dynamic = [{}]\n'.format( ', '.join(['"/World/character_root/{}/{}"'.format(make_valid_name(x.name), make_valid_name(x.data.name)) for x in dynamic_objects]) ) template = "" template_path = os.sep.join([os.path.dirname(os.path.abspath(__file__)), "templates", "project_template.usda"]) with open(template_path, "r") as fp: template = fp.read() template = template.replace("%filepath%", project_filename) template = template.replace("%transfer_data%", transfer_data) project_usd_filepath = filepath.rpartition(".")[0] + "_project.usda" with open(project_usd_filepath, "w") as fp: fp.write(template) self.report({"INFO"}, f"Exported project to: '{project_usd_filepath}'") else: self.report({"INFO"}, f"Exported head to: '{filepath}'") return result ## ====================================================================== def _abs_path(file_path:str) -> str: if not len(file_path) > 2: return file_path if file_path[0] == '/' and file_path[1] == '/': file_path = bpy.path.abspath(file_path) return os.path.abspath(file_path) ## ====================================================================== class OMNI_OT_ImportRigFile(bpy.types.Operator): """Imports a rigged USD file from Audio2Face""" bl_idname = "audio2face.import_rig" bl_label = "Import Rig File" bl_options = {"REGISTER", "UNDO"} @classmethod def poll(cls, context:Context) -> bool: return len(_get_filepath(context.scene, as_import=True)) def execute(self, context:Context) -> Set[str]: filepath = _get_filepath(context.scene, as_import=True) args = { "filepath": filepath, "import_skeletons": False, "import_materials": False, } scene = context.scene ## Switching the active collection requires this odd code. base = _get_or_create_collection(scene.collection, "Audio2Face") import_col = _get_or_create_collection(base, "A2F Import") base_lc = [x for x in context.view_layer.layer_collection.children if x.collection is base][0] import_lc = [x for x in base_lc.children if x.collection is import_col][0] context.view_layer.active_layer_collection = import_lc if not context.mode == 'OBJECT': try: bpy.ops.object.mode_set(mode="OBJECT") except RuntimeError: pass if len(import_col.all_objects): bpy.ops.object.select_all(action="DESELECT") ## Let's clean out the import collection on each go to keep things simple bpy.ops.object.select_same_collection(collection=import_col.name) bpy.ops.object.delete() ## Make sure the import collection is selected so the imported objects ## get assigned to it. # scene.view_layers[0].active_layer_collection.collection = import_col bpy.ops.object.select_all(action='DESELECT') override = context.copy() override["collection"] = bpy.data.collections["A2F Import"] result = bpy.ops.wm.usd_import(**args) roots = [x for x in import_col.objects if not x.parent] for root in roots: ## bugfix: don't reset rotation, since there may have been a rotation ## carried over from the blender scene and we want to line up visibly ## even though it has no bearing on the shape transfer. root.scale = [1.0, 1.0, 1.0] ## Strip out any childless empties, like joint1. empties = [x for x in import_col.objects if not len(x.children) and x.type == "EMPTY"] for empty in empties: bpy.data.objects.remove(empty) self.report({"INFO"}, f"Imported Rig from: {filepath}") return {"FINISHED"} ## ====================================================================== class AnimData: """Small data holder unifying what's coming in from JSON and USD(A)""" def __init__(self, clip_name:str, shapes:List[str], key_data:List[List[float]], start_frame:int=0, frame_rate:float=60.0): self.clip_name = clip_name self.shapes = shapes self.num_frames = len(key_data) self.key_data = self._swizzle_data(key_data) self.start_frame = start_frame self.frame_rate = frame_rate def curves(self): for index, name in enumerate(self.shapes): yield f'key_blocks["{name}"].value', self.key_data[index] def _swizzle_data(self, data:List[List[float]]) -> List[List[float]]: """Massage the data a bit for writing directly to the curves""" result = [] for index, _ in enumerate(self.shapes): result.append( [data[frame][index] for frame in range(self.num_frames)] ) return result class OMNI_OT_ImportAnimation(bpy.types.Operator): """Imports a shape key animation from an Audio2Face USDA file or JSON""" bl_idname = "audio2face.import_animation" bl_label = "Import Animation" bl_options = {"REGISTER", "UNDO"} start_type: EnumProperty( name="Start Type", items=[("CURRENT", "Current Action", "Load Clip at the playhead"), ("CUSTOM", "Custom", "Choose a custom start frame")], default="CURRENT") start_frame: IntProperty(default=1, name="Start Frame", description="Align start of animation to this frame") frame_rate: FloatProperty(default=60.0, min=1.0, name="Frame Rate", description="Frame Rate of file you're importing") set_range: BoolProperty(default=False, name="Set Range", description="If checked, set the scene animation frame range to the imported file's range") apply_scale: BoolProperty(default=False, name="Apply Clip Scale", description="If checked and the clip framerate differs from the scene, scale the keys to match") load_to: EnumProperty( name="Load To", description="Load animation to current Action, or to a new Action Clip", items=[("CURRENT", "Current Action", "Load curves onto current Action"), ("CLIP", "Clip", "Load curves as a new Action Clip (for NLE use)")], default="CURRENT") overwrite: BoolProperty(default=False, name="Overwrite Existing Clips") @classmethod def poll(cls, context:Context) -> bool: have_file = len(context.scene.audio2face.import_anim_path) have_mesh = context.active_object and context.active_object.type == "MESH" have_selection = context.active_object in context.selected_objects is_object_mode = context.mode == "OBJECT" return all([have_file, have_mesh, have_selection, is_object_mode]) def apply_animation(self, animation:AnimData, ob:Object): shapes = ob.data.shape_keys action = None start_frame = bpy.context.scene.frame_current if self.start_type == "CURRENT" else self.start_frame if shapes.animation_data is None: shapes.animation_data_create() nla_tracks = shapes.animation_data.nla_tracks if self.load_to == "CLIP": def _predicate(track): for strip in track.strips: if strip.action and strip.action.name == animation.clip_name: return True return False if len(nla_tracks): existing_tracks = list(filter(_predicate, nla_tracks)) if len(existing_tracks) and not self.overwrite: self.report({"ERROR"}, f"Clip named {animation.clip_name} already exists; aborting.") return False else: ## remove the track(s) specified for overwrites for track in existing_tracks: self.report({"INFO"}, f"Removing old track {track.name}") nla_tracks.remove(track) if not animation.clip_name in bpy.data.actions: bpy.data.actions.new(animation.clip_name) action = bpy.data.actions[animation.clip_name] offset = 0 else: if not shapes.animation_data.action: bpy.data.actions.new(animation.clip_name) action = shapes.animation_data.action = bpy.data.actions[animation.clip_name] else: action = shapes.animation_data.action offset = start_frame ## clean out old curves to_clean = [] for curve in action.fcurves: for name in animation.shapes: if f'["{name}"]' in curve.data_path: to_clean.append(curve) for curve in to_clean: action.fcurves.remove(curve) scene_framerate = bpy.context.scene.render.fps clip_scale = 1.0 clip_to_scene_scale = scene_framerate / animation.frame_rate if self.apply_scale and self.load_to == "CURRENT" and not (int(animation.frame_rate) == int(scene_framerate)): clip_scale = clip_to_scene_scale for data_path, values in animation.curves(): curve = action.fcurves.new(data_path) curve.keyframe_points.add(len(values)) for index, value in enumerate(values): curve.keyframe_points[index].co = (float(index) * clip_scale + offset, value) if self.load_to == "CLIP": ## I'm really not sure if this is the correct idea, but when loading as clip ## we push a new NLA_Track and add the action as a strip, then offset it using ## the strip frame start. track = nla_tracks.new() track.name = animation.clip_name + "_NLE" strip = track.strips.new(animation.clip_name, start_frame, action) if self.apply_scale: strip.scale = clip_to_scene_scale for item in [x for x in nla_tracks if not x == track]: item.select = False track.select = True def load_animation_usda(self, clip_name:str, file_path:str) -> AnimData: """ Do a quick parse of the input USDA file in plain text, as we can't use the USD Python API yet. !TODO: When the USD Python API is available, switch to it instead. """ with open(file_path, "r") as fp: source = fp.read().strip() ## quick sanity checks; not robust! if not all([ source.startswith("#usda"), "framesPerSecond = " in source, "uniform token[] blendShapes = [" in source, "float[] blendShapeWeights.timeSamples = {" in source, "token[] custom:mh_curveNames = [" in source, "float[] custom:mh_curveValues.timeSamples = {" in source]): self.report({"ERROR"}, f"USDA not a weights animation cache: {file_path}") return None end_time = int(source.partition("endTimeCode = ")[-1].partition("\n")[0]) frame_rate = int(source.partition("framesPerSecond = ")[-1].partition("\n")[0]) start_frame = int(source.partition("startTimeCode = ")[-1].partition("\n")[0]) shape_names = source.partition("uniform token[] blendShapes = [")[-1].partition("]")[0] shape_names = shape_names.replace('"','').replace(' ', '').split(',') ## strip to timeSamples, split lines, then split off the index and parse out the arrays into floats samples = source.partition("float[] blendShapeWeights.timeSamples = {")[-1].partition("}")[0].strip().split('\n') weights = [list(map(float, x.partition(": [")[-1].rpartition("]")[0].replace(" ", "").split(","))) for x in samples] ## capture frame rate frame_rate = float(source.partition("framesPerSecond = ")[-1].partition("\n")[0]) return AnimData(clip_name=clip_name, shapes=shape_names, key_data=weights, frame_rate=frame_rate) def load_animation_json(self, clip_name:str, file_path:str) -> AnimData: assert file_path.lower().endswith(".json") file_path = _abs_path(file_path) data = None with open(file_path, "r") as fp: try: data = json.load(fp) except: return None if not "facsNames" in data or not "weightMat" in data or not "numFrames" in data: self.report({"ERROR"}, f"Malformed JSON file (missing data): {file_path}") return None if not data["numFrames"] == len(data["weightMat"]): self.report({"ERROR"}, f"Malformed JSON: malformed file. Expected {data['numFrames']} frames, found {len(data['weightMat'])} -- {file_path}") return None return AnimData(clip_name=clip_name, shapes=data["facsNames"], key_data=data["weightMat"], frame_rate=self.frame_rate) def load_animation(self, file_path:str, ob:Object) -> bool: assert ob and isinstance(ob, (bpy.types.Object)) if not file_path.endswith((".usda", ".json")): self.report({"Error"}, f"Path should point to a USDA or JSON file: {file_path}") return False clip_name = os.path.basename(file_path).partition(".")[0] self.report({"INFO"}, f"Loading anim: {file_path}") if file_path.endswith(".json"): data = self.load_animation_json(clip_name, file_path) else: data = self.load_animation_usda(clip_name, file_path) if data is None: self.report({"ERROR"}, f"Unable to load data from file {file_path}") return False self.apply_animation(data, ob) return True def execute(self, context:Context) -> Set[str]: scene = context.scene ob = context.active_object if not self.load_animation(scene.audio2face.import_anim_path, ob): return {"CANCELLED"} return {"FINISHED"} ## ====================================================================== class OMNI_OT_TransferShapeData(bpy.types.Operator): """Transfers shape data from imported rig heads to the original meshes.""" bl_idname = "audio2face.transfer_shape_data" bl_label = "Transfer Shape Data" bl_options = {"REGISTER", "UNDO"} apply_fix: BoolProperty(name="Apply Fix", description="Propate Basis shape to all parts of the mesh not covered by the head, to prevent vertex vomit.", default=False) @classmethod def poll(cls, context:Context) -> bool: collection = _get_import_collection() if collection is None: return False meshes = [x.name for x in collection.objects if x.type == "MESH"] return bool(len(meshes)) def _get_collection_meshes(self, collection:Collection) -> List["bpy.data.Mesh"]: result = [x for x in collection.all_objects if x.type == "MESH"] return result def _build_mapping_table(self, import_meshes:Collection, export_meshes:Collection) -> Dict: result = {} for imported in import_meshes: ## Intentionally doing the exported data name but the import object name ## because of how the imports work on both sides. token = imported.name.rpartition("__Audio2Face_EX")[0] for exported in export_meshes: exported_token = exported.data.name.rpartition("__Audio2Face_EX")[0] if exported_token == token: result[imported] = exported return result def _transfer_shapes(self, context:Context, source:Object, target:Object, mapping_object:Object) -> int: """ Transfers shapes from the source mesh to the target. :returns: The number of shapes transferred. """ assert source.data and source.data.shape_keys, "Source object has no shape key data." wm = context.window_manager result = 0 ## Run these to make sure they're all visible, checked, and in the view layer a2f_collection, _, _, _ = ensure_scene_collections(context.scene) _get_or_create_collection(a2f_collection, "A2F Import") blocks = source.data.shape_keys.key_blocks total_shapes = len(blocks) if not context.mode == "OBJECT" and context.active_object: bpy.ops.object.mode_set(mode="OBJECT") bpy.ops.object.select_all(action="DESELECT") source.select_set(True) target.select_set(True) context.view_layer.objects.active = target basis = target.data.shape_keys.key_blocks["Basis"] wm.progress_begin(0, total_shapes) start_index = len(target.data.shape_keys.key_blocks) ## Grab the mapping array using the new Attributes API. mapping_indices = np.zeros(len(source.data.vertices), dtype=np.int32) attr = mapping_object.data.attributes['index_orig'] attr.data.foreach_get("value", mapping_indices) for index, block in enumerate(blocks): if block.name == "Basis": continue target.shape_key_add(name=block.name, from_mix=False) target_key_block = target.data.shape_keys.key_blocks[block.name] target_key_block.relative_key = basis for index, target_index in enumerate(mapping_indices): target_key_block.data[target_index].co = block.data[index].co self.report({"INFO"}, f"Transferred shape {block.name} from {source.name} to {target.name}") result += 1 wm.progress_update(index) wm.progress_end() if self.apply_fix: self._select_verts_inverse(target, mapping_indices) bpy.ops.object.mode_set(mode="EDIT") wm.progress_begin(0, total_shapes) for index in range(start_index, start_index+total_shapes-1): shape = target.data.shape_keys.key_blocks[index] self.report({"INFO"}, f"Fixing shape: {shape.name}") target.active_shape_key_index = index bpy.ops.mesh.blend_from_shape(shape='Basis', blend=1.0, add=False) wm.progress_update(index) bpy.ops.object.mode_set(mode="OBJECT") wm.progress_end() return result def _select_verts_inverse(self, ob:Object, mapping_indices:Iterable[int]) -> int: """ Set the vertex selection of the target object to the inverse of what's in mapping_indices through the bmesh API. :returns: The number of vertices selected. """ result = 0 bm = bmesh.new() bm.from_mesh(ob.data) for v in bm.verts: should_set = not (v.index in mapping_indices) v.select_set(should_set) result += int(should_set) bm.to_mesh(ob.data) def _clean_shapes(self, ob:Object, shapes_list:List[str]) -> int: """ For each named shape, remove it from ob's shape keys. :returns: The number of shapes removed """ self.report({"INFO"}, f"Cleaning {', '.join(shapes_list)}") if ob.data.shape_keys is None: return 0 result = 0 for shape in shapes_list: key = ob.data.shape_keys.key_blocks.get(shape) if key: ob.shape_key_remove(key) result +=1 return result def execute(self, context:Context) -> Set[str]: ## Transfer shape data over automatically scene = context.scene export_meshes = self._get_collection_meshes(_get_export_collection()) import_meshes = self._get_collection_meshes(_get_import_collection()) total = 0 mapping_table = self._build_mapping_table(import_meshes, export_meshes).items() self.report({"INFO"}, f"{mapping_table}") for source, mapping_object in mapping_table: ## hop to the true original mesh target = mapping_object.a2f_original source_shapes = [x.name for x in source.data.shape_keys.key_blocks if not x.name == "Basis"] count = self._clean_shapes(target, source_shapes) self.report({"INFO"}, f"Cleaned {count} shape{'' if count == 1 else 's'} from {target.name}") ## regrab the target object now that it's been modified and we're ## holding onto an old pointer target = mapping_object.a2f_original ## bugfix: add a Basis target if none exists if target.data.shape_keys is None or not "Basis" in target.data.shape_keys.key_blocks: target.shape_key_add(name="Basis", from_mix=False) result = self._transfer_shapes(context, source, target, mapping_object) self.report({"INFO"}, f"Transferred {result} shape{'' if result == 1 else 's'} from {source.name} to {target.name}") total += result self.report({"INFO"}, f"Transferred {total} total shape{'' if total == 1 else 's'}") return {"FINISHED"}
31,692
Python
35.220571
151
0.669033
NVIDIA-Omniverse/blender_omniverse_addons/omni_audio2face/ui.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import os from typing import * import bpy from bpy.utils import previews from omni_audio2face.operators import ( OMNI_OT_PrepareScene, OMNI_OT_MarkExportMesh, OMNI_OT_ChooseUSDFile, OMNI_OT_ChooseAnimCache, OMNI_OT_ExportPreparedScene, OMNI_OT_ImportRigFile, OMNI_OT_TransferShapeData, OMNI_OT_ImportAnimation, ) ## ====================================================================== def preload_icons() -> previews.ImagePreviewCollection: """Preload icons used by the interface.""" icons_directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons") all_icons = { "AUDIO2FACE": "omni_audio2face.png", } preview = previews.new() for name, filepath in all_icons.items(): preview.load(name, os.path.join(icons_directory, filepath), "IMAGE") return preview ## ====================================================================== class OBJECT_PT_Audio2FacePanel(bpy.types.Panel): bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category = "Omniverse" bl_label = "Audio2Face" bl_options = {"DEFAULT_CLOSED"} version = "0.0.0" icons = preload_icons() def draw_header(self, context): self.layout.label(text="", icon_value=self.icons["AUDIO2FACE"].icon_id) # draw the panel def draw(self, context): use_face_selection = context.scene.audio2face.use_face_selection is_poly_edit_mode = context.tool_settings.mesh_select_mode[2] and context.mode == "EDIT_MESH" a2f_export_static = bpy.data.collections.get("A2F Export Static", None) a2f_export_dynamic = bpy.data.collections.get("A2F Export Dynamic", None) layout = self.layout layout.label(text="Face Prep and Export", icon="EXPORT") row = layout.row(align=True) op = row.operator(OMNI_OT_MarkExportMesh.bl_idname, text="Export Static") op.is_dynamic = False op = row.operator(OMNI_OT_MarkExportMesh.bl_idname, text="Export Dynamic") op.is_dynamic = True row = layout.row(align=True) row.prop(context.scene.audio2face, "use_face_selection", text="") if use_face_selection and not is_poly_edit_mode: row.label(text="Use Faces: Must be in Polygon Edit Mode!", icon="ERROR") else: row.label(text="Use Face Selection?") ## mesh selections col = layout.column(align=True) if a2f_export_dynamic: col.prop_search(context.scene.audio2face, "mesh_skin", a2f_export_dynamic, "objects", text="Skin Mesh: ") col.prop_search(context.scene.audio2face, "mesh_tongue", a2f_export_dynamic, "objects", text="Tongue Mesh: ") else: col.label(text="Dynamic Meshes are required to set Skin and Tongue", icon="ERROR") col.label(text=" ") if a2f_export_static: col.prop_search(context.scene.audio2face, "mesh_eye_left", a2f_export_static, "objects", text="Left Eye Mesh: ") col.prop_search(context.scene.audio2face, "mesh_eye_right", a2f_export_static, "objects", text="Right Eye Mesh: ") col.prop_search(context.scene.audio2face, "mesh_gums_lower", a2f_export_static, "objects", text="Lower Gums Mesh: ") else: col.label(text="Static Meshes are required to set Eyes", icon="ERROR") col.label(text=" ") col = layout.column(align=True) row = col.row(align=True) row.prop(context.scene.audio2face, "export_filepath", text="Export Path: ") op = row.operator(OMNI_OT_ChooseUSDFile.bl_idname, text="", icon="FILE_FOLDER") op.operation = "EXPORT" col.prop(context.scene.audio2face, "export_project", text="Export With Project File") row = col.row(align=True) collection = bpy.data.collections.get("A2F Export", None) child_count = len(collection.all_objects) if collection else 0 args = { "text": "Export Face USD" if child_count else "No meshes available for Export", } op = row.operator(OMNI_OT_ExportPreparedScene.bl_idname, **args) ## Import Side -- after Audio2Face has transferred the shapes layout.separator() layout.label(text="Face Shapes Import", icon="IMPORT") col = layout.column(align=True) row = col.row(align=True) row.prop(context.scene.audio2face, "import_filepath", text="Shapes Import Path") op = row.operator(OMNI_OT_ChooseUSDFile.bl_idname, text="", icon="FILE_FOLDER") op.operation = "IMPORT" col = layout.column(align=True) col.operator(OMNI_OT_ImportRigFile.bl_idname) row = col.row(align=True) op = row.operator(OMNI_OT_TransferShapeData.bl_idname) op.apply_fix = context.scene.audio2face.transfer_apply_fix row.prop(context.scene.audio2face, "transfer_apply_fix", icon="MODIFIER", text="") col = layout.column(align=True) col.label(text="Anim Cache Path") row = col.row(align=True) row.prop(context.scene.audio2face, "import_anim_path", text="") row.operator(OMNI_OT_ChooseAnimCache.bl_idname, text="", icon="FILE_FOLDER") if context.scene.audio2face.import_anim_path.lower().endswith(".json"): col.prop(context.scene.audio2face, "anim_frame_rate", text="Source Framerate") row = col.row(align=True) row.prop(context.scene.audio2face, "anim_start_type", text="Start Frame") if context.scene.audio2face.anim_start_type == "CUSTOM": row.prop(context.scene.audio2face, "anim_start_frame", text="") col.prop(context.scene.audio2face, "anim_load_to", text="Load To") row = col.row(align=True) row.prop(context.scene.audio2face, "anim_apply_scale", text="Apply Clip Scale") if context.scene.audio2face.anim_load_to == "CLIP": row.prop(context.scene.audio2face, "anim_overwrite") op_label = ("Please change to Object Mode" if not context.mode == "OBJECT" else ("Import Animation Clip" if OMNI_OT_ImportAnimation.poll(context) else "Please Select Target Mesh")) op = col.operator(OMNI_OT_ImportAnimation.bl_idname, text=op_label) op.start_type = context.scene.audio2face.anim_start_type op.frame_rate = context.scene.audio2face.anim_frame_rate op.start_frame = context.scene.audio2face.anim_start_frame op.set_range = context.scene.audio2face.anim_set_range op.load_to = context.scene.audio2face.anim_load_to op.overwrite = context.scene.audio2face.anim_overwrite op.apply_scale = context.scene.audio2face.anim_apply_scale
6,105
Python
36.00606
119
0.702867
NVIDIA-Omniverse/blender_omniverse_addons/omni_panel/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. bl_info = { "name": "Omni Panel", "author": "NVIDIA Corporation", "version": (1, 1, 1), "blender": (3, 4, 0), "location": "View3D > Toolbar > Omniverse", "description": "Nvidia Omniverse bake materials for export to usd", "warning": "", "doc_url": "", "category": "Omniverse", } import bpy #Import classes from .material_bake.operators import (OBJECT_OT_omni_bake_mapbake, OBJECT_OT_omni_bake_bgbake_status, OBJECT_OT_omni_bake_bgbake_import, OBJECT_OT_omni_bake_bgbake_clear) from .ui import (OBJECT_PT_omni_panel, OBJECT_PT_omni_bake_panel, OmniBakePreferences) from .particle_bake.operators import(MyProperties, PARTICLES_OT_omni_hair_bake) from .material_bake import baker from .workflow import usd_kind classes = [ OBJECT_OT_omni_bake_mapbake, OBJECT_PT_omni_panel, OBJECT_PT_omni_bake_panel, OmniBakePreferences, OBJECT_OT_omni_bake_bgbake_status, OBJECT_OT_omni_bake_bgbake_import, OBJECT_OT_omni_bake_bgbake_clear, MyProperties, PARTICLES_OT_omni_hair_bake, ] def ShowMessageBox(message = "", title = "Message Box", icon = 'INFO'): def draw(self, context): self.layout.label(text=message) bpy.context.window_manager.popup_menu(draw, title = title, icon = icon) #---------------------UPDATE FUNCTIONS-------------------------------------------- def prepmesh_update(self, context): if context.scene.prepmesh == False: context.scene.hidesourceobjects = False else: context.scene.hidesourceobjects = True def texture_res_update(self, context): if context.scene.texture_res == "0.5k": context.scene.imgheight = 1024/2 context.scene.imgwidth = 1024/2 context.scene.render.bake.margin = 6 elif context.scene.texture_res == "1k": context.scene.imgheight = 1024 context.scene.imgwidth = 1024 context.scene.render.bake.margin = 10 elif context.scene.texture_res == "2k": context.scene.imgheight = 1024*2 context.scene.imgwidth = 1024*2 context.scene.render.bake.margin = 14 elif context.scene.texture_res == "4k": context.scene.imgheight = 1024*4 context.scene.imgwidth = 1024*4 context.scene.render.bake.margin = 20 elif context.scene.texture_res == "8k": context.scene.imgheight = 1024*8 context.scene.imgwidth = 1024*8 context.scene.render.bake.margin = 32 def newUVoption_update(self, context): if bpy.context.scene.newUVoption == True: bpy.context.scene.prefer_existing_sbmap = False def all_maps_update(self,context): bpy.context.scene.selected_col = True bpy.context.scene.selected_metal = True bpy.context.scene.selected_rough = True bpy.context.scene.selected_normal = True bpy.context.scene.selected_trans = True bpy.context.scene.selected_transrough = True bpy.context.scene.selected_emission = True bpy.context.scene.selected_specular = True bpy.context.scene.selected_alpha = True bpy.context.scene.selected_sss = True bpy.context.scene.selected_ssscol = True #-------------------END UPDATE FUNCTIONS---------------------------------------------- def register(): # usd_kind.register() baker.register() for cls in classes: bpy.utils.register_class(cls) global bl_info version = bl_info["version"] version = str(version[0]) + str(version[1]) + str(version[2]) OBJECT_PT_omni_bake_panel.version = f"{str(version[0])}.{str(version[1])}.{str(version[2])}" #Global variables des = "Texture Resolution" bpy.types.Scene.texture_res = bpy.props.EnumProperty(name="Texture Resolution", default="1k", description=des, items=[ ("0.5k", "0.5k", f"Texture Resolution of {1024/2} x {1024/2}"), ("1k", "1k", f"Texture Resolution of 1024 x 1024"), ("2k", "2k", f"Texture Resolution of {1024*2} x {1024*2}"), ("4k", "4k", f"Texture Resolution of {1024*4} x {1024*4}"), ("8k", "8k", f"Texture Resolution of {1024*8} x {1024*8}") ], update = texture_res_update) des = "Distance to cast rays from target object to selected object(s)" bpy.types.Scene.ray_distance = bpy.props.FloatProperty(name="Ray Distance", default = 0.2, description=des) bpy.types.Scene.ray_warning_given = bpy.props.BoolProperty(default = False) #--- MAPS ----------------------- bpy.types.Scene.omnibake_error = bpy.props.StringProperty(default="") des = "Bake all maps (Diffuse, Metal, SSS, SSS Col. Roughness, Normal, Transmission, Transmission Roughness, Emission, Specular, Alpha, Displacement)" bpy.types.Scene.all_maps = bpy.props.BoolProperty(name="Bake All Maps", default = True, description=des, update = all_maps_update) des = "Bake a PBR Colour map" bpy.types.Scene.selected_col = bpy.props.BoolProperty(name="Diffuse", default = True, description=des) des = "Bake a PBR Metalness map" bpy.types.Scene.selected_metal = bpy.props.BoolProperty(name="Metal", description=des, default= True) des = "Bake a PBR Roughness or Glossy map" bpy.types.Scene.selected_rough = bpy.props.BoolProperty(name="Roughness", description=des, default= True) des = "Bake a Normal map" bpy.types.Scene.selected_normal = bpy.props.BoolProperty(name="Normal", description=des, default= True) des = "Bake a PBR Transmission map" bpy.types.Scene.selected_trans = bpy.props.BoolProperty(name="Transmission", description=des, default= True) des = "Bake a PBR Transmission Roughness map" bpy.types.Scene.selected_transrough = bpy.props.BoolProperty(name="TR Rough", description=des, default= True) des = "Bake an Emission map" bpy.types.Scene.selected_emission = bpy.props.BoolProperty(name="Emission", description=des, default= True) des = "Bake a Subsurface map" bpy.types.Scene.selected_sss = bpy.props.BoolProperty(name="SSS", description=des, default= True) des = "Bake a Subsurface colour map" bpy.types.Scene.selected_ssscol = bpy.props.BoolProperty(name="SSS Col", description=des, default= True) des = "Bake a Specular/Reflection map" bpy.types.Scene.selected_specular = bpy.props.BoolProperty(name="Specular", description=des, default= True) des = "Bake a PBR Alpha map" bpy.types.Scene.selected_alpha = bpy.props.BoolProperty(name="Alpha", description=des, default= True) #------------------------------------------UVs----------------------------------------- des = "Use Smart UV Project to create a new UV map for your objects (or target object if baking to a target). See Blender Market FAQs for more details" bpy.types.Scene.newUVoption = bpy.props.BoolProperty(name="New UV(s)", description=des, update=newUVoption_update, default= False) des = "If one exists for the object being baked, use any existing UV maps called 'OmniBake' for baking (rather than the active UV map)" bpy.types.Scene.prefer_existing_sbmap = bpy.props.BoolProperty(name="Prefer existing UV maps called OmniBake", description=des) des = "New UV Method" bpy.types.Scene.newUVmethod = bpy.props.EnumProperty(name="New UV Method", default="SmartUVProject_Individual", description=des, items=[ ("SmartUVProject_Individual", "Smart UV Project (Individual)", "Each object gets a new UV map using Smart UV Project")]) des = "Margin between islands to use for Smart UV Project" bpy.types.Scene.unwrapmargin = bpy.props.FloatProperty(name="Margin", default=0.03, description=des, min=0.0, step=0.01) des = "Bake to normal UVs" bpy.types.Scene.uv_mode = bpy.props.EnumProperty(name="UV Mode", default="normal", description=des, items=[ ("normal", "Normal", "Normal UV maps")]) #--------------------------------Prep/CleanUp---------------------------------- des = "Create a copy of your selected objects in Blender (or target object if baking to a target) and apply the baked textures to it. If you are baking in the background, this happens after you import" bpy.types.Scene.prepmesh = bpy.props.BoolProperty(name="Copy objects and apply bakes", default = True, description=des, update=prepmesh_update) des = "Hide the source object that you baked from in the viewport after baking. If you are baking in the background, this happens after you import" bpy.types.Scene.hidesourceobjects = bpy.props.BoolProperty(name="Hide source objects after bake", default = True, description=des) des = "Set the height of the baked image that will be produced" bpy.types.Scene.imgheight = bpy.props.IntProperty(name="Height", default=1024, description=des) des = "Set the width of the baked image that will be produced" bpy.types.Scene.imgwidth = bpy.props.IntProperty(name="Width", default=1024, description=des) des="Name to apply to these bakes (is incorporated into the bakes file name, provided you have included this in the image format string - see addon preferences). NOTE: To maintain compatibility, only MS Windows acceptable characters will be used" bpy.types.Scene.batchName = bpy.props.StringProperty(name="Batch name", description=des, default="Bake1", maxlen=20) #---------------------Where To Bake?------------------------------------------- bpy.types.Scene.bgbake = bpy.props.EnumProperty(name="Background Bake", default="fg", items=[ ("fg", "Foreground", "Perform baking in the foreground. Blender will lock up until baking is complete"), ("bg", "Background", "Perform baking in the background, leaving you free to continue to work in Blender while the baking is being carried out") ]) #---------------------Filehanding & Particles------------------------------------------ bpy.types.Scene.particle_options = bpy.props.PointerProperty(type= MyProperties) #-------------------Additional Shaders------------------------------------------- des = "Allows for use of Add, Diffuse, Glossy, Glass, Refraction, Transparent, Anisotropic Shaders. May cause inconsistent results" bpy.types.Scene.more_shaders = bpy.props.BoolProperty(name="Use Additional Shader Types", default=False, description=des) def unregister(): # usd_kind.unregister() baker.unregister() for cls in classes: bpy.utils.unregister_class(cls) del bpy.types.Scene.particle_options del bpy.types.Scene.more_shaders del bpy.types.Scene.newUVoption del bpy.types.Scene.prepmesh del bpy.types.Scene.unwrapmargin del bpy.types.Scene.texture_res del bpy.types.Scene.hidesourceobjects del bpy.types.Scene.batchName del bpy.types.Scene.bgbake del bpy.types.Scene.imgheight del bpy.types.Scene.imgwidth
11,994
Python
47.366935
250
0.650158
NVIDIA-Omniverse/blender_omniverse_addons/omni_panel/ui.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. from typing import * import bpy from bpy.types import (Context, Object, Material, Scene) from . particle_bake.operators import * from . material_bake.background_bake import bgbake_ops # from .material_bake_complex import OBJECT_OT_omni_material_bake from os.path import join, dirname import bpy.utils.previews from .material_bake import baker ## ====================================================================== def get_icons_directory(): icons_directory = join(dirname(__file__), "icons") return icons_directory ## ====================================================================== def _get_bake_types(scene:Scene) -> List[str]: result = [] bake_all = scene.all_maps if scene.selected_col or bake_all: result.append("DIFFUSE") if scene.selected_normal or bake_all: result.append("NORMAL") if scene.selected_emission or bake_all: result.append("EMIT") if scene.selected_specular or bake_all: result.append("GLOSSY") if scene.selected_rough or bake_all: result.append("ROUGHNESS") if scene.selected_trans or bake_all: result.append("TRANSMISSION") ## special types if scene.omni_bake.bake_metallic or bake_all: result.append("METALLIC") return ",".join(result) ## ====================================================================== class OBJECT_PT_omni_panel(bpy.types.Panel): bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category = "Omniverse" bl_label = "NVIDIA Omniverse" bl_options = {"DEFAULT_CLOSED"} version = "0.0.0" #retrieve icons icons = bpy.utils.previews.new() icons_directory = get_icons_directory() icons.load("OMNI", join(icons_directory, "ICON.png"), 'IMAGE') def draw_header(self, context): self.layout.label(text="", icon_value=self.icons["OMNI"].icon_id) def draw(self, context): layout = self.layout scene = context.scene # --------Particle Collection Instancing------------------- particleOptions = scene.particle_options particleCol = self.layout.column(align=True) particleCol.label(text="Omni Particles", icon='PARTICLES') box = particleCol.box() column = box.column(align=True) column.prop(particleOptions, "deletePSystemAfterBake") row = column.row() row.prop(particleOptions, "animateData") if particleOptions.animateData: row = column.row(align=True) row.prop(particleOptions, "selectedStartFrame") row.prop(particleOptions, "selectedEndFrame") row = column.row() row.enabled = False row.label(text="Increased Calculation Time", icon='ERROR') row = column.row() row.scale_y = 1.5 row.operator('omni.hair_bake', text='Convert', icon='MOD_PARTICLE_INSTANCE') if len(bpy.context.selected_objects) != 0 and bpy.context.active_object != None: if bpy.context.active_object.select_get() and bpy.context.active_object.type == "MESH": layout.separator() column = layout.column(align=True) column.label(text="Convert Material to:", icon='SHADING_RENDERED') box = column.box() materialCol = box.column(align=True) materialCol.operator('universalmaterialmap.create_template_omnipbr', text='OmniPBR') materialCol.operator('universalmaterialmap.create_template_omniglass', text='OmniGlass') ## ====================================================================== class OBJECT_PT_omni_bake_panel(bpy.types.Panel): bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category = "Omniverse" bl_label = "Material Baking" bl_options = {"DEFAULT_CLOSED"} version = "0.0.0" #retrieve icons icons = bpy.utils.previews.new() icons_directory = get_icons_directory() icons.load("OMNI", join(icons_directory, "ICON.png"), 'IMAGE') icons.load("BAKE",join(icons_directory, "Oven.png"), 'IMAGE') def draw_header(self, context): self.layout.label(text="", icon="UV_DATA") def draw(self, context): layout = self.layout scene = context.scene box = layout.box() #--------PBR Bake Settings------------------- row = box.row() if scene.all_maps == True: row.prop(scene, "all_maps", icon = 'CHECKBOX_HLT') else: row.prop(scene, "all_maps", icon = 'CHECKBOX_DEHLT') column = box.column(align= True) row = column.row() row.prop(scene, "selected_col") row.prop(scene, "selected_normal") row = column.row() row.prop(scene, "selected_rough") row.prop(scene, "selected_specular", text="Gloss") row = column.row() row.prop(scene, "selected_trans") row.prop(scene, "selected_emission") row = column.row() row.label(text="Special Maps") row = column.row() row.prop(scene.omni_bake, "bake_metallic") row.label(text=" ") #--------Texture Settings------------------- row = box.row() row.label(text="Texture Resolution:") row.scale_y = 0.5 row = box.row() row.prop(scene, "texture_res", expand=True) row.scale_y = 1 if scene.texture_res == "8k" or scene.texture_res == "4k": row = box.row() row.enabled = False row.label(text="Long Bake Times", icon= 'ERROR') #--------UV Settings------------------- column = box.column(align = True) row = column.row() row.prop(scene, "newUVoption") row.prop(scene, "unwrapmargin") #--------Other Settings------------------- column= box.column(align=True) row = column.row() if scene.bgbake == "fg": text = "Copy objects and apply bakes" else: text = "Copy objects and apply bakes (after import)" row.prop(scene, "prepmesh", text=text) if scene.prepmesh == True: if scene.bgbake == "fg": text = "Hide source objects after bake" else: text = "Hide source objects after bake (after import)" row = column.row() row.prop(scene, "hidesourceobjects", text=text) #-------------Buttons------------------------- row = box.row() try: row.prop(scene.cycles, "device", text="Device") except: pass row = box.row() row.scale_y = 1.5 op = row.operator("omni.bake_maps", icon_value=self.icons["BAKE"].icon_id) op.unwrap = scene.newUVoption op.bake_types = _get_bake_types(scene) op.merge_textures = scene.omni_bake.merge_textures op.hide_original = scene.hidesourceobjects op.width = op.height = { "0.5k": 512, "1k": 1024, "2k": 2048, "4k": 4096, "8k": 8192, }[scene.texture_res] can_bake_poll, error_data = baker.omni_bake_maps_poll(context) can_bake_poll_result = { -1: f"Cannot bake objects in collection {baker.COLLECTION_NAME}", -2: f"Material cannot be baked:", -3: "Cycles Renderer Add-on not loaded!" } if can_bake_poll < 0: row = box.row() row.label(text=can_bake_poll_result[can_bake_poll], icon="ERROR") if can_bake_poll == -2: mesh_name, material_name = error_data row = box.row() row.label(text=f"{material_name} on {mesh_name}") row = column.row() row.scale_y = 1 ##!TODO: Restore background baking # row.prop(context.scene, "bgbake", expand=True) if scene.bgbake == "bg": row = column.row(align= True) # - BG status button col = row.column() if len(bgbake_ops.bgops_list) == 0: enable = False icon = "TIME" else: enable = True icon = "TIME" col.operator("object.omni_bake_bgbake_status", text="", icon=icon) col.enabled = enable # - BG import button col = row.column() if len(bgbake_ops.bgops_list_finished) != 0: enable = True icon = "IMPORT" else: enable = False icon = "IMPORT" col.operator("object.omni_bake_bgbake_import", text="", icon=icon) col.enabled = enable #BG erase button col = row.column() if len(bgbake_ops.bgops_list_finished) != 0: enable = True icon = "TRASH" else: enable = False icon = "TRASH" col.operator("object.omni_bake_bgbake_clear", text="", icon=icon) col.enabled = enable row.alignment = 'CENTER' row.label(text=f"Running {len(bgbake_ops.bgops_list)} | Finished {len(bgbake_ops.bgops_list_finished)}") ## ====================================================================== class OmniBakePreferences(bpy.types.AddonPreferences): # this must match the add-on name, use '__package__' # when defining this in a submodule of a python package. bl_idname = __package__ img_name_format: bpy.props.StringProperty(name="Image format string", default="%OBJ%_%BATCH%_%BAKEMODE%_%BAKETYPE%") #Aliases diffuse_alias: bpy.props.StringProperty(name="Diffuse", default="diffuse") metal_alias: bpy.props.StringProperty(name="Metal", default="metalness") roughness_alias: bpy.props.StringProperty(name="Roughness", default="roughness") glossy_alias: bpy.props.StringProperty(name="Glossy", default="glossy") normal_alias: bpy.props.StringProperty(name="Normal", default="normal") transmission_alias: bpy.props.StringProperty(name="Transmission", default="transparency") transmissionrough_alias: bpy.props.StringProperty(name="Transmission Roughness", default="transparencyroughness") clearcoat_alias: bpy.props.StringProperty(name="Clearcost", default="clearcoat") clearcoatrough_alias: bpy.props.StringProperty(name="Clearcoat Roughness", default="clearcoatroughness") emission_alias: bpy.props.StringProperty(name="Emission", default="emission") specular_alias: bpy.props.StringProperty(name="Specular", default="specular") alpha_alias: bpy.props.StringProperty(name="Alpha", default="alpha") sss_alias: bpy.props.StringProperty(name="SSS", default="sss") ssscol_alias: bpy.props.StringProperty(name="SSS Colour", default="ssscol") @classmethod def reset_img_string(self): prefs = bpy.context.preferences.addons[__package__].preferences prefs.property_unset("img_name_format") bpy.ops.wm.save_userpref()
12,271
Python
34.98827
117
0.557412
NVIDIA-Omniverse/blender_omniverse_addons/omni_panel/workflow/usd_kind.py
from typing import * import bpy from bpy.types import (Collection, Context, Image, Object, Material, Mesh, Node, NodeSocket, NodeTree, Scene) from bpy.props import * ## ====================================================================== usd_kind_items = { ('COMPONENT', 'component', 'kind: component'), ('GROUP', 'group', 'kind: group'), ('ASSEMBLY', 'assembly', 'kind: assembly'), ('CUSTOM', 'custom', 'kind: custom'), } ## ====================================================================== def get_plural_count(items) -> (str, int): count = len(items) plural = '' if count == 1 else 's' return plural, count ## ====================================================================== class OBJECT_OT_omni_set_usd_kind(bpy.types.Operator): """Sets the USD Kind value on the selected objects.""" bl_idname = "omni.set_usd_kind" bl_label = "Set USD Kind" bl_options = {"REGISTER", "UNDO"} kind: EnumProperty(name='kind', description='USD Kind', items=usd_kind_items) custom_kind: StringProperty(default="") verbose: BoolProperty(default=False) @property ## read-only def value(self) -> str: return self.custom_kind if self.kind == "CUSTOM" else self.kind.lower() @classmethod def poll(cls, context:Context) -> bool: return bool(len(context.selected_objects)) def execute(self, context:Context) -> Set[str]: if self.kind == "NONE": self.report({"WARNING"}, "No kind specified-- nothing authored.") return {"CANCELLED"} for item in context.selected_objects: props = item.id_properties_ensure() props["usdkind"] = self.value props_ui = item.id_properties_ui("usdkind") props_ui.update(default=self.value, description="USD Kind") if self.verbose: plural, count = get_plural_count(context.selected_objects) self.report({"INFO"}, f"Set USD Kind to {self.value} for {count} object{plural}.") return {"FINISHED"} ## ====================================================================== class OBJECT_OT_omni_set_usd_kind_auto(bpy.types.Operator): """Sets the USD Kind value on scene objects, automatically.""" bl_idname = "omni.set_usd_kind_auto" bl_label = "Set USD Kind Auto" bl_options = {"REGISTER", "UNDO"} verbose: BoolProperty(default=False) def execute(self, context:Context) -> Set[str]: active = context.active_object selected = list(context.selected_objects) bpy.ops.object.select_all(action='DESELECT') ## heuristics ## First, assign "component" to all unparented empties unparented = [x for x in context.scene.collection.all_objects if not x.parent and x.type == "EMPTY"] for item in unparented: item.select_set(True) bpy.ops.omni.set_usd_kind(kind="COMPONENT") item.select_set(False) if self.verbose: plural, count = get_plural_count(unparented) self.report({"INFO"}, f"Set USD Kind Automatically on {count} object{plural}.") return {"FINISHED"} ## ====================================================================== class OBJECT_OT_omni_clear_usd_kind(bpy.types.Operator): """Clear USD Kind values on the selected objects.""" bl_idname = "omni.clear_usd_kind" bl_label = "Clear USD Kind" bl_options = {"REGISTER", "UNDO"} verbose: BoolProperty(default=False) @classmethod def poll(cls, context:Context) -> bool: return bool(len(context.selected_objects)) def execute(self, context:Context) -> Set[str]: from rna_prop_ui import rna_idprop_ui_prop_update total = 0 for item in context.selected_objects: if "usdkind" in item: rna_idprop_ui_prop_update(item, "usdkind") del item["usdkind"] total += 1 if self.verbose: plural, count = get_plural_count(range(total)) self.report({"INFO"}, f"Cleared USD Kind from {count} object{plural}.") return {"FINISHED"} ## ====================================================================== class OBJECT_PT_omni_usd_kind_panel(bpy.types.Panel): bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category = "Omniverse" bl_label = "USD Kind" def draw(self, context:Context): layout = self.layout scene = context.scene layout.label(text="USD Kind") row = layout.row() row.prop(scene.omni_usd_kind, "kind", text="Kind") if scene.omni_usd_kind.kind == "CUSTOM": row = layout.row() row.prop(scene.omni_usd_kind, "custom_kind", text="Custom Kind") col = layout.column(align=True) op = col.operator(OBJECT_OT_omni_set_usd_kind.bl_idname, icon="PLUS") op.kind = scene.omni_usd_kind.kind op.custom_kind = scene.omni_usd_kind.custom_kind op.verbose = True op = col.operator(OBJECT_OT_omni_clear_usd_kind.bl_idname, icon="X") op.verbose = True op = col.operator(OBJECT_OT_omni_set_usd_kind_auto.bl_idname, icon="BRUSH_DATA") op.verbose = True ## ====================================================================== class USDKindProperites(bpy.types.PropertyGroup): kind: EnumProperty(name='kind', description='USD Kind', items=usd_kind_items) custom_kind: StringProperty(default="") ## ====================================================================== classes = [ OBJECT_OT_omni_set_usd_kind, OBJECT_OT_omni_set_usd_kind_auto, OBJECT_OT_omni_clear_usd_kind, OBJECT_PT_omni_usd_kind_panel, USDKindProperites, ] def unregister(): for cls in reversed(classes): try: bpy.utils.unregister_class(cls) except ValueError: continue except RuntimeError: continue try: del bpy.types.Scene.omni_usd_kind except AttributeError: pass def register(): unregister() for cls in classes: bpy.utils.register_class(cls) bpy.types.Scene.omni_usd_kind = bpy.props.PointerProperty(type=USDKindProperites)
5,618
Python
27.668367
102
0.620862
NVIDIA-Omniverse/blender_omniverse_addons/omni_panel/particle_bake/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
858
Python
44.210524
74
0.7331
NVIDIA-Omniverse/blender_omniverse_addons/omni_panel/particle_bake/operators.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import time import bpy import numpy as np class MyProperties(bpy.types.PropertyGroup): deletePSystemAfterBake: bpy.props.BoolProperty( name = "Delete PS after converting", description = "Delete selected particle system after conversion", default = False ) progressBar: bpy.props.StringProperty( name = "Progress", description = "Progress of Particle Conversion", default = "RUNNING" ) animateData: bpy.props.BoolProperty( name = "Keyframe Animation", description = "Add a keyframe for each particle for each of the specified frames", default = False ) selectedStartFrame: bpy.props.IntProperty( name = "Start", description = "Frame to begin keyframes", default = 1 ) selectedEndFrame: bpy.props.IntProperty( name = "End", description = "Frame to stop keyframes", default = 3 ) # def fixEndFrame(): # particleOptions = context.particle_options # particleOptions.selectedEndFrame = particleOptions.selectedStartFrame particleSystemVisibility = [] particleSystemRender = [] def getOriginalModifiers(parent): particleSystemVisibility.clear() particleSystemRender.clear() for mod in parent.modifiers: if mod.type == 'PARTICLE_SYSTEM': particleSystemVisibility.append(mod.show_viewport) particleSystemRender.append(mod.show_render) def restoreOriginalModifiers(parent): count = 0 for mod in parent.modifiers: if mod.type == 'PARTICLE_SYSTEM': mod.show_viewport = particleSystemVisibility[count] mod.show_render = particleSystemRender[count] count+=1 def hideOtherModifiers(parent, countH): count = 0 for mod in parent.modifiers: if mod.type == 'PARTICLE_SYSTEM': if countH != count: mod.show_viewport = False count += 1 def particleSystemVisible(parent, countP): countS = 0 for mod in parent.modifiers: if mod.type == 'PARTICLE_SYSTEM': if countP == countS: return mod.show_viewport else: countS += 1 # Omni Hair Bake class PARTICLES_OT_omni_hair_bake(bpy.types.Operator): """Convert blender particles for Omni scene instancing""" bl_idname = "omni.hair_bake" bl_label = "Omni Hair Bake" bl_options = {'REGISTER', 'UNDO'} # create undo state def execute(self, context): particleOptions = context.scene.particle_options startTime= time.time() print() print("____BEGINING PARTICLE CONVERSION______") #Deselect Non-meshes for obj in bpy.context.selected_objects: if obj.type != "MESH": obj.select_set(False) print("not mesh") #Do we still have an active object? if bpy.context.active_object == None: #Pick arbitary bpy.context.view_layer.objects.active = bpy.context.selected_objects[0] for parentObj in bpy.context.selected_objects: print() print("--Staring " + parentObj.name + ":") getOriginalModifiers(parentObj) countH = 0 countP = 0 countPS = 0 showEmmiter = False hasPS = False for currentPS in parentObj.particle_systems: hideOtherModifiers(parentObj, countH) countH+=1 hasVisible = particleSystemVisible(parentObj, countP) countP+=1 if currentPS != None and hasVisible: hasPS = True bpy.ops.object.select_all(action='DESELECT') renderType = currentPS.settings.render_type emmitOrHair = currentPS.settings.type if parentObj.show_instancer_for_viewport == True: showEmmiter = True if renderType == 'OBJECT' or renderType == 'COLLECTION': count = 0 listInst = [] listInstScale = [] # For Object Instances if renderType == 'OBJECT': instObj = currentPS.settings.instance_object # Duplicate Instanced Object dupInst = instObj.copy() bpy.context.collection.objects.link(dupInst) dupInst.select_set(True) dupInst.location = (0,0,0) bpy.ops.object.move_to_collection(collection_index=0, is_new=True, new_collection_name="INST_"+str(dupInst.name)) dupInst.select_set(False) count += 1 listInst.append(dupInst) listInstScale.append(instObj.scale) # For Collection Instances if renderType == 'COLLECTION': instCol = currentPS.settings.instance_collection.objects countW = 0 weight = 1 for obj in instCol: # Duplicate Instanced Object dupInst = obj.copy() bpy.context.collection.objects.link(dupInst) dupInst.select_set(True) dupInst.location = (0,0,0) bpy.ops.object.move_to_collection(collection_index=0, is_new=True, new_collection_name="INST_"+str(dupInst.name)) dupInst.select_set(False) if parentObj.particle_systems.active.settings.use_collection_count: weight = currentPS.settings.instance_weights[countW].count print("Instance Count: " + str(weight)) for i in range(weight): count += 1 listInst.append(dupInst) listInstScale.append(obj.scale) countW += 1 # For Path Instances *NOT SUPPORTED if renderType == 'PATH': print("path no good") return {'FINISHED'} if renderType == 'NONE': print("no instances") return {'FINISHED'} #DOES NOTHING RIGHT NOW #if overwriteExsisting: #bpy.ops.outliner.delete(hierarchy=True) # Variables parentObj.select_set(True) parentCollection = parentObj.users_collection[0] nameP = parentObj.particle_systems[countPS].name # get name of object's particle system # Create Empty as child o = bpy.data.objects.new( "empty", None) o.name = "EM_" + nameP o.parent = parentObj parentCollection.objects.link( o ) # FOR ANIMATED EMITTER DATA if particleOptions.animateData and emmitOrHair == 'EMITTER': print("--ANIMATED EMITTER--") #Prep for Keyframing collectionInstances = [] # Calculate Dependency Graph degp = bpy.context.evaluated_depsgraph_get() # Evaluate the depsgraph (Important step) particle_systems = parentObj.evaluated_get(degp).particle_systems # All particles of selected particle system activePS = particle_systems[countPS] particles = activePS.particles # Total Particles totalParticles = len(particles) #Currently does NOT work # if activePS.type == 'HAIR': # hairLength = particles[0].hair_length # print(hairLength) # print(bpy.types.ParticleHairKey.co_object(parentObj,parentObj.modifiers[0], particles[0])) # key = particles[0].hair_keys # print(key) # coo = key.co # print(coo) # print(particles[0].location) #Beginings of supporting use random, requires more thought # obInsttt = parentObj.evaluated_get(degp).object_instances # for i in obInsttt: # obj = i.object # print(obj.name) # for obj in degp.object_instances: # print(obj.instance_object) # print(obj.particle_system) # Handle instances for construction of scene collections **Fast** for i in range(totalParticles): childObj = particles[i] calculateChild = False if childObj.birth_time <= particleOptions.selectedEndFrame and childObj.die_time > particleOptions.selectedStartFrame: calculateChild = True if calculateChild: modInst = i % count #Works for "use count" but not "pick random" dupColName = str(listInst[modInst].users_collection[0].name) #Create Collection Instance source_collection = bpy.data.collections[dupColName] instance_obj = bpy.data.objects.new( name= "Inst_" + listInst[modInst].name + "." + str(i), object_data=None ) instance_obj.empty_display_type = 'SINGLE_ARROW' instance_obj.empty_display_size = .1 instance_obj.instance_collection = source_collection instance_obj.instance_type = 'COLLECTION' parentCollection.objects.link(instance_obj) instance_obj.parent = o instance_obj.matrix_parent_inverse = o.matrix_world.inverted() collectionInstances.append(instance_obj) print("Using " + str(len(collectionInstances))) print("Out of " + str(totalParticles) + " instances") collectionCount = len(collectionInstances) startFrame = particleOptions.selectedStartFrame endFrame = particleOptions.selectedEndFrame #Do we need to swap start and end frame? if particleOptions.selectedStartFrame > particleOptions.selectedEndFrame: endFrame = startFrame startFrame = particleOptions.selectedEndFrame for frame in range(startFrame, endFrame + 1): print("frame = " + str(frame)) bpy.context.scene.frame_current = frame # Calculate Dependency Graph for each frame degp = bpy.context.evaluated_depsgraph_get() particle_systems = parentObj.evaluated_get(degp).particle_systems particles = particle_systems[countPS].particles for i in range(collectionCount): activeCol = collectionInstances[i] activeDup = particles[i] #Keyframe Visibility, Scale, Location, and Rotation if activeDup.alive_state == 'UNBORN' or activeDup.alive_state == 'DEAD': activeCol.scale = (0,0,0) activeCol.keyframe_insert(data_path='scale') activeCol.hide_viewport = True activeCol.hide_render = True activeCol.keyframe_insert("hide_viewport") activeCol.keyframe_insert("hide_render") else: activeCol.hide_viewport = False activeCol.hide_render = False scale = activeDup.size activeCol.location = activeDup.location activeCol.rotation_mode = 'QUATERNION' activeCol.rotation_quaternion = activeDup.rotation activeCol.rotation_mode = 'XYZ' activeCol.scale = (scale, scale, scale) activeCol.keyframe_insert(data_path='location') activeCol.keyframe_insert(data_path='rotation_euler') activeCol.keyframe_insert(data_path='scale') activeCol.keyframe_insert("hide_viewport") activeCol.keyframe_insert("hide_render") # FOR ANIMATED HAIR DATA elif particleOptions.animateData and emmitOrHair == 'HAIR': print("--ANIMATED HAIR--") #Prep for Keyframing bpy.ops.object.duplicates_make_real(use_base_parent=True, use_hierarchy=True) # bake particles dups = bpy.context.selected_objects lengthDups = len(dups) collectionInstances = [] # Handle instances for construction of scene collections **Fast** for i in range(lengthDups): childObj = dups.pop(0) modInst = i % count #Works for "use count" but not "pick random" dupColName = str(listInst[modInst].users_collection[0].name) #Create Collection Instance source_collection = bpy.data.collections[dupColName] instance_obj = bpy.data.objects.new( name= "Inst_" + childObj.name, object_data=None ) instance_obj.empty_display_type = 'SINGLE_ARROW' instance_obj.empty_display_size = .1 instance_obj.instance_collection = source_collection instance_obj.instance_type = 'COLLECTION' parentCollection.objects.link(instance_obj) instance_obj.parent = o bpy.data.objects.remove(childObj, do_unlink=True) collectionInstances.append(instance_obj) print(str(len(collectionInstances)) + " instances") collectionCount = len(collectionInstances) startFrame = particleOptions.selectedStartFrame endFrame = particleOptions.selectedEndFrame #Do we need to swap start and end frame? if particleOptions.selectedStartFrame > particleOptions.selectedEndFrame: endFrame = startFrame startFrame = particleOptions.selectedEndFrame for frame in range(startFrame, endFrame + 1): print("frame = " + str(frame)) bpy.context.scene.frame_current = frame # Calculate hairs for each frame parentObj.select_set(True) bpy.ops.object.duplicates_make_real(use_base_parent=True, use_hierarchy=True) # bake particles tempdups = bpy.context.selected_objects for i in range(collectionCount): activeDup = tempdups.pop(0) activeCol = collectionInstances[i] #Keyframe Scale, Location, and Rotation activeCol.location = activeDup.location activeCol.rotation_euler = activeDup.rotation_euler activeCol.scale = activeDup.scale activeCol.keyframe_insert(data_path='location') activeCol.keyframe_insert(data_path='rotation_euler') activeCol.keyframe_insert(data_path='scale') bpy.data.objects.remove(activeDup, do_unlink=True) # FOR SINGLE FRAME CONVERSION else: print("--SINGLE FRAME--") bpy.ops.object.duplicates_make_real(use_base_parent=True, use_hierarchy=True) # bake particles dups = bpy.context.selected_objects lengthDups = len(dups) # Handle instances for construction of scene collections **Fast** for i in range(lengthDups): childObj = dups.pop(0) modInst = i % count dupColName = str(listInst[modInst].users_collection[0].name) loc=childObj.location rot=childObj.rotation_euler newScale = np.divide(childObj.scale, listInstScale[modInst]) #Create Collection Instance source_collection = bpy.data.collections[dupColName] instance_obj = bpy.data.objects.new( name= "Inst_" + childObj.name, object_data=None ) instance_obj.empty_display_type = 'SINGLE_ARROW' instance_obj.empty_display_size = .1 instance_obj.instance_collection = source_collection instance_obj.instance_type = 'COLLECTION' instance_obj.location = loc instance_obj.rotation_euler = rot instance_obj.scale = newScale parentCollection.objects.link(instance_obj) instance_obj.parent = o bpy.data.objects.remove(childObj, do_unlink=True) for obj in listInst: bpy.context.view_layer.layer_collection.children[obj.users_collection[0].name].exclude = True #Make parent object active object again parentObj.select_set(True) bpy.context.view_layer.objects.active = parentObj else: print("Must be object or collection instance") else: print("Object has no active particle system") restoreOriginalModifiers(parentObj) countPS += 1 #Handle PS after converting if particleOptions.deletePSystemAfterBake: if showEmmiter == False and hasPS == True: bpy.context.active_object.hide_render = True bpy.context.active_object.hide_set(True) countI = 0 for ps in range(len(parentObj.particle_systems)): if particleSystemVisibility[ps] == True: parentObj.particle_systems.active_index = countI bpy.ops.object.particle_system_remove() else: countI+=1 else: countI = 0 for mod in parentObj.modifiers: if mod.type == 'PARTICLE_SYSTEM': mod.show_viewport = False if particleSystemVisibility[countI] == True: mod.show_render = False countI+=1 print ("My program took", time.time() - startTime, " seconds to run") # run time return {'FINISHED'}
23,439
Python
46.258064
150
0.462477
NVIDIA-Omniverse/blender_omniverse_addons/omni_panel/material_bake/material_setup.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import bpy from . import functions from .data import MasterOperation def find_node_from_label(label, nodes): for node in nodes: if node.label == label: return node return False def find_isocket_from_identifier(idname, node): for inputsocket in node.inputs: if inputsocket.identifier == idname: return inputsocket return False def find_osocket_from_identifier(idname, node): for outputsocket in node.outputs: if outputsocket.identifier == idname: return outputsocket return False def make_link(f_node_label, f_node_ident, to_node_label, to_node_ident, nodetree): fromnode = find_node_from_label(f_node_label, nodetree.nodes) if(fromnode == False): return False fromsocket = find_osocket_from_identifier(f_node_ident, fromnode) tonode = find_node_from_label(to_node_label, nodetree.nodes) if(tonode == False): return False tosocket = find_isocket_from_identifier(to_node_ident, tonode) nodetree.links.new(fromsocket, tosocket) return True def wipe_labels(nodes): for node in nodes: node.label = "" def get_image_from_tag(thisbake, objname): current_bake_op = MasterOperation.current_bake_operation global_mode = current_bake_op.bake_mode objname = functions.untrunc_if_needed(objname) batch_name = bpy.context.scene.batchName result = [] result = [img for img in bpy.data.images if\ ("SB_objname" in img and img["SB_objname"] == objname) and\ ("SB_batch" in img and img["SB_batch"] == batch_name) and\ ("SB_globalmode" in img and img["SB_globalmode"] == global_mode) and\ ("SB_thisbake" in img and img["SB_thisbake"] == thisbake)\ ] if len(result) > 0: return result[0] functions.printmsg(f"ERROR: No image with matching tag ({thisbake}) found for object {objname}") return False def create_principled_setup(nodetree, obj): functions.printmsg("Creating principled material") nodes = nodetree.nodes obj_name = obj.name.replace("_OmniBake", "") obj.active_material.cycles.displacement_method = 'BOTH' #First we wipe out any existing nodes for node in nodes: nodes.remove(node) # Node Frame node = nodes.new("NodeFrame") node.location = (0,0) node.use_custom_color = True node.color = (0.149763, 0.214035, 0.0590617) #Now create the Principled BSDF pnode = nodes.new("ShaderNodeBsdfPrincipled") pnode.location = (-25, 335) pnode.label = "pnode" pnode.use_custom_color = True pnode.color = (0.3375297784805298, 0.4575316309928894, 0.08615386486053467) pnode.parent = nodes["Frame"] #And the output node node = nodes.new("ShaderNodeOutputMaterial") node.location = (500, 200) node.label = "monode" node.show_options = False node.parent = nodes["Frame"] #----------------------------------------------------------------- #Node Image texture types Types if(bpy.context.scene.selected_col): image = get_image_from_tag("diffuse", obj_name) node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, 250) node.label = "col_tex" node.image = image node.parent = nodes["Frame"] if(bpy.context.scene.selected_sss): node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, 210) node.label = "sss_tex" image = get_image_from_tag("sss", obj_name) node.image = image node.parent = nodes["Frame"] if(bpy.context.scene.selected_ssscol): node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, 170) node.label = "ssscol_tex" image = get_image_from_tag("ssscol", obj_name) node.image = image node.parent = nodes["Frame"] if(bpy.context.scene.selected_metal): node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, 130) node.label = "metal_tex" image = get_image_from_tag("metalness", obj_name) node.image = image node.parent = nodes["Frame"] if(bpy.context.scene.selected_specular): node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, 90) node.label = "specular_tex" image = get_image_from_tag("specular", obj_name) node.image = image node.parent = nodes["Frame"] if(bpy.context.scene.selected_rough): node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, 50) node.label = "roughness_tex" image = get_image_from_tag("roughness", obj_name) node.image = image node.parent = nodes["Frame"] if(bpy.context.scene.selected_trans): node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, -90) node.label = "transmission_tex" image = get_image_from_tag("transparency", obj_name) node.image = image node.parent = nodes["Frame"] if(bpy.context.scene.selected_transrough): node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, -130) node.label = "transmissionrough_tex" image = get_image_from_tag("transparencyroughness", obj_name) node.image = image node.parent = nodes["Frame"] if(bpy.context.scene.selected_emission): node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, -170) node.label = "emission_tex" image = get_image_from_tag("emission", obj_name) node.image = image node.parent = nodes["Frame"] if(bpy.context.scene.selected_alpha): node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, -210) node.label = "alpha_tex" image = get_image_from_tag("alpha", obj_name) node.image = image node.parent = nodes["Frame"] if(bpy.context.scene.selected_normal): node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, -318.7) node.label = "normal_tex" image = get_image_from_tag("normal", obj_name) node.image = image node.parent = nodes["Frame"] #----------------------------------------------------------------- # Additional normal map node for normal socket if(bpy.context.scene.selected_normal): node = nodes.new("ShaderNodeNormalMap") node.location = (-220, -240) node.label = "normalmap" node.show_options = False node.parent = nodes["Frame"] #----------------------------------------------------------------- make_link("emission_tex", "Color", "pnode", "Emission", nodetree) make_link("col_tex", "Color", "pnode", "Base Color", nodetree) make_link("metal_tex", "Color", "pnode", "Metallic", nodetree) make_link("roughness_tex", "Color", "pnode", "Roughness", nodetree) make_link("transmission_tex", "Color", "pnode", "Transmission", nodetree) make_link("transmissionrough_tex", "Color", "pnode", "Transmission Roughness", nodetree) make_link("normal_tex", "Color", "normalmap", "Color", nodetree) make_link("normalmap", "Normal", "pnode", "Normal", nodetree) make_link("specular_tex", "Color", "pnode", "Specular", nodetree) make_link("alpha_tex", "Color", "pnode", "Alpha", nodetree) make_link("sss_tex", "Color", "pnode", "Subsurface", nodetree) make_link("ssscol_tex", "Color", "pnode", "Subsurface Color", nodetree) make_link("pnode", "BSDF", "monode", "Surface", nodetree) #--------------------------------------------------- wipe_labels(nodes) node = nodes["Frame"] node.label = "OMNI PBR"
8,828
Python
33.088803
100
0.608518
NVIDIA-Omniverse/blender_omniverse_addons/omni_panel/material_bake/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
858
Python
44.210524
74
0.7331
NVIDIA-Omniverse/blender_omniverse_addons/omni_panel/material_bake/baker.py
from tempfile import NamedTemporaryFile from typing import * import addon_utils import bpy from bpy.types import (Collection, Context, Image, Object, Material, Mesh, Node, NodeSocket, NodeTree, Scene) from bpy.props import * from mathutils import * from omni_panel.material_bake import material_setup COLLECTION_NAME = "OmniBake_Bakes" def get_material_output(tree:NodeTree, engine:str="CYCLES") -> Optional[Node]: """ Find the material output node that applies only to a specific engine. :param tree: The NodeTree to search. :param engine: The engine to search for. :return: The Material Output Node associated with the engine, or None if not found. """ supported_engines = {"CYCLES", "EEVEE", "ALL"} assert engine in supported_engines, f"Only the following engines are supported: {','.join(supported_engines)}" result = [x for x in tree.nodes if x.type == "OUTPUT_MATERIAL" and x.target in {"ALL", engine}] if len(result): return result[0] return None def prepare_collection(scene:Scene) -> Collection: """ Ensures the bake Collection exists in the specified scene. :param scene: The scene to which you wish to add the bake Collection. :return: the bake Collection """ collection = bpy.data.collections.get(COLLECTION_NAME, None) or bpy.data.collections.new(COLLECTION_NAME) if not COLLECTION_NAME in scene.collection.children: scene.collection.children.link(collection) return collection def select_only(ob:Object): """ Ensure that only the specified object is selected. :param ob: Object to select """ bpy.ops.object.select_all(action="DESELECT") ob.select_set(state=True) bpy.context.view_layer.objects.active = ob def smart_unwrap_object(ob:Object, name:str="OmniBake"): """ Use Blenders built-in smart unwrap functionality to generate a new UV map. :param ob: Mesh Object to unwrap. """ bpy.ops.object.mode_set(mode="EDIT", toggle=False) # Unhide any geo that's hidden in edit mode or it'll cause issues. bpy.ops.mesh.reveal() bpy.ops.mesh.select_all(action="SELECT") bpy.ops.mesh.reveal() if name in ob.data.uv_layers: ob.data.uv_layers.remove(ob.data.uv_layers[name]) uv_layer = ob.data.uv_layers.new(name=name) uv_layer.active = True bpy.ops.uv.select_all(action="SELECT") bpy.ops.uv.smart_project(island_margin=0.0) bpy.ops.object.mode_set(mode="OBJECT", toggle=False) def prepare_mesh(ob:Object, collection: Collection, unwrap=False) -> Object: """ Duplicate the specified Object, also duplicating all its materials. :param ob: The object to duplicate. :param collection: After duplication, the object will be inserted into this Collection :param unwrap: If True, also smart unwrap the object's UVs. :return: The newly created duplicate object. """ assert not ob.name in collection.all_objects, f"{ob.name} is a baked mesh (cannot be used)" new_mesh_name = ob.data.name[:56] + "_baked" if new_mesh_name in bpy.data.meshes: bpy.data.meshes.remove(bpy.data.meshes[new_mesh_name]) new_mesh = ob.data.copy() new_mesh.name = new_mesh_name new_name = ob.name[:56] + "_baked" if new_name in bpy.data.objects: bpy.data.objects.remove(bpy.data.objects[new_name]) new_object = bpy.data.objects.new(new_name, new_mesh) collection.objects.link(new_object) select_only(new_object) new_object.matrix_world = ob.matrix_world.copy() if unwrap: smart_unwrap_object(new_object) for index, material in enumerate([x.material for x in new_object.material_slots]): new_material_name = material.name[:56] + "_baked" if new_material_name in bpy.data.materials: bpy.data.materials.remove(bpy.data.materials[new_material_name]) new_material = material.copy() new_material.name = new_material_name new_object.material_slots[index].material = new_material ob.hide_viewport = True return new_object ##!<--- TODO: Fix these def find_node_from_label(label:str, nodes:List[Node]) -> Node: for node in nodes: if node.label == label: return node return False def find_isocket_from_identifier(idname:str, node:Node) -> NodeSocket: for inputsocket in node.inputs: if inputsocket.identifier == idname: return inputsocket return False def find_osocket_from_identifier(idname, node): for outputsocket in node.outputs: if outputsocket.identifier == idname: return outputsocket return False def make_link(f_node_label, f_node_ident, to_node_label, to_node_ident, nodetree): fromnode = find_node_from_label(f_node_label, nodetree.nodes) if (fromnode == False): return False fromsocket = find_osocket_from_identifier(f_node_ident, fromnode) tonode = find_node_from_label(to_node_label, nodetree.nodes) if (tonode == False): return False tosocket = find_isocket_from_identifier(to_node_ident, tonode) nodetree.links.new(fromsocket, tosocket) return True ## ---> ## ====================================================================== ##!TODO: Shader type identification and bake setup def _nodes_for_type(node_tree:NodeTree, node_type:str) -> List[Node]: result = [x for x in node_tree.nodes if x.type == node_type] ## skip unconnected nodes from_nodes = [x.from_node for x in node_tree.links] to_nodes = [x.to_node for x in node_tree.links] all_nodes = set(from_nodes + to_nodes) result = list(filter(lambda x: x in all_nodes, result)) return result def output_nodes_for_engine(node_tree:NodeTree, engine:str) -> List[Node]: nodes = _nodes_for_type(node_tree, "OUTPUT_MATERIAL") return nodes def get_principled_nodes(node_tree:NodeTree) -> List[Node]: return _nodes_for_type(node_tree, "BSDF_PRINCIPLED") def identify_shader_type(node_tree:NodeTree) -> str: principled_nodes = get_principled_nodes(node_tree) emission_nodes = _nodes_for_type(node_tree, "EMISSION") mix_nodes = _nodes_for_type(node_tree, "MIX_SHADER") outputs = output_nodes_for_engine(node_tree, "CYCLES") total_shader_nodes = principled_nodes + emission_nodes + mix_nodes ## first type: principled straight into the output ## ---------------------------------------------------------------------- def create_principled_setup(material:Material, images:Dict[str,Image]): """ Creates a new shader setup in the tree of the specified material using the baked images, removing all old shader nodes. :param material: The material to change. :param images: The baked Images dictionary, name:Image pairs. """ node_tree = material.node_tree nodes = node_tree.nodes material.cycles.displacement_method = 'BOTH' principled_nodes = get_principled_nodes(node_tree) for node in filter(lambda x: not x in principled_nodes, nodes): nodes.remove(node) # Node Frame frame = nodes.new("NodeFrame") frame.location = (0, 0) frame.use_custom_color = True frame.color = (0.149763, 0.214035, 0.0590617) ## reuse the old BSDF if it exists to make sure the non-textured constant inputs are correct pnode = principled_nodes[0] if len(principled_nodes) else nodes.new("ShaderNodeBsdfPrincipled") pnode.location = (-25, 335) pnode.label = "pnode" pnode.use_custom_color = True pnode.color = (0.3375297784805298, 0.4575316309928894, 0.08615386486053467) pnode.parent = nodes["Frame"] # And the output node node = nodes.new("ShaderNodeOutputMaterial") node.location = (500, 200) node.label = "monode" node.show_options = False node.parent = nodes["Frame"] make_link("pnode", "BSDF", "monode", "Surface", node_tree) # ----------------------------------------------------------------- # 'COMBINED', 'AO', 'SHADOW', 'POSITION', 'NORMAL', 'UV', 'ROUGHNESS', # 'EMIT', 'ENVIRONMENT', 'DIFFUSE', 'GLOSSY', 'TRANSMISSION' ## These are the currently supported types. ## More could be supported at a future date. if "DIFFUSE" in images: node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, 250) node.label = "col_tex" node.image = images["DIFFUSE"] node.parent = nodes["Frame"] make_link("col_tex", "Color", "pnode", "Base Color", node_tree) if "METALLIC" in images: node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, 140) node.label = "metallic_tex" node.image = images["METALLIC"] node.parent = nodes["Frame"] make_link("metallic_tex", "Color", "pnode", "Metallic", node_tree) if "GLOSSY" in images: node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, 90) node.label = "specular_tex" node.image = images["GLOSSY"] node.parent = nodes["Frame"] make_link("specular_tex", "Color", "pnode", "Specular", node_tree) if "ROUGHNESS" in images: node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, 50) node.label = "roughness_tex" node.image = images["ROUGHNESS"] node.parent = nodes["Frame"] make_link("roughness_tex", "Color", "pnode", "Roughness", node_tree) if "TRANSMISSION" in images: node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, -90) node.label = "transmission_tex" node.image = images["TRANSMISSION"] node.parent = nodes["Frame"] make_link("transmission_tex", "Color", "pnode", "Transmission", node_tree) if "EMIT" in images: node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, -170) node.label = "emission_tex" node.image = images["EMIT"] node.parent = nodes["Frame"] make_link("emission_tex", "Color", "pnode", "Emission", node_tree) if "NORMAL" in images: node = nodes.new("ShaderNodeTexImage") node.hide = True node.location = (-500, -318.7) node.label = "normal_tex" image = images["NORMAL"] node.image = image node.parent = nodes["Frame"] # Additional normal map node for normal socket node = nodes.new("ShaderNodeNormalMap") node.location = (-220, -240) node.label = "normalmap" node.show_options = False node.parent = nodes["Frame"] make_link("normal_tex", "Color", "normalmap", "Color", node_tree) make_link("normalmap", "Normal", "pnode", "Normal", node_tree) # ----------------------------------------------------------------- ## wipe all labels for item in nodes: item.label = "" node = nodes["Frame"] node.label = "OMNI PBR" for type, image in images.items(): if type in {"DIFFUSE", "EMIT"}: image.colorspace_settings.name = "sRGB" else: image.colorspace_settings.name = "Non-Color" ## ====================================================================== def _selected_meshes(context:Context) -> List[Mesh]: """ :return: List[Mesh] of all selected mesh objects in active Blender Scene. """ return [x for x in context.selected_objects if x.type == "MESH"] def _material_can_be_baked(material:Material) -> bool: outputs = output_nodes_for_engine(material.node_tree, "CYCLES") if not len(outputs) == 1: return False try: from_node = outputs[0].inputs["Surface"].links[0].from_node except IndexError: return False ##!TODO: Support one level of mix with principled inputs if not from_node.type == "BSDF_PRINCIPLED": return False return True def omni_bake_maps_poll(context:Context) -> (int, Any): """ :return: 1 if we can bake 0 if no meshes are selected -1 if any selected meshes are already in the bake collection -2 if mesh contains non-bakeable materials -3 if Cycles renderer isn't loaded """ ## Cycles renderer is not available _, loaded_state = addon_utils.check("cycles") if not loaded_state: return (-3, None) selected = _selected_meshes(context) if not len(selected): return (0, None) for mesh in selected: for material in [slot.material for slot in mesh.material_slots]: if not _material_can_be_baked(material): return (-2, [mesh.name, material.name]) collection = bpy.data.collections.get(COLLECTION_NAME, None) if collection is None: ## We have selected meshes but no collection-- early out return (1, None) in_collection = [x for x in selected if x.name in collection.all_objects] if len(in_collection): return (-1, None) return (1, None) ## ====================================================================== class OmniBakerProperties(bpy.types.PropertyGroup): bake_metallic: BoolProperty(name="Metallic", default=True) merge_textures: BoolProperty(name="Merge Textures", description="Bake all materials for each object onto a single map", default=True) ## ====================================================================== class OBJECT_OT_omni_bake_maps(bpy.types.Operator): """Bake specified passes on the selected Mesh object.""" bl_idname = "omni.bake_maps" bl_label = "Bake Maps" bl_options = {"REGISTER", "UNDO"} base_bake_types = { ##!TODO: Possibly support these at a later date? # "COMBINED", "AO", "SHADOW", "POSITION", "UV", "ENVIRONMENT", "DIFFUSE", "NORMAL", "EMIT", "GLOSSY", "ROUGHNESS", "TRANSMISSION", } special_bake_types = { "METALLIC": "Metallic", } unwrap: BoolProperty(default=False, description="Unwrap") hide_original: BoolProperty(default=False, description="Hide Original") width: IntProperty(default=1024, min=128, max=8192, description="Width") height: IntProperty(default=1024, min=128, max=8192, description="Height") bake_types: StringProperty(default="DIFFUSE") merge_textures: BoolProperty(default=True, description="Merge Textures") @classmethod def poll(cls, context:Context) -> bool: return omni_bake_maps_poll(context)[0] == 1 def draw(self, context:Context): """Empty draw to disable the Operator Props Panel.""" pass def _get_bake_emission_target(self, node_tree:NodeTree) -> Node: bake_emission_name = "OmniBake_Emission" if not bake_emission_name in node_tree.nodes: node = node_tree.nodes.new("ShaderNodeEmission") node.name = bake_emission_name output = get_material_output(node_tree, "CYCLES") node.location = output.location + Vector((-200.0, -100.0)) return node_tree.nodes[bake_emission_name] def _copy_connection(self, material:Material, bsdf:Node, bake_type:str, target_socket:NodeSocket) -> bool: if not bake_type in self.special_bake_types: return False orig_socket = bsdf.inputs[self.special_bake_types[bake_type]] if not len(orig_socket.links): ## copy over the color and return if orig_socket.type == "VECTOR": for index in range(4): target_socket.default_value[index] = orig_socket.default_value elif orig_socket.type in {"VECTOR", "RGBA"}: for index in range(3): target_socket.default_value[index] = orig_socket.default_value[index] target_socket.default_value[3] = 1.0 else: ## should never arrive here return False else: input_socket = orig_socket.links[0].from_socket material.node_tree.links.new(input_socket, target_socket) return True def _create_bake_texture_names(self, ob:Object, bake_types:List[str]) -> List[str]: result = [] for material in [x.material for x in ob.material_slots]: material_name = material.name.rpartition('_baked')[0] for bake_type in bake_types: if self.merge_textures: image_name = f"{ob.name}__{bake_type}" else: image_name = f"{ob.name}_{material_name}_{bake_type}" result.append(image_name) return result def report(self, type:Set[str], message:str): print(message) super(OBJECT_OT_omni_bake_maps, self).report(type, message) def execute(self, context:Context) -> Set[str]: wm = context.window_manager scene = context.scene scene_engine = scene.render.engine scene.render.engine = "CYCLES" scene_use_clear = scene.render.bake.use_clear scene.render.bake.use_clear = False collection = prepare_collection(scene) all_bake_types = self.base_bake_types | self.special_bake_types.keys() valid_types_str = "Valid types are: " + ", ".join(all_bake_types) self.report({"INFO"}, f"Bake types: {self.bake_types}") bake_types = self.bake_types.split(",") if not len(bake_types): self.report({"ERROR"}, "No bake type specified. " + valid_types_str) for bake_type in bake_types: if not bake_type in all_bake_types: self.report({"ERROR"}, f"Bake type '{bake_type}' is not valid. " + valid_types_str) return {"CANCELLED"} selected_meshes = _selected_meshes(context) count = 0 total = 0 for mesh in selected_meshes: count += len(mesh.material_slots) * len(bake_types) wm.progress_begin(total, count) bpy.ops.object.mode_set(mode="OBJECT") for mesh_object in _selected_meshes(context): mesh_object.hide_select = mesh_object.hide_render = mesh_object.hide_viewport = False baked_ob = prepare_mesh(mesh_object, collection, unwrap=self.unwrap) uv_layer = "OmniBake" if self.unwrap else baked_ob.data.uv_layers.active.name bpy.ops.object.select_all(action="DESELECT") baked_ob.select_set(True) context.view_layer.objects.active = baked_ob self.report({"INFO"}, f"Baking Object {baked_ob.name}") baked_materials = [] ## Because of merge_textures, we have to create the names now and clear them ## before the whole bake process starts bake_image_names = self._create_bake_texture_names(baked_ob, bake_types) ## if merge_textures is on there'll be some repeats for image_name in set(bake_image_names): if image_name in bpy.data.images: bpy.data.images.remove(bpy.data.images[image_name]) image = bpy.data.images.new(image_name, self.width, self.height, float_buffer=(image_name.endswith(("NORMAL", "EMIT"))) ) # if bake_type in {"DIFFUSE", "EMIT"}: # image.colorspace_settings.name = "sRGB" # else: # image.colorspace_settings.name = "Non-Color" image.colorspace_settings.name = "Raw" if self.merge_textures: temp_file = NamedTemporaryFile(prefix=bake_type, suffix=".png", delete=False) image.filepath = temp_file.name image_index = 0 for material_index, material in enumerate([x.material for x in baked_ob.material_slots]): self.report({"INFO"}, f" => Material: {material.name}") tree = material.node_tree baked_ob.active_material_index = material_index for node in tree.nodes: node.select = False output = get_material_output(tree) bsdf = output.inputs["Surface"].links[0].from_node if "OmniBakeImage" in tree.nodes: tree.nodes.remove(tree.nodes["OmniBakeImage"]) bake_image_node = tree.nodes.new("ShaderNodeTexImage") bake_image_node.name = "OmniBakeImage" bake_image_node.location = output.location.copy() bake_image_node.location.x += 200.0 bake_image_node.select = True tree.nodes.active = bake_image_node ## for special cases bake_emission = self._get_bake_emission_target(tree) original_link = output.inputs["Surface"].links[0] original_from, original_to = original_link.from_socket, original_link.to_socket baked_images = {} for bake_type in bake_types: image_name = bake_image_names[image_index] image = bpy.data.images[image_name] bake_image_node.image = image.original if image.original else image self.report({"INFO"}, f"====> Baking {material.name} pass {bake_type}...") kwargs = {} if bake_type in {"DIFFUSE"}: ## ensure no black due to bad direct / indirect lighting kwargs["pass_filter"] = {"COLOR"} scene.render.bake.use_pass_indirect = False scene.render.bake.use_pass_direct = False if bake_type in self.special_bake_types: ## cheat by running the bake through emit after reconnecting real_bake_type = "EMIT" tree.links.new(bake_emission.outputs["Emission"], original_to) self._copy_connection(material, bsdf, bake_type, bake_emission.inputs["Color"]) else: real_bake_type = bake_type tree.links.new(original_from, original_to) ## have to do this every pass? if bake_type in {"DIFFUSE", "EMIT"}: image.colorspace_settings.name = "sRGB" else: image.colorspace_settings.name = "Non-Color" bpy.ops.object.bake(type=real_bake_type, width=self.width, height=self.height, uv_layer=uv_layer, use_clear=False, margin=1, **kwargs) if self.merge_textures: ## I know this seems weird, but if you don't save the file here ## post-bake when merging, the texture gets corrupted and you end ## up with a texture that's taking up ram, but can't be loaded ## for rendering (comes up pink in Cycles) image.save() self.report({"INFO"}, "... Done.") baked_images[bake_type] = image total += 1 image_index += 1 wm.progress_update(total) wm.update_tag() for node in bake_image_node, bake_emission: tree.nodes.remove(node) tree.links.new(original_from, original_to) baked_materials.append((material, baked_images)) for material, images in baked_materials: ## Perform conversion after all images are baked ## If this is not done, then errors can arise despite not ## replacing shader indices. create_principled_setup(material, images) for image in [bpy.data.images[x] for x in bake_image_names]: image.pack() ## Set new UV map as active if it exists if "OmniBake" in baked_ob.data.uv_layers: baked_ob.data.uv_layers["OmniBake"].active_render = True if self.hide_original: mesh_object.hide_set(True) wm.progress_end() scene.render.engine = scene_engine scene.render.bake.use_clear = scene_use_clear return {"FINISHED"} ## ====================================================================== module_classes = [ OBJECT_OT_omni_bake_maps, OmniBakerProperties, ] def register(): for cls in module_classes: bpy.utils.register_class(cls) bpy.types.Scene.omni_bake = bpy.props.PointerProperty(type=OmniBakerProperties) def unregister(): for cls in reversed(module_classes): bpy.utils.unregister_class(cls) try: del bpy.types.Scene.omni_bake except (AttributeError, RuntimeError): pass
21,781
Python
30.659884
111
0.678573
NVIDIA-Omniverse/blender_omniverse_addons/omni_panel/material_bake/data.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. from .bake_operation import bakestolist class MasterOperation: current_bake_operation = None total_bake_operations = 0 this_bake_operation_num = 0 orig_UVs_dict = {} baked_textures = [] prepared_mesh_objects = [] batch_name = "" orig_objects = [] orig_active_object = "" orig_sample_count = 0 @staticmethod def clear(): # Master variables called throughout bake process MasterOperation.orig_UVs_dict = {} MasterOperation.total_bake_operations = 0 MasterOperation.current_bake_operation = None MasterOperation.this_bake_operation_num = 0 MasterOperation.prepared_mesh_objects = [] MasterOperation.baked_textures = [] MasterOperation.batch_name = "" # Variables to reset your scene to what it was before bake. MasterOperation.orig_objects = [] MasterOperation.orig_active_object = "" MasterOperation.orig_sample_count = 0 return True class BakeOperation: #Constants PBR = "pbr" def __init__(self): #Mapping of object name to active UVs self.bake_mode = BakeOperation.PBR #So the example in the user prefs will work self.bake_objects = [] self.active_object = None #normal self.uv_mode = "normal" #pbr stuff self.pbr_selected_bake_types = [] def assemble_pbr_bake_list(self): self.pbr_selected_bake_types = bakestolist()
2,334
Python
28.935897
86
0.667095
NVIDIA-Omniverse/blender_omniverse_addons/omni_panel/material_bake/operators.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import bpy import sys import subprocess import os from .bake_operation import BakeStatus, bakestolist from .data import MasterOperation, BakeOperation from . import functions from . import bakefunctions from .background_bake import bgbake_ops from pathlib import Path import tempfile class OBJECT_OT_omni_bake_mapbake(bpy.types.Operator): """Start the baking process""" bl_idname = "object.omni_bake_mapbake" bl_label = "Bake" bl_options = {'REGISTER', 'UNDO'} # create undo state def execute(self, context): def commence_bake(needed_bake_modes): #Prepare the BakeStatus tracker for progress bar num_of_objects = 0 num_of_objects = len(bpy.context.selected_objects) total_maps = 0 for need in needed_bake_modes: if need == BakeOperation.PBR: total_maps+=(bakestolist(justcount=True) * num_of_objects) BakeStatus.total_maps = total_maps #Clear the MasterOperation stuff MasterOperation.clear() #Need to know the total operations MasterOperation.total_bake_operations = len(needed_bake_modes) #Master list of all ops bops = [] for need in needed_bake_modes: #Create operation bop = BakeOperation() #Set master level attributes #------------------------------- bop.bake_mode = need #------------------------------- bops.append(bop) functions.printmsg(f"Created operation for {need}") #Run queued operations for bop in bops: MasterOperation.this_bake_operation_num+=1 MasterOperation.current_bake_operation = bop if bop.bake_mode == BakeOperation.PBR: functions.printmsg("Running PBR bake") bakefunctions.doBake() return True ######################TEMP############################################### needed_bake_modes = [] needed_bake_modes.append(BakeOperation.PBR) #Clear the progress stuff BakeStatus.current_map = 0 BakeStatus.total_maps = 0 #If we have been called in background mode, just get on with it. Checks should be done. if "--background" in sys.argv: if "OmniBake_Bakes" in bpy.data.collections: #Remove any prior baked objects bpy.data.collections.remove(bpy.data.collections["OmniBake_Bakes"]) #Bake commence_bake(needed_bake_modes) self.report({"INFO"}, "Bake complete") return {'FINISHED'} functions.deselect_all_not_mesh() #We are in foreground, do usual checks """ result = True for need in needed_bake_modes: if not functions.startingChecks(bpy.context.selected_objects, need): result = False if not result: return {"CANCELLED"} """ #If the user requested background mode, fire that up now and exit if bpy.context.scene.bgbake == "bg": bpy.ops.wm.save_mainfile() filepath = filepath = bpy.data.filepath process = subprocess.Popen( [bpy.app.binary_path, "--background",filepath, "--python-expr",\ "import bpy;\ import os;\ from pathlib import Path;\ savepath=Path(bpy.data.filepath).parent / (str(os.getpid()) + \".blend\");\ bpy.ops.wm.save_as_mainfile(filepath=str(savepath), check_existing=False);\ bpy.ops.object.omni_bake_mapbake();"], shell=False) bgbake_ops.bgops_list.append([process, bpy.context.scene.prepmesh, bpy.context.scene.hidesourceobjects]) self.report({"INFO"}, "Background bake process started") return {'FINISHED'} #If we are doing this here and now, get on with it #Create a bake operation commence_bake(needed_bake_modes) self.report({"INFO"}, "Bake complete") return {'FINISHED'} #--------------------BACKGROUND BAKE---------------------------------- class OBJECT_OT_omni_bake_bgbake_status(bpy.types.Operator): bl_idname = "object.omni_bake_bgbake_status" bl_label = "Check on the status of bakes running in the background" def execute(self, context): msg_items = [] #Display remaining if len(bgbake_ops.bgops_list) == 0: msg_items.append("No background bakes are currently running") else: msg_items.append(f"--------------------------") for p in bgbake_ops.bgops_list: t = Path(tempfile.gettempdir()) t = t / f"OmniBake_Bgbake_{str(p[0].pid)}" try: with open(str(t), "r") as progfile: progress = progfile.readline() except: #No file yet, as no bake operation has completed yet. Holding message progress = 0 msg_items.append(f"RUNNING: Process ID: {str(p[0].pid)} - Progress {progress}%") msg_items.append(f"--------------------------") functions.ShowMessageBox(msg_items, "Background Bake Status(es)") return {'FINISHED'} class OBJECT_OT_omni_bake_bgbake_import(bpy.types.Operator): bl_idname = "object.omni_bake_bgbake_import" bl_label = "Import baked objects previously baked in the background" bl_options = {'REGISTER', 'UNDO'} # create undo state def execute(self, context): if bpy.context.mode != "OBJECT": self.report({"ERROR"}, "You must be in object mode") return {'CANCELLED'} for p in bgbake_ops.bgops_list_finished: savepath = Path(bpy.data.filepath).parent pid_str = str(p[0].pid) path = savepath / (pid_str + ".blend") path = str(path) + "\\Collection\\" #Record the objects and collections before append (as append doesn't give us a reference to the new stuff) functions.spot_new_items(initialise=True, item_type="objects") functions.spot_new_items(initialise=True, item_type="collections") functions.spot_new_items(initialise=True, item_type="images") #Append bpy.ops.wm.append(filename="OmniBake_Bakes", directory=path, use_recursive=False, active_collection=False) #If we didn't actually want the objects, delete them if not p[1]: #Delete objects we just imported (leaving only textures) for obj_name in functions.spot_new_items(initialise=False, item_type = "objects"): bpy.data.objects.remove(bpy.data.objects[obj_name]) for col_name in functions.spot_new_items(initialise=False, item_type = "collections"): bpy.data.collections.remove(bpy.data.collections[col_name]) #If we have to hide the source objects, do it if p[2]: #Get the newly introduced objects: objects_before_names = functions.spot_new_items(initialise=False, item_type="objects") for obj_name in objects_before_names: #Try this in case there are issues with long object names.. better than a crash try: bpy.data.objects[obj_name.replace("_Baked", "")].hide_set(True) except: pass #Delete the temp blend file try: os.remove(str(savepath / pid_str) + ".blend") os.remove(str(savepath / pid_str) + ".blend1") except: pass #Clear list for next time bgbake_ops.bgops_list_finished = [] #Confirm back to user self.report({"INFO"}, "Import complete") messagelist = [] messagelist.append(f"{len(functions.spot_new_items(initialise=False, item_type='objects'))} objects imported") messagelist.append(f"{len(functions.spot_new_items(initialise=False, item_type='images'))} textures imported") functions.ShowMessageBox(messagelist, "Import complete", icon = 'INFO') #If we imported an image, and we already had an image with the same name, get rid of the original in favour of the imported new_images_names = functions.spot_new_items(initialise=False, item_type="images") #Find any .001s for imgname in new_images_names: try: int(imgname[-3:]) #Delete the existing version bpy.data.images.remove(bpy.data.images[imgname[0:-4]]) #Rename our version bpy.data.images[imgname].name = imgname[0:-4] except ValueError: pass return {'FINISHED'} class OBJECT_OT_omni_bake_bgbake_clear(bpy.types.Operator): """Delete the background bakes because you don't want to import them into Blender. NOTE: If you chose to save bakes or FBX externally, these are safe and NOT deleted. This is just if you don't want to import into this Blender session""" bl_idname = "object.omni_bake_bgbake_clear" bl_label = "" bl_options = {'REGISTER', 'UNDO'} # create undo state def execute(self, context): savepath = Path(bpy.data.filepath).parent for p in bgbake_ops.bgops_list_finished: pid_str = str(p[0].pid) try: os.remove(str(savepath / pid_str) + ".blend") os.remove(str(savepath / pid_str) + ".blend1") except: pass bgbake_ops.bgops_list_finished = [] return {'FINISHED'}
11,546
Python
38.409556
240
0.540274
NVIDIA-Omniverse/blender_omniverse_addons/omni_panel/material_bake/bake_operation.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import bpy # Bake helper method def bakestolist(justcount = False): #Assemble properties into list selectedbakes = [] selectedbakes.append("diffuse") if bpy.context.scene.selected_col else False selectedbakes.append("metalness") if bpy.context.scene.selected_metal else False selectedbakes.append("roughness") if bpy.context.scene.selected_rough else False selectedbakes.append("normal") if bpy.context.scene.selected_normal else False selectedbakes.append("transparency") if bpy.context.scene.selected_trans else False selectedbakes.append("transparencyroughness") if bpy.context.scene.selected_transrough else False selectedbakes.append("emission") if bpy.context.scene.selected_emission else False selectedbakes.append("specular") if bpy.context.scene.selected_specular else False selectedbakes.append("alpha") if bpy.context.scene.selected_alpha else False selectedbakes.append("sss") if bpy.context.scene.selected_sss else False selectedbakes.append("ssscol") if bpy.context.scene.selected_ssscol else False if justcount: return len(selectedbakes) else: return selectedbakes class BakeStatus: total_maps = 0 current_map = 0
2,095
Python
40.919999
101
0.741766
NVIDIA-Omniverse/blender_omniverse_addons/omni_panel/material_bake/bakefunctions.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import bpy from . import functions import sys from .bake_operation import BakeStatus from .data import MasterOperation, BakeOperation def optimize(): current_bake_op = MasterOperation.current_bake_operation MasterOperation.orig_sample_count = bpy.context.scene.cycles.samples functions.printmsg("Reducing sample count to 16 for more efficient baking") bpy.context.scene.cycles.samples = 16 return True def undo_optimize(): #Restore sample count bpy.context.scene.cycles.samples = MasterOperation.orig_sample_count def common_bake_prep(): #--------------Set Bake Operation Variables---------------------------- current_bake_op = MasterOperation.current_bake_operation functions.printmsg("================================") functions.printmsg("---------Beginning Bake---------") functions.printmsg(f"{current_bake_op.bake_mode}") functions.printmsg("================================") #Run information op_num = MasterOperation.this_bake_operation_num firstop = False lastop = False if op_num == 1: firstop = True if op_num == MasterOperation.total_bake_operations: lastop = True #If this is a pbr bake, gather the selected maps if current_bake_op.bake_mode in {BakeOperation.PBR}: current_bake_op.assemble_pbr_bake_list() #Record batch name MasterOperation.batch_name = bpy.context.scene.batchName #Set values based on viewport selection current_bake_op.orig_objects = bpy.context.selected_objects.copy() current_bake_op.orig_active_object = bpy.context.active_object current_bake_op.bake_objects = bpy.context.selected_objects.copy() current_bake_op.active_object = bpy.context.active_object current_bake_op.orig_engine = bpy.context.scene.render.engine #Record original UVs for everyone if firstop: for obj in current_bake_op.bake_objects: try: MasterOperation.orig_UVs_dict[obj.name] = obj.data.uv_layers.active.name except AttributeError: MasterOperation.orig_UVs_dict[obj.name] = False #Record the rendering engine if firstop: MasterOperation.orig_engine = bpy.context.scene.render.engine current_bake_op.uv_mode = "normal" #---------------------------------------------------------------------- #Force it to cycles bpy.context.scene.render.engine = "CYCLES" bpy.context.scene.render.bake.use_selected_to_active = False functions.printmsg(f"Selected to active is now {bpy.context.scene.render.bake.use_selected_to_active}") #If the user doesn't have a GPU, but has still set the render device to GPU, set it to CPU if not bpy.context.preferences.addons["cycles"].preferences.has_active_device(): bpy.context.scene.cycles.device = "CPU" #Clear the trunc num for this session functions.trunc_num = 0 functions.trunc_dict = {} #Turn off that dam use clear. bpy.context.scene.render.bake.use_clear = False #Do what we are doing with UVs (only if we are the primary op) if firstop: functions.processUVS() #Optimize optimize() #Make sure the normal y setting is at default bpy.context.scene.render.bake.normal_g = "POS_Y" return True def common_bake_finishing(): #Run information current_bake_op = MasterOperation.current_bake_operation op_num = MasterOperation.this_bake_operation_num firstop = False lastop = False if op_num == 1: firstop = True if op_num == MasterOperation.total_bake_operations: lastop = True #Restore the original rendering engine if lastop: bpy.context.scene.render.engine = MasterOperation.orig_engine undo_optimize() #If prep mesh, or save object is selected, or running in the background, then do it #We do this on primary run only if firstop: if(bpy.context.scene.prepmesh or "--background" in sys.argv): functions.prepObjects(current_bake_op.bake_objects, current_bake_op.bake_mode) #If the user wants it, restore the original active UV map so we don't confuse anyone functions.restore_Original_UVs() #Restore the original object selection so we don't confuse anyone bpy.ops.object.select_all(action="DESELECT") for obj in current_bake_op.orig_objects: obj.select_set(True) bpy.context.view_layer.objects.active = current_bake_op.orig_active_object #Hide all the original objects if bpy.context.scene.prepmesh and bpy.context.scene.hidesourceobjects and lastop: for obj in current_bake_op.bake_objects: obj.hide_set(True) #Delete placeholder material if lastop and "OmniBake_Placeholder" in bpy.data.materials: bpy.data.materials.remove(bpy.data.materials["OmniBake_Placeholder"]) if "--background" in sys.argv: bpy.ops.wm.save_mainfile() def doBake(): current_bake_op = MasterOperation.current_bake_operation #Do the prep we need to do for all bake types common_bake_prep() #Loop over the bake modes we are using def doBake_actual(): IMGNAME = "" for thisbake in current_bake_op.pbr_selected_bake_types: for obj in current_bake_op.bake_objects: #Reset the already processed list mats_done = [] functions.printmsg(f"Baking object: {obj.name}") #Truncate if needed from this point forward OBJNAME = functions.trunc_if_needed(obj.name) #Create the image we need for this bake (Delete if exists) IMGNAME = functions.gen_image_name(obj.name, thisbake) functions.create_Images(IMGNAME, thisbake, obj.name) #Prep the materials one by one materials = obj.material_slots for matslot in materials: mat = bpy.data.materials.get(matslot.name) if mat.name in mats_done: functions.printmsg(f"Skipping material {mat.name}, already processed") #Skip this loop #We don't want to process any materials more than once or bad things happen continue else: mats_done.append(mat.name) #Make sure we are using nodes if not mat.use_nodes: functions.printmsg(f"Material {mat.name} wasn't using nodes. Have enabled nodes") mat.use_nodes = True nodetree = mat.node_tree nodes = nodetree.nodes #Take a copy of material to restore at the end of the process functions.backupMaterial(mat) #Create the image node and set to the bake texutre we are using imgnode = nodes.new("ShaderNodeTexImage") imgnode.image = bpy.data.images[IMGNAME] imgnode.label = "OmniBake" #Remove all disconnected nodes so don't interfere with typing the material functions.removeDisconnectedNodes(nodetree) #Use additional shader types functions.useAdditionalShaderTypes(nodetree, nodes) #Normal and emission bakes require no further material prep. Just skip the rest if(thisbake != "normal" and thisbake != "emission"): #Work out what type of material we are dealing with here and take correct action mat_type = functions.getMatType(nodetree) if(mat_type == "MIX"): functions.setup_mix_material(nodetree, thisbake) elif(mat_type == "PURE_E"): functions.setup_pure_e_material(nodetree, thisbake) elif(mat_type == "PURE_P"): functions.setup_pure_p_material(nodetree, thisbake) #Last action before leaving this material, make the image node selected and active functions.deselectAllNodes(nodes) imgnode.select = True nodetree.nodes.active = imgnode #Select only this object functions.selectOnlyThis(obj) #We are done with this image, set colour space functions.set_image_internal_col_space(bpy.data.images[IMGNAME], thisbake) #Bake the object for this bake mode functions.bakeoperation(thisbake, bpy.data.images[IMGNAME]) #Update tracking BakeStatus.current_map+=1 functions.printmsg(f"Bake maps {BakeStatus.current_map} of {BakeStatus.total_maps} complete") functions.write_bake_progress(BakeStatus.current_map, BakeStatus.total_maps) #Restore the original materials functions.printmsg("Restoring original materials") functions.restoreAllMaterials() functions.printmsg("Restore complete") #Last thing we do with this image is scale it functions.sacle_image_if_needed(bpy.data.images[IMGNAME]) #Do the bake at least once doBake_actual() #Finished baking. Perform wind down actions common_bake_finishing()
10,620
Python
36.932143
109
0.608004
NVIDIA-Omniverse/blender_omniverse_addons/omni_panel/material_bake/functions.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. from pathlib import Path from ..ui import OmniBakePreferences import bpy from bpy.types import * import os import sys import tempfile from . import material_setup from .data import MasterOperation #Global variables psocketname = { "diffuse": "Base Color", "metalness": "Metallic", "roughness": "Roughness", "normal": "Normal", "transparency": "Transmission", "transparencyroughness": "Transmission Roughness", "specular": "Specular", "alpha": "Alpha", "sss": "Subsurface", "ssscol": "Subsurface Color", "displacement": "Displacement" } def printmsg(msg): print(f"BAKE: {msg}") def gen_image_name(obj_name, baketype): current_bake_op = MasterOperation.current_bake_operation #First, let's get the format string we are working with prefs = bpy.context.preferences.addons[OmniBakePreferences.bl_idname].preferences image_name = prefs.img_name_format #The easy ones image_name = image_name.replace("%OBJ%", obj_name) image_name = image_name.replace("%BATCH%", bpy.context.scene.batchName) #Bake mode image_name = image_name.replace("%BAKEMODE%", current_bake_op.bake_mode) #The hard ones if baketype == "diffuse": image_name = image_name.replace("%BAKETYPE%", prefs.diffuse_alias) elif baketype == "metalness": image_name = image_name.replace("%BAKETYPE%", prefs.metal_alias) elif baketype == "roughness": image_name = image_name.replace("%BAKETYPE%", prefs.roughness_alias) elif baketype == "normal": image_name = image_name.replace("%BAKETYPE%", prefs.normal_alias) elif baketype == "transparency": image_name = image_name.replace("%BAKETYPE%", prefs.transmission_alias) elif baketype == "transparencyroughness": image_name = image_name.replace("%BAKETYPE%", prefs.transmissionrough_alias) elif baketype == "emission": image_name = image_name.replace("%BAKETYPE%", prefs.emission_alias) elif baketype == "specular": image_name = image_name.replace("%BAKETYPE%", prefs.specular_alias) elif baketype == "alpha": image_name = image_name.replace("%BAKETYPE%", prefs.alpha_alias) elif baketype == "sss": image_name = image_name.replace("%BAKETYPE%", prefs.sss_alias) elif baketype == "ssscol": image_name = image_name.replace("%BAKETYPE%", prefs.ssscol_alias) #Displacement is not currently Implemented elif baketype == "displacement": image_name = image_name.replace("%BAKETYPE%", prefs.displacement_alias) else: image_name = image_name.replace("%BAKETYPE%", baketype) return image_name def removeDisconnectedNodes(nodetree): nodes = nodetree.nodes #Loop through nodes repeat = False for node in nodes: if node.type == "BSDF_PRINCIPLED" and len(node.outputs[0].links) == 0: #Not a player, delete node nodes.remove(node) repeat = True elif node.type == "EMISSION" and len(node.outputs[0].links) == 0: #Not a player, delete node nodes.remove(node) repeat = True elif node.type == "MIX_SHADER" and len(node.outputs[0].links) == 0: #Not a player, delete node nodes.remove(node) repeat = True elif node.type == "ADD_SHADER" and len(node.outputs[0].links) == 0: #Not a player, delete node nodes.remove(node) repeat = True #Displacement is not currently Implemented elif node.type == "DISPLACEMENT" and len(node.outputs[0].links) == 0: #Not a player, delete node nodes.remove(node) repeat = True #If we removed any nodes, we need to do this again if repeat: removeDisconnectedNodes(nodetree) def backupMaterial(mat): dup = mat.copy() dup.name = mat.name + "_OmniBake" def restoreAllMaterials(): #Not efficient but, if we are going to do things this way, we need to loop over every object in the scene dellist = [] for obj in bpy.data.objects: for slot in obj.material_slots: origname = slot.name #Try to set to the corresponding material that was the backup try: slot.material = bpy.data.materials[origname + "_OmniBake"] #If not already on our list, log the original material (that we messed with) for mass deletion if origname not in dellist: dellist.append(origname) except KeyError: #Not been backed up yet. Must not have processed an object with that material yet pass #Delete the unused materials for matname in dellist: bpy.data.materials.remove(bpy.data.materials[matname]) #Rename all materials to the original name, leaving us where we started for mat in bpy.data.materials: if "_OmniBake" in mat.name: mat.name = mat.name.replace("_OmniBake", "") def create_Images(imgname, thisbake, objname): #thisbake is subtype e.g. diffuse, ao, etc. current_bake_op = MasterOperation.current_bake_operation global_mode = current_bake_op.bake_mode batch = MasterOperation.batch_name printmsg(f"Creating image {imgname}") #Get the image height and width from the interface IMGHEIGHT = bpy.context.scene.imgheight IMGWIDTH = bpy.context.scene.imgwidth #If it already exists, remove it. if(imgname in bpy.data.images): bpy.data.images.remove(bpy.data.images[imgname]) #Create image 32 bit or not 32 bit if thisbake == "normal" : image = bpy.data.images.new(imgname, IMGWIDTH, IMGHEIGHT, float_buffer=True) else: image = bpy.data.images.new(imgname, IMGWIDTH, IMGHEIGHT, float_buffer=False) #Set tags image["SB_objname"] = objname image["SB_batch"] = batch image["SB_globalmode"] = global_mode image["SB_thisbake"] = thisbake #Always mark new images fake user when generated in the background if "--background" in sys.argv: image.use_fake_user = True #Store it at bake operation level MasterOperation.baked_textures.append(image) def deselectAllNodes(nodes): for node in nodes: node.select = False def findSocketConnectedtoP(pnode, thisbake): #Get socket name for this bake mode socketname = psocketname[thisbake] #Get socket of the pnode socket = pnode.inputs[socketname] fromsocket = socket.links[0].from_socket #Return the socket connected to the pnode return fromsocket def get_input_socket_name(node, thisbake) -> str: pass def createdummynodes(nodetree, thisbake): #Loop through pnodes nodes = nodetree.nodes for node in nodes: if node.type in {"BSDF_PRINCIPLED"}: pnode = node #Get socket name for this bake mode socketname = psocketname[thisbake] #Get socket of the pnode psocket = pnode.inputs[socketname] #If it has something plugged in, we can leave it here if(len(psocket.links) > 0): continue #Get value of the unconnected socket val = psocket.default_value #If this is base col or ssscol, add an RGB node and set it's value to that of the socket if(socketname == "Base Color" or socketname == "Subsurface Color"): rgb = nodetree.nodes.new("ShaderNodeRGB") rgb.outputs[0].default_value = val rgb.label = "OmniBake" nodetree.links.new(rgb.outputs[0], psocket) #If this is anything else, use a value node else: vnode = nodetree.nodes.new("ShaderNodeValue") vnode.outputs[0].default_value = val vnode.label = "OmniBake" nodetree.links.new(vnode.outputs[0], psocket) def bakeoperation(thisbake, img): printmsg(f"Beginning bake for {thisbake}") if(thisbake != "normal"): bpy.ops.object.bake(type="EMIT", save_mode="INTERNAL", use_clear=True) else: bpy.ops.object.bake(type="NORMAL", save_mode="INTERNAL", use_clear=True) #Always pack the image for now img.pack() def startingChecks(objects, bakemode): messages = [] if len(objects) == 0: messages.append("ERROR: Nothing selected for bake") #Are any of our objects hidden? for obj in objects: if (obj.hide_viewport == True) or (obj.hide_get(view_layer=bpy.context.view_layer) == True): messages.append(f"ERROR: Object '{obj.name}' is hidden in viewport (eye icon in outliner) or in the current view lawyer (computer screen icon in outliner)") #What about hidden from rendering? for obj in objects: if obj.hide_render: messages.append(f"ERROR: Object '{obj.name}' is hidden for rendering (camera icon in outliner)") #None of the objects can have zero faces for obj in objects: if len(obj.data.polygons) < 1: messages.append(f"ERROR: Object '{obj.name}' has no faces") if(bpy.context.mode != "OBJECT"): ##!TODO(kiki): switch back messages.append("ERROR: Not in object mode") #PBR Bake Checks for obj in objects: #Is it mesh? if obj.type != "MESH": messages.append(f"ERROR: Object {obj.name} is not mesh") #Must continue here - other checks will throw exceptions continue #Are UVs OK? if bpy.context.scene.newUVoption == False and len(obj.data.uv_layers) == 0: messages.append(f"ERROR: Object {obj.name} has no UVs, and you aren't generating new ones") continue #Are materials OK? Fix if not if not checkObjectValidMaterialConfig(obj): fix_invalid_material_config(obj) #Do all materials have valid PBR config? if bpy.context.scene.more_shaders == False: for slot in obj.material_slots: mat = slot.material result = checkMatsValidforPBR(mat) if len(result) > 0: for node_name in result: messages.append(f"ERROR: Node '{node_name}' in material '{mat.name}' on object '{obj.name}' is not valid for PBR bake. In order to use more than just Princpled, Emission, and Mix Shaders, turn on 'Use additional Shader Types'!") else: for slot in obj.material_slots: mat = slot.material result = checkExtraMatsValidforPBR(mat) if len(result) > 0: for node_name in result: messages.append(f"ERROR: Node '{node_name}' in material '{mat.name}' on object '{obj.name}' is not supported") #Let's report back if len(messages) != 0: ShowMessageBox(messages, "Errors occured", "ERROR") return False else: #If we get here then everything looks good return True #------------------------------------------ def processUVS(): current_bake_op = MasterOperation.current_bake_operation #------------------NEW UVS ------------------------------------------------------------ if bpy.context.scene.newUVoption: printmsg("We are generating new UVs") printmsg("We are unwrapping each object individually with Smart UV Project") objs = current_bake_op.bake_objects for obj in objs: if("OmniBake" in obj.data.uv_layers): obj.data.uv_layers.remove(obj.data.uv_layers["OmniBake"]) obj.data.uv_layers.new(name="OmniBake") obj.data.uv_layers["OmniBake"].active = True #Will set active object selectOnlyThis(obj) #Blender 2.91 kindly breaks Smart UV Project in object mode so... yeah... thanks bpy.ops.object.mode_set(mode="EDIT", toggle=False) #Unhide any geo that's hidden in edit mode or it'll cause issues. bpy.ops.mesh.reveal() bpy.ops.mesh.select_all(action="SELECT") bpy.ops.mesh.reveal() bpy.ops.uv.smart_project(island_margin=bpy.context.scene.unwrapmargin) bpy.ops.object.mode_set(mode="OBJECT", toggle=False) #------------------END NEW UVS ------------------------------------------------------------ else: #i.e. New UV Option was not selected printmsg("We are working with the existing UVs") if bpy.context.scene.prefer_existing_sbmap: printmsg("We are preferring existing UV maps called OmniBake. Setting them to active") for obj in current_bake_op.bake_objects: if("OmniBake" in obj.data.uv_layers): obj.data.uv_layers["OmniBake"].active = True #Before we finish, restore the original selected and active objects bpy.ops.object.select_all(action="DESELECT") for obj in current_bake_op.orig_objects: obj.select_set(True) bpy.context.view_layer.objects.active = current_bake_op.orig_active_object #Done return True def restore_Original_UVs(): current_bake_op = MasterOperation.current_bake_operation #First the bake objects for obj in current_bake_op.bake_objects: if MasterOperation.orig_UVs_dict[obj. name] != None: original_uv = MasterOperation.orig_UVs_dict[obj.name] obj.data.uv_layers.active = obj.data.uv_layers[original_uv] def setupEmissionRunThrough(nodetree, m_output_node, thisbake, ismix=False): nodes = nodetree.nodes pnode = find_pnode(nodetree) #Create emission shader emissnode = nodes.new("ShaderNodeEmission") emissnode.label = "OmniBake" #Connect to output if(ismix): #Find the existing mix node before we create a new one existing_m_node = find_mnode(nodetree) #Add a mix shader node and label it mnode = nodes.new("ShaderNodeMixShader") mnode.label = "OmniBake" #Connect new mix node to the output fromsocket = mnode.outputs[0] tosocket = m_output_node.inputs[0] nodetree.links.new(fromsocket, tosocket) #Connect new emission node to the first mix slot (leaving second empty) fromsocket = emissnode.outputs[0] tosocket = mnode.inputs[1] nodetree.links.new(fromsocket, tosocket) #If there is one, plug the factor from the original mix node into our new mix node if(len(existing_m_node.inputs[0].links) > 0): fromsocket = existing_m_node.inputs[0].links[0].from_socket tosocket = mnode.inputs[0] nodetree.links.new(fromsocket, tosocket) #If no input, add a value node set to same as the mnode factor else: val = existing_m_node.inputs[0].default_value vnode = nodes.new("ShaderNodeValue") vnode.label = "OmniBake" vnode.outputs[0].default_value = val fromsocket = vnode.outputs[0] tosocket = mnode.inputs[0] nodetree.links.new(fromsocket, tosocket) else: #Just connect our new emission to the output fromsocket = emissnode.outputs[0] tosocket = m_output_node.inputs[0] nodetree.links.new(fromsocket, tosocket) #Create dummy nodes for the socket for this bake if needed createdummynodes(nodetree, pnode, thisbake) #Connect whatever is in Principled Shader for this bakemode to the emission fromsocket = findSocketConnectedtoP(pnode, thisbake) tosocket = emissnode.inputs[0] nodetree.links.new(fromsocket, tosocket) #---------------------Node Finders--------------------------- def find_pnode(nodetree): nodes = nodetree.nodes for node in nodes: if(node.type == "BSDF_PRINCIPLED"): return node #We never found it return False def find_enode(nodetree): nodes = nodetree.nodes for node in nodes: if(node.type == "EMISSION"): return node #We never found it return False def find_mnode(nodetree): nodes = nodetree.nodes for node in nodes: if(node.type == "MIX_SHADER"): return node #We never found it return False def find_onode(nodetree): nodes = nodetree.nodes for node in nodes: if(node.type == "OUTPUT_MATERIAL"): return node #We never found it return False def checkObjectValidMaterialConfig(obj): #Firstly, check it actually has material slots if len(obj.material_slots) == 0: return False #Check the material slots all have a material assigned for slot in obj.material_slots: if slot.material == None: return False #All materials must be using nodes for slot in obj.material_slots: if slot.material.use_nodes == False: return False #If we get here, everything looks good return True def getMatType(nodetree): if (find_pnode(nodetree) and find_mnode(nodetree)): return "MIX" elif(find_pnode(nodetree)): return "PURE_P" elif(find_enode(nodetree)): return "PURE_E" else: return "INVALID" def prepObjects(objs, baketype): current_bake_op = MasterOperation.current_bake_operation printmsg("Creating prepared object") #First we prepare objectes export_objects = [] for obj in objs: #-------------Create the prepared mesh---------------------------------------- #Object might have a truncated name. Should use this if it's there objname = trunc_if_needed(obj.name) new_obj = obj.copy() new_obj.data = obj.data.copy() new_obj["SB_createdfrom"] = obj.name #clear all materials new_obj.data.materials.clear() new_obj.name = objname + "_OmniBake" #Create a collection for our baked objects if it doesn't exist if "OmniBake_Bakes" not in bpy.data.collections: c = bpy.data.collections.new("OmniBake_Bakes") bpy.context.scene.collection.children.link(c) #Make sure it's visible and enabled for current view laywer or it screws things up bpy.context.view_layer.layer_collection.children["OmniBake_Bakes"].exclude = False bpy.context.view_layer.layer_collection.children["OmniBake_Bakes"].hide_viewport = False c = bpy.data.collections["OmniBake_Bakes"] #Link object to our new collection c.objects.link(new_obj) #Append this object to the export list export_objects.append(new_obj) #---------------------------------UVS-------------------------------------- uvlayers = new_obj.data.uv_layers #If we generated new UVs, it will be called "OmniBake" and we are using that. End of. #Same if we are being called for Sketchfab upload, and last bake used new UVs if bpy.context.scene.newUVoption: pass #If there is an existing map called OmniBake, and we are preferring it, use that elif ("OmniBake" in uvlayers) and bpy.context.scene.prefer_existing_sbmap: pass #Even if we are not preferring it, if there is just one map called OmniBake, we are using that elif ("OmniBake" in uvlayers) and len(uvlayers) <2: pass #If there is an existing map called OmniBake, and we are not preferring it, it has to go #Active map becommes OmniBake elif ("OmniBake" in uvlayers) and not bpy.context.scene.prefer_existing_sbmap: uvlayers.remove(uvlayers["OmniBake"]) active_layer = uvlayers.active active_layer.name = "OmniBake" #Finally, if none of the above apply, we are just using the active map #Active map becommes OmniBake else: active_layer = uvlayers.active active_layer.name = "OmniBake" #In all cases, we can now delete everything other than OmniBake deletelist = [] for uvlayer in uvlayers: if (uvlayer.name != "OmniBake"): deletelist.append(uvlayer.name) for uvname in deletelist: uvlayers.remove(uvlayers[uvname]) #---------------------------------END UVS-------------------------------------- #Create a new material #call it same as object + batchname + baked mat = bpy.data.materials.get(objname + "_" + bpy.context.scene.batchName + "_baked") if mat is None: mat = bpy.data.materials.new(name=objname + "_" + bpy.context.scene.batchName +"_baked") # Assign it to object mat.use_nodes = True new_obj.data.materials.append(mat) #Set up the materials for each object for obj in export_objects: #Should only have one material mat = obj.material_slots[0].material nodetree = mat.node_tree material_setup.create_principled_setup(nodetree, obj) #Change object name to avoid collisions obj.name = obj.name.replace("_OmniBake", "_Baked") bpy.ops.object.select_all(action="DESELECT") for obj in export_objects: obj.select_set(state=True) if (not bpy.context.scene.prepmesh) and (not "--background" in sys.argv): #Deleted duplicated objects for obj in export_objects: bpy.data.objects.remove(obj) #Add the created objects to the bake operation list to keep track of them else: for obj in export_objects: MasterOperation.prepared_mesh_objects.append(obj) def selectOnlyThis(obj): bpy.ops.object.select_all(action="DESELECT") obj.select_set(state=True) bpy.context.view_layer.objects.active = obj def setup_pure_p_material(nodetree, thisbake): #Create dummy nodes as needed createdummynodes(nodetree, thisbake) #Create emission shader nodes = nodetree.nodes m_output_node = find_onode(nodetree) loc = m_output_node.location #Create an emission shader emissnode = nodes.new("ShaderNodeEmission") emissnode.label = "OmniBake" emissnode.location = loc emissnode.location.y = emissnode.location.y + 200 #Connect our new emission to the output fromsocket = emissnode.outputs[0] tosocket = m_output_node.inputs[0] nodetree.links.new(fromsocket, tosocket) #Connect whatever is in Principled Shader for this bakemode to the emission fromsocket = findSocketConnectedtoP(find_pnode(nodetree), thisbake) tosocket = emissnode.inputs[0] nodetree.links.new(fromsocket, tosocket) def setup_pure_e_material(nodetree, thisbake): #If baking something other than emission, mute the emission modes so they don't contaiminate our bake if thisbake != "Emission": nodes = nodetree.nodes for node in nodes: if node.type == "EMISSION": node.mute = True node.label = "OmniBakeMuted" def setup_mix_material(nodetree, thisbake): #No need to mute emission nodes. They are automuted by setting the RGBMix to black nodes = nodetree.nodes #Create dummy nodes as needed createdummynodes(nodetree, thisbake) #For every mix shader, create a mixrgb above it #Also connect the factor input to the same thing created_mix_nodes = {} for node in nodes: if node.type == "MIX_SHADER": loc = node.location rgbmix = nodetree.nodes.new("ShaderNodeMixRGB") rgbmix.label = "OmniBake" rgbmix.location = loc rgbmix.location.y = rgbmix.location.y + 200 #If there is one, plug the factor from the original mix node into our new mix node if(len(node.inputs[0].links) > 0): fromsocket = node.inputs[0].links[0].from_socket tosocket = rgbmix.inputs["Fac"] nodetree.links.new(fromsocket, tosocket) #If no input, add a value node set to same as the mnode factor else: val = node.inputs[0].default_value vnode = nodes.new("ShaderNodeValue") vnode.label = "OmniBake" vnode.outputs[0].default_value = val fromsocket = vnode.outputs[0] tosocket = rgbmix.inputs[0] nodetree.links.new(fromsocket, tosocket) #Keep a dictionary with paired shader mix node created_mix_nodes[node.name] = rgbmix.name #Loop over the RGBMix nodes that we created for node in created_mix_nodes: mshader = nodes[node] rgb = nodes[created_mix_nodes[node]] #Mshader - Socket 1 #First, check if there is anything plugged in at all if len(mshader.inputs[1].links) > 0: fromnode = mshader.inputs[1].links[0].from_node if fromnode.type == "BSDF_PRINCIPLED": #Get the socket we are looking for, and plug it into RGB socket 1 fromsocket = findSocketConnectedtoP(fromnode, thisbake) nodetree.links.new(fromsocket, rgb.inputs[1]) elif fromnode.type == "MIX_SHADER": #If it's a mix shader on the other end, connect the equivilent RGB node #Get the RGB node for that mshader fromrgb = nodes[created_mix_nodes[fromnode.name]] fromsocket = fromrgb.outputs[0] nodetree.links.new(fromsocket, rgb.inputs[1]) elif fromnode.type == "EMISSION": #Set this input to black rgb.inputs[1].default_value = (0.0, 0.0, 0.0, 1) elif fromnode.type == "GROUP": pass else: printmsg("Error, invalid node config") else: rgb.inputs[1].default_value = (0.0, 0.0, 0.0, 1) #Mshader - Socket 2 if len(mshader.inputs[2].links) > 0: fromnode = mshader.inputs[2].links[0].from_node if fromnode.type == "BSDF_PRINCIPLED": #Get the socket we are looking for, and plug it into RGB socket 2 fromsocket = findSocketConnectedtoP(fromnode, thisbake) nodetree.links.new(fromsocket, rgb.inputs[2]) elif fromnode.type == "MIX_SHADER": #If it's a mix shader on the other end, connect the equivilent RGB node #Get the RGB node for that mshader fromrgb = nodes[created_mix_nodes[fromnode.name]] fromsocket = fromrgb.outputs[0] nodetree.links.new(fromsocket, rgb.inputs[2]) elif fromnode.type == "EMISSION": #Set this input to black rgb.inputs[2].default_value = (0.0, 0.0, 0.0, 1) elif fromnode.type == "GROUP": pass else: printmsg("Error, invalid node config") else: rgb.inputs[2].default_value = (0.0, 0.0, 0.0, 1) #Find the output node with location m_output_node = find_onode(nodetree) loc = m_output_node.location #Create an emission shader emissnode = nodes.new("ShaderNodeEmission") emissnode.label = "OmniBake" emissnode.location = loc emissnode.location.y = emissnode.location.y + 200 #Get the original mix node that was connected to the output node socket = m_output_node.inputs["Surface"] fromnode = socket.links[0].from_node #Find our created mix node that is paired with it rgbmix = nodes[created_mix_nodes[fromnode.name]] #Plug rgbmix into emission nodetree.links.new(rgbmix.outputs[0], emissnode.inputs[0]) #Plug emission into output nodetree.links.new(emissnode.outputs[0], m_output_node.inputs[0]) #------------Long Name Truncation----------------------- trunc_num = 0 trunc_dict = {} def trunc_if_needed(objectname): global trunc_num global trunc_dict #If we already truncated this, just return that if objectname in trunc_dict: printmsg(f"Object name {objectname} was previously truncated. Returning that.") return trunc_dict[objectname] #If not, let's see if we have to truncate it elif len(objectname) >= 38: printmsg(f"Object name {objectname} is too long and will be truncated") trunc_num += 1 truncdobjectname = objectname[0:34] + "~" + str(trunc_num) trunc_dict[objectname] = truncdobjectname return truncdobjectname #If nothing else, just return the original name else: return objectname def untrunc_if_needed(objectname): global trunc_num global trunc_dict for t in trunc_dict: if trunc_dict[t] == objectname: printmsg(f"Returning untruncated value {t}") return t return objectname def ShowMessageBox(messageitems_list, title, icon = 'INFO'): def draw(self, context): for m in messageitems_list: self.layout.label(text=m) bpy.context.window_manager.popup_menu(draw, title = title, icon = icon) #---------------Bake Progress-------------------------------------------- def write_bake_progress(current_operation, total_operations): progress = int((current_operation / total_operations) * 100) t = Path(tempfile.gettempdir()) t = t / f"OmniBake_Bgbake_{os.getpid()}" with open(str(t), "w") as progfile: progfile.write(str(progress)) #---------------End Bake Progress-------------------------------------------- past_items_dict = {} def spot_new_items(initialise=True, item_type="images"): global past_items_dict if item_type == "images": source = bpy.data.images elif item_type == "objects": source = bpy.data.objects elif item_type == "collections": source = bpy.data.collections #First run if initialise: #Set to empty list for this item type past_items_dict[item_type] = [] for source_item in source: past_items_dict[item_type].append(source_item.name) return True else: #Get the list of items for this item type from the dict past_items_list = past_items_dict[item_type] new_item_list_names = [] for source_item in source: if source_item.name not in past_items_list: new_item_list_names.append(source_item.name) return new_item_list_names #---------------Validation Checks------------------------------------------- def checkMatsValidforPBR(mat): nodes = mat.node_tree.nodes valid = True invalid_node_names = [] for node in nodes: if len(node.outputs) > 0: if node.outputs[0].type == "SHADER" and not (node.bl_idname == "ShaderNodeBsdfPrincipled" or node.bl_idname == "ShaderNodeMixShader" or node.bl_idname == "ShaderNodeEmission"): #But is it actually connected to anything? if len(node.outputs[0].links) >0: invalid_node_names.append(node.name) return invalid_node_names def checkExtraMatsValidforPBR(mat): nodes = mat.node_tree.nodes invalid_node_names = [] supported_node_types = { "ShaderNodeBsdfPrincipled", "ShaderNodeMixShader", "ShaderNodeAddShader", "ShaderNodeEmission", "ShaderNodeBsdfGlossy", "ShaderNodeBsdfGlass", "ShaderNodeBsdfRefraction", "ShaderNodeBsdfDiffuse", "ShaderNodeBsdfAnisotropic", "ShaderNodeBsdfTransparent", } for node in filter(lambda x: bool(len(node.outputs)), nodes): if node.outputs[0].type == "GROUP": ## Support baking for group nodes even if they're in an odd spot continue if node.outputs[0].type == "SHADER" and node.bl_idname not in supported_node_types: #But is it actually connected to anything? if len(node.outputs[0].links) > 0: invalid_node_names.append(node.name) return invalid_node_names def deselect_all_not_mesh(): import bpy for obj in bpy.context.selected_objects: if obj.type != "MESH": obj.select_set(False) #Do we still have an active object? if bpy.context.active_object == None: #Pick arbitary bpy.context.view_layer.objects.active = bpy.context.selected_objects[0] def fix_invalid_material_config(obj): if "OmniBake_Placeholder" in bpy.data.materials: mat = bpy.data.materials["OmniBake_Placeholder"] else: mat = bpy.data.materials.new("OmniBake_Placeholder") bpy.data.materials["OmniBake_Placeholder"].use_nodes = True # Assign it to object if len(obj.material_slots) > 0: #Assign it to every empty slot for slot in obj.material_slots: if slot.material == None: slot.material = mat else: # no slots obj.data.materials.append(mat) #All materials must use nodes for slot in obj.material_slots: mat = slot.material if mat.use_nodes == False: mat.use_nodes = True return True def sacle_image_if_needed(img): printmsg("Scaling images if needed") context = bpy.context width = img.size[0] height = img.size[1] proposed_width = 0 proposed_height = 0 if context.scene.texture_res == "0.5k": proposed_width, proposed_height = 512,512 if context.scene.texture_res == "1k": proposed_width, proposed_height = 1024,1024 if context.scene.texture_res == "2k": proposed_width, proposed_height = 1024*2,1024*2 if context.scene.texture_res == "4k": proposed_width, proposed_height = 1024*4,1024*4 if context.scene.texture_res == "8k": proposed_width, proposed_height = 1024*8,1024*8 if width != proposed_width or height != proposed_height: img.scale(proposed_width, proposed_height) def set_image_internal_col_space(image, thisbake): if thisbake != "diffuse" and thisbake != "emission": image.colorspace_settings.name = "Non-Color" #------------------------Allow Additional Shaders---------------------------- def findProperInput(OName, pnode): for input in pnode.inputs: if OName == "Anisotropy": OName = "Anisotropic" if OName == "Rotation": OName = "Anisotropic Rotation" if OName == "Color": OName = "Base Color" if input.identifier == OName: return input def useAdditionalShaderTypes(nodetree, nodes): count = 0 for node in nodes: if (node.type == "BSDF_GLOSSY" or node.type == "BSDF_GLASS" or node.type == "BSDF_REFRACTION" or node.type == "BSDF_DIFFUSE" or node.type == "BSDF_ANISOTROPIC" or node.type == "BSDF_TRANSPARENT" or node.type == "ADD_SHADER"): if node.type == "ADD_SHADER": pnode = nodes.new("ShaderNodeMixShader") pnode.label = "mixNew" + str(count) else: pnode = nodes.new("ShaderNodeBsdfPrincipled") pnode.label = "BsdfNew" + str(count) pnode.location = node.location pnode.use_custom_color = True pnode.color = (0.3375297784805298, 0.4575316309928894, 0.08615386486053467) for input in node.inputs: if len(input.links) != 0: fromNode = input.links[0].from_node for output in fromNode.outputs: if len(output.links) != 0: for linkOut in output.links: if linkOut.to_node == node: inSocket = findProperInput(input.identifier, pnode) nodetree.links.new(output, inSocket) else: inSocket = findProperInput(input.identifier, pnode) if inSocket.name != "Shader": inSocket.default_value = input.default_value if len(node.outputs[0].links) != 0: for link in node.outputs[0].links: toNode = link.to_node for input in toNode.inputs: if len(input.links) != 0: if input.links[0].from_node == node: nodetree.links.new(pnode.outputs[0], input) if node.type == "BSDF_REFRACTION" or node.type == "BSDF_GLASS": pnode.inputs[15].default_value = 1 if node.type == "BSDF_DIFFUSE": pnode.inputs[5].default_value = 0 if node.type == "BSDF_ANISOTROPIC" or node.type == "BSDF_GLOSSY": pnode.inputs[4].default_value = 1 pnode.inputs[5].default_value = 0 if node.type == "BSDF_TRANSPARENT": pnode.inputs[7].default_value = 0 pnode.inputs[15].default_value = 1 pnode.inputs[14].default_value = 1 pnode.hide = True pnode.select = False nodetree.nodes.remove(node) count += 1
38,975
Python
36.26195
252
0.592636
NVIDIA-Omniverse/blender_omniverse_addons/omni_panel/material_bake/background_bake.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import bpy class bgbake_ops(): bgops_list = [] bgops_list_last = [] bgops_list_finished = [] def remove_dead(): #Remove dead processes from current list for p in bgbake_ops.bgops_list: if p[0].poll() == 0: bgbake_ops.bgops_list_finished.append(p) bgbake_ops.bgops_list.remove(p) return 1 #1 second timer bpy.app.timers.register(remove_dead, persistent=True)
1,305
Python
30.853658
74
0.683525
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. bl_info = { "name": "Omni Scene Optimization Panel", "author": "Nvidia", "description": "", "blender": (3, 4, 0), "version": (2, 0, 0), "location": "View3D > Toolbar > Omniverse", "warning": "", "category": "Omniverse" } from . import (operators, ui) def register(): operators.register() ui.register() def unregister(): operators.unregister() ui.unregister()
1,274
Python
27.333333
74
0.678964
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/operators.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import os import subprocess import time from typing import * from importlib import reload import bpy from bpy.props import (BoolProperty, EnumProperty, FloatProperty, IntProperty, StringProperty) from bpy.types import (Context, Event, Object, Modifier, NodeTree, Scene) from mathutils import Vector from .properties import (OmniSceneOptChopPropertiesMixin, chopProperties) ## ====================================================================== symmetry_axis_items = [ ("X", "X", "X"), ("Y", "Y", "Y"), ("Z", "Z", "Z") ] generate_type_items = [ ("CONVEX_HULL", "Convex Hull", "Convex Hull"), ("BOUNDING_BOX", "Bounding Box", "Bounding Box") ] generate_name = "OmniSceneOptGenerate" ## ====================================================================== def selected_meshes(scene:Scene) -> List[Object]: result = [x for x in scene.collection.all_objects if x.type == "MESH" and x.select_get()] return result def get_plural_count(items) -> (str, int): count = len(items) plural = '' if count == 1 else 's' return plural, count ## ====================================================================== def preserve_selection(func, *args, **kwargs): def wrapper(*args, **kwargs): selection = [x.name for x in bpy.context.selected_objects] active = bpy.context.active_object.name if bpy.context.active_object else None result = func(*args, **kwargs) scene_objects = bpy.context.scene.objects to_select = [ scene_objects[x] for x in selection if x in scene_objects ] if active: active = scene_objects[active] if active in scene_objects else (to_select[-1] if len(to_select) else None) bpy.ops.object.select_all(action="DESELECT") for item in to_select: item.select_set(True) bpy.context.view_layer.objects.active = active return result return wrapper ## ====================================================================== class OmniSceneOptPropertiesMixin: """ Blender Properties that are shared between the in-scene preferences pointer and the various operators. """ verbose: BoolProperty(name="Verbose", description="Print information while running", default=False) selected: BoolProperty(name="Selected", description="Run on Selected Objects (if False, run on whole Scene)", default=False) ## export options export_textures: BoolProperty(name="Export Textures", description="Export textures when doing a background export", default=True) ## these are deliberate copies from ui.OmniYes.Properties validate: BoolProperty(name="Validate Meshes", description="Attempt to remove invalid geometry", default=True) weld: BoolProperty(name="Weld Verts", description="Weld loose vertices", default=False) weld_distance: FloatProperty(name="Weld Distance", description="Distance threshold for welds", default=0.0001, min=0.00001, step=0.00001) unwrap: BoolProperty(name="Unwrap Mesh UVs", description="Use the Smart Unwrap feature to add new UVs", default=False) unwrap_margin: FloatProperty(name="Margin", description="Distance between UV islands", default=0.00, min=0.0, step=0.01) decimate: BoolProperty(name="Decimate", description="Reduce polygon and vertex counts on meshes", default=False) decimate_ratio: IntProperty(name="Ratio", subtype="PERCENTAGE", description="Reduce face count to this percentage of original", default=50, min=10, max=100, step=5) decimate_use_symmetry: BoolProperty(name="Use Symmetry", description="Decimate with Symmetry across an axis", default=False) decimate_symmetry_axis: EnumProperty(name="Symmetry Axis", description="Axis for symmetry", items=symmetry_axis_items, default="X") decimate_min_face_count: IntProperty(name="Minimum Face Count", description="Do not decimate objects with less faces", default=500, min=100, step=10) decimate_remove_shape_keys: BoolProperty(name="Remove Shape Keys", description="Remove shape keys to allow meshes with shapes to be decimated", default=False) chop: BoolProperty(name="Chop Meshes", description="Physically divide meshes based on size and point count", default=False) generate: BoolProperty(name="Generate", description="Generate convex hulls or bounding boxes", default=False) merge: BoolProperty(name="Merge Selected", description="On Export, merge selected meshes into a single object", default=False) ## ====================================================================== class OmniSceneOptGeneratePropertiesMixin: generate_duplicate: BoolProperty(name="Create Duplicate", description="Generate a new object instead of replacing the original", default=True) generate_type: EnumProperty(name="Generate Type", description="Type of geometry to generate", items=generate_type_items, default="CONVEX_HULL") ## ====================================================================== """ This is a weird one. The decimate modifier was failing on multiple objects in order, but wrapping it in an Operator seems to fix the issues with making sure the correct things are selected in the Context. """ class OBJECT_OT_omni_sceneopt_decimate(bpy.types.Operator, OmniSceneOptPropertiesMixin): """Decimates the selected object using the Decimation modifier.""" bl_idname = "omni_sceneopt.decimate" bl_label = "Omni Scene Optimization: Decimate" bl_options = {"REGISTER", "UNDO"} ratio: IntProperty(name="Ratio", subtype="PERCENTAGE", description="Reduce face count to this percentage of original", default=50, min=10, max=100, step=5) use_symmetry: BoolProperty(name="Use Symmetry", description="Decimate with Symmetry across an axis", default=True) symmetry_axis: EnumProperty(name="Symmetry Axis", description="Axis for symmetry", items=symmetry_axis_items, default="X") min_face_count: IntProperty(name="Minimum Face Count", description="Do not decimate objects with less faces", default=500, min=100, step=10) @classmethod def poll(cls, context:Context) -> bool: return bool(context.active_object) def execute(self, context:Context) -> Set[str]: from .batch import lod result = lod.decimate_object(context.active_object, ratio=self.ratio / 100.0, use_symmetry=self.use_symmetry, symmetry_axis=self.symmetry_axis, min_face_count=self.min_face_count, create_duplicate=False) return {"FINISHED"} ## ====================================================================== class OmniOverrideMixin: def set_active(self, ob:Object): try: bpy.context.view_layer.objects.active = ob except RuntimeError as e: print(f"-- unable to set active: {ob.name} ({e}") def override(self, objects:List[Object], single=False): assert isinstance(objects, (list, tuple)), "'objects' is expected to be a list or tuple" assert len(objects), "'objects' cannot be empty" ## filter out objects not in current view layer objects = list(filter(lambda x: x.name in bpy.context.view_layer.objects, objects)) if single: objects = objects[0:1] override = { 'active_object': objects[0], 'edit_object': None, 'editable_objects': objects, 'object': objects[0], 'objects_in_mode': [], 'objects_in_mode_unique_data': [], 'selectable_objects': objects, 'selected_editable_objects': objects, 'selected_objects': objects, 'visible_objects': objects, } self.set_active(objects[0]) return bpy.context.temp_override(**override) def edit_override(self, objects:List[Object], single=False): assert isinstance(objects, (list, tuple)), "'objects' is expected to be a list or tuple" assert len(objects), "'objects' cannot be empty" if single: objects = objects[0:1] override = { 'active_object': objects[0], 'edit_object': objects[0], 'editable_objects': objects, 'object': objects[0], 'objects_in_mode': objects, 'objects_in_mode_unique_data': objects, 'selectable_objects': objects, 'selected_editable_objects': objects, 'selected_objects': objects, 'visible_objects': objects, } self.set_active(objects[0]) return bpy.context.temp_override(**override) ## ====================================================================== class OBJECT_OT_omni_sceneopt_optimize(bpy.types.Operator, OmniSceneOptPropertiesMixin, OmniSceneOptChopPropertiesMixin, OmniSceneOptGeneratePropertiesMixin, OmniOverrideMixin): """Run specified optimizations on the scene or on selected objects.""" bl_idname = "omni_sceneopt.optimize" bl_label = "Omni Scene Optimization: Optimize Scene" bl_options = {"REGISTER", "UNDO"} # def draw(self, context:Context): # """Empty draw to disable the Operator Props Panel.""" # pass def _object_mode(self): if not bpy.context.mode == "OBJECT": bpy.ops.object.mode_set(mode="OBJECT") def _edit_mode(self): if not bpy.context.mode == "EDIT_MESH": bpy.ops.object.mode_set(mode="EDIT") @staticmethod def _remove_shape_keys(ob:Object): assert ob.type == "MESH", "Cannot be run on non-Mesh Objects." ## Reversed because we want to remove Basis last, or we will end up ## with garbage baked in. for key in reversed(ob.data.shape_keys.key_blocks): ob.shape_key_remove(key) @staticmethod def _select_one(ob:Object): bpy.ops.object.select_all(action="DESELECT") ob.select_set(True) bpy.context.view_layer.objects.active = ob @staticmethod def _select_objects(objects:List[Object]): bpy.ops.object.select_all(action="DESELECT") for item in objects: item.select_set(True) bpy.context.view_layer.objects.active = objects[-1] @staticmethod def _get_evaluated(objects:List[Object]) -> List[Object]: deps = bpy.context.evaluated_depsgraph_get() return [x.evaluated_get(deps).original for x in objects] @staticmethod def _total_vertex_count(target_objects:List[Object]): deps = bpy.context.evaluated_depsgraph_get() eval_objs = [x.evaluated_get(deps) for x in target_objects] return sum([len(x.data.vertices) for x in eval_objs]) def do_validate(self, target_objects:List[Object]) -> List[Object]: """Expects to be run in Edit Mode with all meshes selected""" total_orig = self._total_vertex_count(target_objects) bpy.ops.mesh.select_all(action="SELECT") bpy.ops.mesh.dissolve_degenerate() total_result = self._total_vertex_count(target_objects) if self.verbose: plural, obj_count = get_plural_count(target_objects) message = f"Validated {obj_count} object{plural}." self.report({"INFO"}, message) return target_objects def do_weld(self, target_objects:List[Object]) -> List[Object]: """Expects to be run in Edit Mode with all meshes selected""" bpy.ops.mesh.remove_doubles(threshold=self.weld_distance, use_unselected=True) bpy.ops.mesh.normals_make_consistent(inside=False) return target_objects def do_unwrap(self, target_objects:List[Object]) -> List[Object]: bpy.ops.object.select_all(action="DESELECT") start = time.time() for item in target_objects: with self.edit_override([item]): bpy.ops.object.mode_set(mode="EDIT") bpy.ops.mesh.select_all(action="SELECT") bpy.ops.uv.smart_project(island_margin=0.0) bpy.ops.uv.select_all(action="SELECT") # bpy.ops.uv.average_islands_scale() # bpy.ops.uv.pack_islands(margin=self.unwrap_margin) bpy.ops.object.mode_set(mode="OBJECT") end = time.time() if self.verbose: plural, obj_count = get_plural_count(target_objects) message = f"Unwrapped {obj_count} object{plural} ({end-start:.02f} seconds)." self.report({"INFO"}, message) return target_objects def do_decimate(self, target_objects:List[Object]) -> List[Object]: assert bpy.context.mode == "OBJECT", "Decimate must be run in object mode." total_orig = self._total_vertex_count(target_objects) total_result = 0 start = time.time() for item in target_objects: if item.data.shape_keys and len(item.data.shape_keys.key_blocks): if not self.decimate_remove_shape_keys: self.report({"WARNING"}, f"[ Decimate ] Skipping {item.name} because it has shape keys.") continue else: self._remove_shape_keys(item) if len(item.data.polygons) < self.decimate_min_face_count: self.report({"INFO"}, f"{item.name} is under face count-- not decimating.") continue ## We're going to use the decimate modifier mod = item.modifiers.new("OmniLOD", type="DECIMATE") mod.decimate_type = "COLLAPSE" mod.ratio = self.decimate_ratio / 100.0 mod.use_collapse_triangulate = True mod.use_symmetry = self.decimate_use_symmetry mod.symmetry_axis = self.decimate_symmetry_axis ## we don't need a full context override here self.set_active(item) bpy.ops.object.modifier_apply(modifier=mod.name) total_result += len(item.data.vertices) end = time.time() if self.verbose: plural, obj_count = get_plural_count(target_objects) message = f"Decimated {obj_count} object{plural}. Vertex count original {total_orig} to {total_result} ({end-start:.02f} seconds)." self.report({"INFO"}, message) return target_objects def do_chop(self, target_objects:List[Object]): """ Assumes all objects are selected and that we are in Object mode """ assert bpy.context.mode == "OBJECT", "Chop must be run in object mode." scene = bpy.context.scene attributes = scene.omni_sceneopt_chop.attributes() attributes["selected_only"] = self.selected bpy.ops.omni_sceneopt.chop(**attributes) return target_objects def do_generate(self, target_objects:List[Object]): with self.override(target_objects): bpy.ops.omni_sceneopt.generate(generate_type=self.generate_type, generate_duplicate=self.generate_duplicate) return target_objects def execute(self, context:Context) -> Set[str]: start = time.time() active = context.active_object if self.selected: targets = selected_meshes(context.scene) else: targets = [x for x in context.scene.collection.all_objects if x.type == "MESH"] bpy.ops.object.select_all(action="DESELECT") [ x.select_set(True) for x in targets ] if active: self.set_active(active) if not len(targets): self.info({"ERROR"}, "No targets specified.") return {"CANCELLED"} self._object_mode() ## Have to do vertex counts outside edit mode! total_orig = self._total_vertex_count(targets) if self.validate or self.weld: with self.edit_override(targets): bpy.ops.object.mode_set(mode="EDIT") ## We can run these two operations together because they don't collide ## or cause issues between each other. if self.validate: self.do_validate(targets) if self.weld: self.do_weld(targets) ## Unfortunately, the rest are object-by-object operations self._object_mode() total_result = self._total_vertex_count(targets) if self.verbose and self.weld: plural, obj_count = get_plural_count(targets) message = f"Welded {obj_count} object{plural}. Vertex count original {total_orig} to {total_result}." self.report({"INFO"}, message) if self.unwrap: self.do_unwrap(targets) if self.decimate: self.do_decimate(targets) if self.chop: self.do_chop(targets) if self.generate: self.do_generate(targets) end = time.time() if self.verbose: self.report({"INFO"}, f"Optimization complete-- process took {end-start:.02f} seconds") return {"FINISHED"} ## ====================================================================== class OBJECT_OT_omni_sceneopt_chop(bpy.types.Operator, OmniSceneOptChopPropertiesMixin): """Chop the specified object into a grid of smaller ones""" bl_idname = "omni_sceneopt.chop" bl_label = "Omni Scene Optimizer: Chop" bl_options = {"REGISTER", "UNDO"} # def draw(self, context:Context): # """Empty draw to disable the Operator Props Panel.""" # pass def execute(self, context:Context) -> Set[str]: attributes = dict( merge=self.merge, cut_meshes=self.cut_meshes, max_vertices=self.max_vertices, min_box_size=self.min_box_size, max_depth=self.max_depth, print_updated_results=self.print_updated_results, create_bounds=self.create_bounds, selected_only=self.selected_only ) from .scripts.chop import Chop chopper = Chop() chopper.execute(self.attributes()) return {"FINISHED"} ## ====================================================================== class OBJECT_OT_omni_sceneopt_generate(bpy.types.Operator, OmniSceneOptGeneratePropertiesMixin, OmniOverrideMixin): """Generate geometry based on selected objects. Currently supported: Bounding Box, Convex Hull""" bl_idname = "omni_sceneopt.generate" bl_label = "Omni Scene Optimizer: Generate" bl_options = {"REGISTER", "UNDO"} # def draw(self, context:Context): # """Empty draw to disable the Operator Props Panel.""" # pass def create_geometry_nodes_group(self, group:NodeTree): """Create or return the shared Generate node group.""" node_type = { "CONVEX_HULL": "GeometryNodeConvexHull", "BOUNDING_BOX": "GeometryNodeBoundBox", }[self.generate_type] geometry_input = group.nodes["Group Input"] geometry_input.location = Vector((-1.5 * geometry_input.width, 0)) group_output = group.nodes["Group Output"] group_output.location = Vector((1.5 * group_output.width, 0)) node = group.nodes.new(node_type) node.name = "Processor" group.links.new(geometry_input.outputs['Geometry'], node.inputs['Geometry']) group.links.new(node.outputs[0], group_output.inputs['Geometry']) return bpy.data.node_groups[generate_name] def create_geometry_nodes_modifier(self, ob:Object) -> Modifier: if generate_name in ob.modifiers: ob.modifiers.remove(ob.modifiers[generate_name]) if generate_name in bpy.data.node_groups: bpy.data.node_groups.remove(bpy.data.node_groups[generate_name]) mod = ob.modifiers.new(name=generate_name, type="NODES") bpy.ops.node.new_geometry_node_group_assign() mod.node_group.name = generate_name self.create_geometry_nodes_group(mod.node_group) return mod def create_duplicate(self, ob:Object, token:str) -> Object: from .batch import lod duplicate = lod.duplicate_object(ob, token, weld=False) return duplicate @preserve_selection def apply_modifiers(self, target_objects:List[Object]): count = 0 for item in target_objects: if self.generate_duplicate: token = self.generate_type.rpartition("_")[-1] duplicate = self.create_duplicate(item, token=token) duplicate.parent = item.parent duplicate.matrix_world = item.matrix_world.copy() bpy.context.scene.collection.objects.unlink(duplicate) for collection in item.users_collection: collection.objects.link(duplicate) item = duplicate with self.override([item]): mod = self.create_geometry_nodes_modifier(item) bpy.context.view_layer.objects.active = item item.select_set(True) bpy.ops.object.modifier_apply(modifier=mod.name) count += 1 def execute(self, context:Context) -> Set[str]: changed = self.apply_modifiers(context.selected_objects) if changed: group = bpy.data.node_groups["OMNI_SCENEOPT_GENERATE"] bpy.data.node_groups.remove(group) return {"FINISHED"} ## ====================================================================== class OBJECT_OT_omni_progress(bpy.types.Operator): bl_idname = "omni.progress" bl_label = "Export Optimized USD" bl_options = {"REGISTER", "UNDO"} message: StringProperty(name="message", description="Message to print upon completion.", default="") _timer = None def modal(self, context:Context, event:Event) -> Set[str]: if context.scene.omni_progress_active is False: message = self.message.strip() if len(message): self.report({"INFO"}, message) return {"FINISHED"} context.area.tag_redraw() context.window.cursor_set("WAIT") return {"RUNNING_MODAL"} def invoke(self, context:Context, event:Event) -> Set[str]: context.scene.omni_progress_active = True self._timer = context.window_manager.event_timer_add(0.1, window=context.window) context.window_manager.modal_handler_add(self) context.window.cursor_set("WAIT") return {"RUNNING_MODAL"} ## ====================================================================== class OBJECT_OT_omni_sceneopt_export(bpy.types.Operator, OmniSceneOptPropertiesMixin, OmniSceneOptChopPropertiesMixin, OmniSceneOptGeneratePropertiesMixin): """Runs specified optimizations on the scene before running a USD Export""" bl_idname = "omni_sceneopt.export" bl_label = "Export USD" bl_options = {"REGISTER", "UNDO"} filepath: StringProperty(subtype="FILE_PATH") filter_glob: StringProperty(default="*.usd;*.usda;*.usdc", options={"HIDDEN"}) check_existing: BoolProperty(default=True, options={"HIDDEN"}) def draw(self, context:Context): """Empty draw to disable the Operator Props Panel.""" pass def invoke(self, context:Context, event:Event) -> Set[str]: if len(self.filepath.strip()) == 0: self.filepath = "untitled.usdc" context.window_manager.fileselect_add(self) return {"RUNNING_MODAL"} def execute(self, context:Context) -> Set[str]: output_path = bpy.path.abspath(self.filepath) script_path = os.sep.join((os.path.dirname(os.path.abspath(__file__)), "batch", "optimize_export.py")) bpy.ops.omni.progress(message=f"Finished background write to {output_path}") bpy.ops.wm.save_mainfile() command = " ".join([ '"{}"'.format(bpy.app.binary_path), "--background", '"{}"'.format(bpy.data.filepath), "--python", '"{}"'.format(script_path), "--", '"{}"'.format(output_path) ]) print(command) subprocess.check_output(command, shell=True) context.scene.omni_progress_active = False if self.verbose: self.report({"INFO"}, f"Exported optimized scene to: {output_path}") return {"FINISHED"} ## ====================================================================== classes = [ OBJECT_OT_omni_sceneopt_decimate, OBJECT_OT_omni_sceneopt_chop, OBJECT_OT_omni_sceneopt_generate, OBJECT_OT_omni_sceneopt_optimize, OBJECT_OT_omni_progress, OBJECT_OT_omni_sceneopt_export, chopProperties ] def unregister(): try: del bpy.types.Scene.omni_sceneopt_chop except AttributeError: pass try: del bpy.types.Scene.omni_progress_active except AttributeError: pass for cls in reversed(classes): try: bpy.utils.unregister_class(cls) except (ValueError, AttributeError, RuntimeError): continue def register(): for cls in classes: bpy.utils.register_class(cls) bpy.types.Scene.omni_sceneopt_chop = bpy.props.PointerProperty(type=chopProperties) bpy.types.Scene.omni_progress_active = bpy.props.BoolProperty(default=False)
23,131
Python
30.687671
134
0.67001
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/panel.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. from bpy.types import Panel from os.path import join, dirname import bpy.utils.previews #---------------Custom ICONs---------------------- def get_icons_directory(): icons_directory = join(dirname(__file__), "icons") return icons_directory class OPTIMIZE_PT_Panel(Panel): bl_space_type = "VIEW_3D" bl_region_type = "UI" bl_label = "OPTIMIZE SCENE" bl_category = "Omniverse" #retrieve icons icons = bpy.utils.previews.new() icons_directory = get_icons_directory() icons.load("OMNI", join(icons_directory, "ICON.png"), 'IMAGE') icons.load("GEAR", join(icons_directory, "gear.png"), 'IMAGE') def draw(self, context): layout = self.layout layout.label(text="Omniverse", icon_value=self.icons["OMNI"].icon_id) optimizeOptions = context.scene.optimize_options modifyOptions = context.scene.modify_options uvOptions = context.scene.uv_options chopOptions = context.scene.chop_options # OPERATOR SETTINGS box = layout.box() col = box.column(align= True) row = col.row(align=True) row.scale_y = 1.5 row.operator("optimize.scene", text = "Optimize Scene", icon_value=self.icons["GEAR"].icon_id) col.separator() row2 = col.row(align=True) row2.scale_y = 1.3 row2.prop(optimizeOptions, "operation", text="Operation") col.separator() col.prop(optimizeOptions, "print_attributes", expand= True) box2 = layout.box() box2.label(text= "OPERATION PROPERTIES:") col2 = box2.column(align= True) # MODIFY SETTINGS if optimizeOptions.operation == 'modify': row = col2.row(align= True) row.prop(modifyOptions, "modifier", text="Modifier") row2 = col2.row(align= True) row3 = col2.row(align= True) #DECIMATE if modifyOptions.modifier == 'DECIMATE': row2.prop(modifyOptions, "decimate_type", expand= True) if modifyOptions.decimate_type == 'COLLAPSE': row3.prop(modifyOptions, "ratio", expand= True) elif modifyOptions.decimate_type == 'UNSUBDIV': row3.prop(modifyOptions, "iterations", expand= True) elif modifyOptions.decimate_type == 'DISSOLVE': row3.prop(modifyOptions, "angle", expand= True) #REMESH elif modifyOptions.modifier == 'REMESH': row2.prop(modifyOptions, "remesh_type", expand= True) if modifyOptions.remesh_type == 'BLOCKS': row3.prop(modifyOptions, "oDepth", expand= True) if modifyOptions.remesh_type == 'SMOOTH': row3.prop(modifyOptions, "oDepth", expand= True) if modifyOptions.remesh_type == 'SHARP': row3.prop(modifyOptions, "oDepth", expand= True) if modifyOptions.remesh_type == 'VOXEL': row3.prop(modifyOptions, "voxel_size", expand= True) #NODES elif modifyOptions.modifier == 'NODES': row2.prop(modifyOptions, "geo_type") if modifyOptions.geo_type == "GeometryNodeSubdivisionSurface": row2.prop(modifyOptions, "geo_attribute", expand= True) col2.prop(modifyOptions, "selected_only", expand= True) col2.prop(modifyOptions, "apply_mod", expand= True) box3 = col2.box() col3 = box3.column(align=True) col3.label(text="FIX MESH BEFORE MODIFY") col3.prop(modifyOptions, "fix_bad_mesh", expand= True) if modifyOptions.fix_bad_mesh: col3.prop(modifyOptions, "dissolve_threshold", expand= True) col3.prop(modifyOptions, "merge_vertex", expand= True) if modifyOptions.merge_vertex: col3.prop(modifyOptions, "merge_threshold", expand= True) if modifyOptions.fix_bad_mesh or modifyOptions.merge_vertex: col3.prop(modifyOptions, "remove_existing_sharp", expand= True) col3.prop(modifyOptions, "fix_normals", expand= True) if modifyOptions.fix_normals: col3.prop(modifyOptions, "create_new_custom_normals", expand= True) # use_modifier_stack= modifyOptions.use_modifier_stack, # modifier_stack=[["DECIMATE", "COLLAPSE", 0.5]], # FIX MESH SETTINGS elif optimizeOptions.operation == 'fixMesh': col2.prop(modifyOptions, "selected_only", expand= True) col3 = col2.column(align=True) col3.prop(modifyOptions, "fix_bad_mesh", expand= True) if modifyOptions.fix_bad_mesh: col3.prop(modifyOptions, "dissolve_threshold", expand= True) col3.prop(modifyOptions, "merge_vertex", expand= True) if modifyOptions.merge_vertex: col3.prop(modifyOptions, "merge_threshold", expand= True) if modifyOptions.fix_bad_mesh or modifyOptions.merge_vertex: col3.prop(modifyOptions, "remove_existing_sharp", expand= True) col3.prop(modifyOptions, "fix_normals", expand= True) if modifyOptions.fix_normals: col3.prop(modifyOptions, "create_new_custom_normals", expand= True) # UV SETTINGS elif optimizeOptions.operation == 'uv': if uvOptions.unwrap_type == 'Smart': col2.label(text= "SMART UV CAN BE SLOW", icon='ERROR') else: col2.label(text= "Unwrap Type") col2.prop(uvOptions, "unwrap_type", expand= True) col2.prop(uvOptions, "selected_only", expand= True) col2.prop(uvOptions, "scale_to_bounds", expand= True) col2.prop(uvOptions, "clip_to_bounds", expand= True) col2.prop(uvOptions, "use_set_size", expand= True) if uvOptions.use_set_size: col2.prop(uvOptions, "set_size", expand= True) col2.prop(uvOptions, "print_updated_results", expand= True) # CHOP SETTINGS elif optimizeOptions.operation == 'chop': col2.prop(chopOptions, "selected_only", expand= True) col2.prop(chopOptions, "cut_meshes", expand= True) col2.prop(chopOptions, "max_vertices", expand= True) col2.prop(chopOptions, "min_box_size", expand= True) col2.prop(chopOptions, "max_depth", expand= True) col2.prop(chopOptions, "merge", expand= True) col2.prop(chopOptions, "create_bounds", expand= True) col2.prop(chopOptions, "print_updated_results", expand= True)
7,603
Python
44.532934
102
0.605682
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/properties.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. from typing import * from bpy.props import * import bpy class optimizeProperties(bpy.types.PropertyGroup): # PROPERTIES operation: EnumProperty( name="Operation", items= [ ('modify', 'MODIFY', 'run modify'), ('fixMesh', 'FIX MESH', 'run fix Mesh'), ('uv', 'UV UNWRAP', "run uv"), ('chop', 'CHOP', 'run chop')], description= "Choose the operation to run on the scene", default = 'modify' ) print_attributes: BoolProperty( name ="Print Attributes", description = "Print attributes used at the begging of operation", default = False ) class modProperties(bpy.types.PropertyGroup): # PROPERTIES selected_only: BoolProperty( name ="Use Selected Only", description = "Operate on selected objects only", default = False ) apply_mod: BoolProperty( name ="Apply Modifier", description = "Apply modifier after adding", default = True ) fix_bad_mesh: BoolProperty( name ="Fix Bad Mesh", description = "Remove zero area faces and zero length edges", default = False ) dissolve_threshold: FloatProperty( name="Dissolve Threshold", description = "Threshold value used with Fix Bad Mesh", default=0.08, min=0, max=50 ) merge_vertex: BoolProperty( name ="Merge Vertex", description = "Merge vertices by distance", default = False ) merge_threshold: FloatProperty( name="Merge Threshold", description = "Distance value used with merge vertex", default=0.01, min=0, max=50 ) remove_existing_sharp: BoolProperty( name ="Remove Existing Sharp", description = "Remove existing sharp edges from meshes. This helps sometimes after fixing bad meshes", default = True ) fix_normals: BoolProperty( name ="Fix Normals", description = "Remove existing custom split normals", default = False ) create_new_custom_normals: BoolProperty( name ="Create New Custom Normals", description = "Create new custom split normals", default = False ) # Some common modifier names for reference:'DECIMATE''REMESH''NODES''SUBSURF''SOLIDIFY''ARRAY''BEVEL' modifier: EnumProperty( name="Modifier", items= [ ('DECIMATE', 'Decimate', 'decimate geometry'), ('REMESH', 'Remesh', 'remesh geometry'), ('NODES', 'Nodes', 'add geometry node mod'), ('FIX', 'Fix Mesh', "fix mesh")], description= "Choose the modifier to apply to geometry", default = 'DECIMATE' ) # TODO: Implement this modifier stack properly. would allow for multiple modifiers to be queued and run at once # use_modifier_stack: BoolProperty( # name ="Use Modifier Stack", # description = "use stack of modifiers instead of a single modifier", # default = False # ) # modifier_stack: CollectionProperty( # type= optimizeProperties, # name="Modifiers", # description= "list of modifiers to be used", # default = [["DECIMATE", "COLLAPSE", 0.5]] # ) decimate_type: EnumProperty( items= [ ('COLLAPSE','collapse',"collapse geometry"), ('UNSUBDIV','unSubdivide',"un subdivide geometry"), ('DISSOLVE','planar',"dissolve geometry")], description = "Choose which type of decimation to perform.", default = "COLLAPSE" ) ratio: FloatProperty( name="Ratio", default=0.5, min=0.0, max=1.0 ) iterations: IntProperty( name="Iterations", default=2, min=0, max=50 ) angle: FloatProperty( name="Angle", default=15.0, min=0.0, max=180.0 ) remesh_type: EnumProperty( items= [ ('BLOCKS','blocks',"collapse geometry"), ('SMOOTH','smooth',"un subdivide geometry"), ('SHARP','sharp',"un subdivide geometry"), ('VOXEL','voxel',"dissolve geometry")], description = "Choose which type of remesh to perform.", default = "VOXEL" ) oDepth: IntProperty( name="Octree Depth", default=4, min=1, max=8 ) voxel_size: FloatProperty( name="Voxel Size", default=0.1, min=0.01, max=2.0 ) geo_type: EnumProperty( items= [ ('GeometryNodeConvexHull','convex hull',"basic convex hull"), ('GeometryNodeBoundBox','bounding box',"basic bounding box"), ('GeometryNodeSubdivisionSurface','subdiv',"subdivide geometry")], description = "Choose which type of geo node tree to add", default = "GeometryNodeBoundBox" ) geo_attribute: IntProperty( name="Attribute", description = "Additional attribute used for certain geo nodes", default=2, min=0, max=8 ) class uvProperties(bpy.types.PropertyGroup): # PROPERTIES selected_only: BoolProperty( name ="Use Selected Only", description = "Operate on selected objects only", default = False ) unwrap_type: EnumProperty( items= [ ('Cube','cube project',"basic convex hull"), ('Sphere','sphere project',"subdivide geometry"), ('Cylinder','cylinder project',"dissolve geometry"), ('Smart','smart project',"basic bounding box")], description = "Choose which type of unwrap process to use.", default = "Cube" ) scale_to_bounds: BoolProperty( name ="Scale To Bounds", description = "Scale UVs to 2D bounds", default = False ) clip_to_bounds: BoolProperty( name ="Clip To Bounds", description = "Clip UVs to 2D bounds", default = False ) use_set_size: BoolProperty( name ="Use Set Size", description = "Use a defined UV size for all objects", default = False ) set_size : FloatProperty( name="Set Size", default=2.0, min=0.01, max=100.0 ) print_updated_results: BoolProperty( name ="Print Updated Results", description = "Print updated results to console", default = True ) class OmniSceneOptChopPropertiesMixin: selected_only: BoolProperty( name="Split Selected Only", description="Operate on selected objects only", default=False ) print_updated_results: BoolProperty( name="Print Updated Results", description="Print updated results to console", default=True ) cut_meshes: BoolProperty( name="Cut Meshes", description="Cut meshes", default=True ) merge: BoolProperty( name="Merge", description="Merge split chunks after splitting is complete", default=False ) create_bounds: BoolProperty( name="Create Boundary Objects", description="Add generated boundary objects to scene", default=False ) max_depth: IntProperty( name="Max Depth", description="Maximum recursion depth", default=8, min=0, max=32 ) max_vertices: IntProperty( name="Max Vertices", description="Maximum vertices allowed per block", default=10000, min=0, max=1000000 ) min_box_size: FloatProperty( name="Min Box Size", description="Minimum dimension for a chunk to be created", default=1, min=0, max=10000 ) def attributes(self) -> Dict: return dict( merge=self.merge, cut_meshes=self.cut_meshes, max_vertices=self.max_vertices, min_box_size=self.min_box_size, max_depth=self.max_depth, print_updated_results=self.print_updated_results, create_bounds=self.create_bounds, selected_only=self.selected_only ) def set_attributes(self, attributes:Dict): for attr, value in attributes.items(): if hasattr(self, attr): setattr(self, attr, value) else: raise ValueError(f"OmniSceneOptChopPropertiesMixin: invalid attribute for set {attr}") class chopProperties(bpy.types.PropertyGroup, OmniSceneOptChopPropertiesMixin): pass
9,344
Python
27.842593
115
0.601241
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/ui.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import os from typing import * import bpy from bpy.utils import previews from bpy.props import (BoolProperty, EnumProperty, FloatProperty, IntProperty, StringProperty) from bpy.types import (Context, Object, Operator, Scene) from .operators import ( OBJECT_OT_omni_sceneopt_optimize, OBJECT_OT_omni_sceneopt_export, OmniSceneOptPropertiesMixin, OmniSceneOptGeneratePropertiesMixin, selected_meshes, symmetry_axis_items ) ## ====================================================================== def preload_icons() -> previews.ImagePreviewCollection: """Preload icons used by the interface.""" icons_directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons") all_icons = { "GEAR": "gear.png", "ICON": "ICON.png", } preview = previews.new() for name, filepath in all_icons.items(): preview.load(name, os.path.join(icons_directory, filepath), "IMAGE") return preview ## ====================================================================== class OmniSceneOptProperties(bpy.types.PropertyGroup, OmniSceneOptPropertiesMixin, OmniSceneOptGeneratePropertiesMixin): """We're only here to register the mixins through the PropertyGroup""" pass ## ====================================================================== def can_run_optimization(scene:Scene) -> bool: if scene.omni_sceneopt.selected and not len(selected_meshes(scene)): return False has_operations = any(( scene.omni_sceneopt.validate, scene.omni_sceneopt.weld, scene.omni_sceneopt.decimate, scene.omni_sceneopt.unwrap, scene.omni_sceneopt.chop, scene.omni_sceneopt.generate, )) if not has_operations: return False return True ## ====================================================================== class OBJECT_PT_OmniOptimizationPanel(bpy.types.Panel): bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category = "Omniverse" bl_label = "Scene Optimizer" bl_options = {"DEFAULT_CLOSED"} icons = preload_icons() @staticmethod def _apply_parameters(settings, op:Operator): """Copy parameters from the scene-level settings blob to an operator""" invalid = {"bl_rna", "name", "rna_type"} for property_name in filter(lambda x: not x[0] == '_' and not x in invalid, dir(settings)): if hasattr(op, property_name): value = getattr(settings, property_name) setattr(op, property_name, value) op.verbose = True def draw_validate(self, layout, scene: Scene): box = layout.box() box.prop(scene.omni_sceneopt, "validate") def draw_weld(self, layout, scene: Scene): box = layout.box() box.prop(scene.omni_sceneopt, "weld") if not scene.omni_sceneopt.weld: return box.prop(scene.omni_sceneopt, "weld_distance") def draw_decimate(self, layout, scene: Scene): box = layout.box() box.prop(scene.omni_sceneopt, "decimate") if not scene.omni_sceneopt.decimate: return box.prop(scene.omni_sceneopt, "decimate_ratio") box.prop(scene.omni_sceneopt, "decimate_min_face_count") row = box.row() row.prop(scene.omni_sceneopt, "decimate_use_symmetry") row = row.row() row.prop(scene.omni_sceneopt, "decimate_symmetry_axis", text="") row.enabled = scene.omni_sceneopt.decimate_use_symmetry box.prop(scene.omni_sceneopt, "decimate_remove_shape_keys") def draw_unwrap(self, layout, scene: Scene): box = layout.box() box.prop(scene.omni_sceneopt, "unwrap") if not scene.omni_sceneopt.unwrap: return box.prop(scene.omni_sceneopt, "unwrap_margin") def draw_chop(self, layout, scene: Scene): box = layout.box() box.prop(scene.omni_sceneopt, "chop") if not scene.omni_sceneopt.chop: return col = box.column(align=True) col.prop(scene.omni_sceneopt_chop, "max_vertices") col.prop(scene.omni_sceneopt_chop, "min_box_size") col.prop(scene.omni_sceneopt_chop, "max_depth") box.prop(scene.omni_sceneopt_chop, "create_bounds") def draw_generate(self, layout, scene: Scene): box = layout.box() box.prop(scene.omni_sceneopt, "generate", text="Generate Bounding Mesh") if not scene.omni_sceneopt.generate: return col = box.column(align=True) col.prop(scene.omni_sceneopt, "generate_type") col.prop(scene.omni_sceneopt, "generate_duplicate") def draw_operators(self, layout, context:Context, scene:Scene): layout.label(text="") row = layout.row(align=True) row.label(text="Run Operations", icon="PLAY") row.prop(scene.omni_sceneopt, "selected", text="Selected Meshes Only") run_text = f"{'Selected' if scene.omni_sceneopt.selected else 'Scene'}" col = layout.column(align=True) op = col.operator(OBJECT_OT_omni_sceneopt_optimize.bl_idname, text=f"Optimize {run_text}", icon_value=self.icons["GEAR"].icon_id) self._apply_parameters(scene.omni_sceneopt, op) col.enabled = can_run_optimization(scene) col = layout.column(align=True) op = col.operator(OBJECT_OT_omni_sceneopt_export.bl_idname, text=f"Export Optimized Scene to USD", icon='EXPORT') self._apply_parameters(scene.omni_sceneopt, op) col.label(text="Export Options") row = col.row(align=True) row.prop(scene.omni_sceneopt, "merge") row.prop(scene.omni_sceneopt, "export_textures") def draw(self, context:Context): scene = context.scene layout = self.layout self.draw_validate(layout, scene=scene) self.draw_weld(layout, scene=scene) self.draw_unwrap(layout, scene=scene) self.draw_decimate(layout, scene=scene) self.draw_chop(layout, scene=scene) self.draw_generate(layout, scene=scene) self.draw_operators(layout, context, scene=scene) ## ====================================================================== classes = [ OBJECT_PT_OmniOptimizationPanel, OmniSceneOptProperties, ] def unregister(): try: del bpy.types.Scene.omni_sceneopt except (ValueError, AttributeError, RuntimeError): pass for cls in reversed(classes): try: bpy.utils.unregister_class(cls) except (ValueError, AttributeError, RuntimeError): continue def register(): for cls in classes: bpy.utils.register_class(cls) bpy.types.Scene.omni_sceneopt = bpy.props.PointerProperty(type=OmniSceneOptProperties)
6,169
Python
27.302752
94
0.677906
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/batch/lod.py
import argparse import os import sys from typing import * import bpy from bpy.types import (Collection, Context, Image, Object, Material, Mesh, Node, NodeSocket, NodeTree, Scene) from bpy.props import * from mathutils import * ## ====================================================================== def select_only(ob:Object): """ Ensure that only the specified object is selected. :param ob: Object to select """ bpy.ops.object.select_all(action="DESELECT") ob.select_set(state=True) bpy.context.view_layer.objects.active = ob ## -------------------------------------------------------------------------------- def _selected_meshes(context:Context, use_instancing=True) -> List[Mesh]: """ :return: List[Mesh] of all selected mesh objects in active Blender Scene. """ ## instances support meshes = [x for x in context.selected_objects if x.type == "MESH"] instances = [x for x in context.selected_objects if x.type == "EMPTY" and x.instance_collection] if use_instancing: for inst in instances: instance_meshes = [x for x in inst.instance_collection.all_objects if x.type == "MESH"] meshes += instance_meshes meshes = list(set(meshes)) return meshes ## -------------------------------------------------------------------------------- def copy_object_parenting(source_ob:Object, target_ob:Object): """ Copy parenting and Collection membership from a source object. """ target_collections = list(target_ob.users_collection) for collection in target_collections: collection.objects.unlink(target_ob) for collection in source_ob.users_collection: collection.objects.link(target_ob) target_ob.parent = source_ob.parent ## -------------------------------------------------------------------------------- def find_unique_name(name:str, library:Iterable) -> str: """ Given a Blender library, find a unique name that does not exist in it. """ if not name in library: return name index = 0 result_name = name + f".{index:03d}" while result_name in library: index += 1 result_name = name + f".{index:03d}" print(f"Unique Name: {result_name}") return result_name ## -------------------------------------------------------------------------------- def duplicate_object(ob:Object, token:str="D", weld=True) -> Object: """ Duplicates the specified object, maintaining the same parenting and collection memberships. """ base_name = "__".join((ob.name.rpartition("__")[0] if "__" in ob.name else ob.name, token)) base_data = "__".join((ob.data.name.rpartition("__")[0] if "__" in ob.data.name else ob.data.name, token)) if base_name in bpy.data.objects: base_name = find_unique_name(base_name, bpy.data.objects) if base_data in bpy.data.objects: base_data = find_unique_name(base_data, bpy.data.objects) data = ob.data.copy() data.name = base_data duplicate = bpy.data.objects.new(base_name, data) ## Ensure scene collection membership ## Prototypes might not have this or be in the view layer if not duplicate.name in bpy.context.scene.collection.all_objects: bpy.context.scene.collection.objects.link(duplicate) select_only(duplicate) ## decimate doesn't work on unwelded triangle soups if weld: bpy.ops.object.mode_set(mode="EDIT") bpy.ops.mesh.select_all(action="SELECT") bpy.ops.mesh.remove_doubles(threshold=0.01, use_unselected=True) bpy.ops.object.mode_set(mode="OBJECT") return duplicate ## -------------------------------------------------------------------------------- def delete_mesh_object(ob:Object): """ Removes object from the Blender library. """ base_name = ob.name data_name = ob.data.name bpy.data.objects.remove(bpy.data.objects[base_name]) bpy.data.meshes.remove(bpy.data.meshes[data_name]) ## -------------------------------------------------------------------------------- def decimate_object(ob:Object, token:str=None, ratio:float=0.5, use_symmetry:bool=False, symmetry_axis="X", min_face_count:int=3, create_duplicate=True): old_mode = bpy.context.mode scene = bpy.context.scene token = token or "DCM" if create_duplicate: target = duplicate_object(ob, token=token) else: target = ob if len(target.data.polygons) < min_face_count: print(f"{target.name} is under face count-- not decimating.") return target ## We're going to use the decimate modifier mod = target.modifiers.new("OmniLOD", type="DECIMATE") mod.decimate_type = "COLLAPSE" mod.ratio = ratio mod.use_collapse_triangulate = True mod.use_symmetry = use_symmetry mod.symmetry_axis = symmetry_axis bpy.ops.object.select_all(action="DESELECT") target.select_set(True) bpy.context.view_layer.objects.active = target bpy.ops.object.modifier_apply(modifier=mod.name) return target ## -------------------------------------------------------------------------------- def decimate_selected(ratios:List[float]=[0.5], min_face_count=3, use_symmetry:bool=False, symmetry_axis="X", use_instancing=True): assert isinstance(ratios, (list, tuple)), "Ratio should be a list of floats from 0.1 to 1.0" for value in ratios: assert 0.1 <= value <= 1.0, f"Invalid ratio value {value} -- should be between 0.1 and 1.0" selected_objects = list(bpy.context.selected_objects) active = bpy.context.view_layer.objects.active selected_meshes = _selected_meshes(bpy.context, use_instancing=use_instancing) total = len(selected_meshes) * len(ratios) count = 1 print(f"\n\n[ Generating {total} decimated LOD meshes (minimum face count: {min_face_count}]") for mesh in selected_meshes: welded_duplicate = duplicate_object(mesh, token="welded") for index, ratio in enumerate(ratios): padd = len(str(total)) - len(str(count)) token = f"LOD{index}" orig_count = len(welded_duplicate.data.vertices) lod_duplicate = decimate_object(welded_duplicate, ratio=ratio, token=token, use_symmetry=use_symmetry, symmetry_axis=symmetry_axis, min_face_count=min_face_count) print(f"[{'0'*padd}{count}/{total}] Decimating {mesh.name} to {ratio} ({orig_count} >> {len(lod_duplicate.data.vertices)}) ...") copy_object_parenting(mesh, lod_duplicate) count += 1 delete_mesh_object(welded_duplicate) print(f"\n[ Decimation complete ]\n\n") ## -------------------------------------------------------------------------------- def import_usd_file(filepath:str, root_prim:Optional[str]=None, visible_only:bool=False, use_instancing:bool=True): all_objects = bpy.context.scene.collection.all_objects names = [x.name for x in all_objects] try: bpy.ops.object.mode_set(mode="OBJECT") except RuntimeError: pass for name in names: ob = bpy.data.objects[name] bpy.data.objects.remove(ob) kwargs = { "filepath":filepath, "import_cameras": False, "import_curves": False, "import_lights": False, "import_materials": True, "import_blendshapes": False, "import_volumes": False, "import_skeletons": False, "import_shapes": False, "import_instance_proxies": True, "import_visible_only": visible_only, "read_mesh_uvs": True, "read_mesh_colors": False, "use_instancing": use_instancing, "validate_meshes": True, } if root_prim: ## if you end with a slash it fails kwargs["prim_path_mask"] = root_prim[:-1] if root_prim.endswith("/") else root_prim bpy.ops.wm.usd_import(**kwargs) print(f"Imported USD file: {filepath}") ## -------------------------------------------------------------------------------- def export_usd_file(filepath:str, use_instancing:bool=True): kwargs = { "filepath":filepath, "visible_objects_only": False, "default_prim_path": "/World", "root_prim_path": "/World", "generate_preview_surface": True, "export_materials": True, "export_uvmaps": True, "merge_transform_and_shape": True, "use_instancing": use_instancing, } bpy.ops.wm.usd_export(**kwargs) print(f"Wrote USD file with UVs: {filepath}") ## ====================================================================== if __name__ == "__main__": real_args = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] parser = argparse.ArgumentParser() parser.add_argument('--input', type=str, required=True, help="Path to input USD file") parser.add_argument('--output', type=str, help="Path to output USD file (default is input_LOD.usd)") parser.add_argument('--ratios', type=str, required=True, help='Ratios to use as a space-separated string, ex: "0.5 0.2"') parser.add_argument('--use_symmetry', action="store_true", default=False, help="Decimate with symmetry enabled.") parser.add_argument('--symmetry_axis', default="X", help="Symmetry axis to use (X, Y, or Z)") parser.add_argument('--visible_only', action="store_true", default=False, help="Only import visible prims from the input USD file.") parser.add_argument('--min_face_count', type=int, default=3, help="Minimum number of faces for decimation.") parser.add_argument('--no_instancing', action="store_false", help="Process the prototype meshes of instanced prims.") parser.add_argument('--root_prim', type=str, default=None, help="Root Prim to import. If unspecified, the whole file will be imported.") if not len(real_args): parser.print_help() sys.exit(1) args = parser.parse_args(real_args) input_file = os.path.abspath(args.input) split = input_file.rpartition(".") output_path = args.output or (split[0] + "_LOD." + split[-1]) ratios = args.ratios if not " " in ratios: ratios = [float(ratios)] else: ratios = list(map(lambda x: float(x), ratios.split(" "))) use_instancing = not args.no_instancing import_usd_file(input_file, root_prim=args.root_prim, visible_only=args.visible_only, use_instancing=use_instancing) bpy.ops.object.select_all(action="SELECT") decimate_selected(ratios=ratios, min_face_count=args.min_face_count, use_symmetry=args.use_symmetry, symmetry_axis=args.symmetry_axis, use_instancing=use_instancing) export_usd_file(output_path, use_instancing=use_instancing) sys.exit(0)
9,912
Python
32.94863
166
0.64659
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/batch/optimize_export.py
import os import sys import time import bpy from omni_optimization_panel.operators import OmniOverrideMixin omniover = OmniOverrideMixin() ## ====================================================================== def perform_scene_merge(): """ Combine all selected mesh objects into a single mesh. """ orig_scene = bpy.context.scene selected = [x for x in bpy.context.selected_objects if x.type == "MESH"] if not len(selected): print("-- No objects selected for merge.") return merge_collection = bpy.data.collections.new("MergeCollection") if not "MergeCollection" in bpy.data.collections else bpy.data.collections["MergeCollection"] merge_scene = bpy.data.scenes.new("MergeScene") if not "MergeScene" in bpy.data.scenes else bpy.data.scenes["MergeScene"] for child in merge_scene.collection.children: merge_scene.collection.children.unlink(child) for ob in merge_collection.all_objects: merge_collection.objects.unlink(ob) to_merge = set() sources = set() for item in selected: to_merge.add(item) merge_collection.objects.link(item) if not item.instance_type == "NONE": item.show_instancer_for_render = True child_set = set(item.children) to_merge |= child_set sources |= child_set merge_scene.collection.children.link(merge_collection) bpy.context.window.scene = merge_scene for item in to_merge: try: merge_collection.objects.link(item) except RuntimeError: continue ## make sure to remove shape keys and merge modifiers for all merge_collection objects for item in merge_collection.all_objects: with omniover.override([item], single=True): if item.data.shape_keys: bpy.ops.object.shape_key_remove(all=True, apply_mix=True) for mod in item.modifiers: bpy.ops.object.modifier_apply(modifier=mod.name, single_user=True) ## turns out the make_duplis_real function swaps selection for you, and ## leaves non-dupli objects selected bpy.ops.object.select_all(action="SELECT") bpy.ops.object.duplicates_make_real() ## this invert and delete is removing the old instancer objects bpy.ops.object.select_all(action="INVERT") for item in sources: item.select_set(True) bpy.ops.object.delete(use_global=False) bpy.ops.object.select_all(action="SELECT") ## need an active object for join poll() bpy.context.view_layer.objects.active = bpy.context.selected_objects[0] bpy.ops.object.join() ## ====================================================================== if __name__ == "__main__": real_args = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] if not len(real_args): print("-- No output path name.") sys.exit(-1) output_file = real_args[-1] ## make sure the add-on is properly loaded bpy.ops.preferences.addon_enable(module="omni_optimization_panel") start_time = time.time() ## pull all attribute names from all mixins for passing on to the optimizer sceneopts = bpy.context.scene.omni_sceneopt chopopts = bpy.context.scene.omni_sceneopt_chop skips = {"bl_rna", "name", "rna_type"} optimize_kwargs = {} for item in sceneopts, chopopts: for key in filter(lambda x: not x.startswith("__") and not x in skips, dir(item)): optimize_kwargs[key] = getattr(item, key) print(f"optimize kwargs: {optimize_kwargs}") if sceneopts.merge: ## merge before because of the possibility of objects getting created perform_scene_merge() bpy.ops.wm.save_as_mainfile(filepath=output_file.rpartition(".")[0]+".blend") ## always export whole scene optimize_kwargs["selected"] = False optimize_kwargs["verbose"] = True bpy.ops.omni_sceneopt.optimize(**optimize_kwargs) optimize_time = time.time() print(f"Optimization time: {(optimize_time - start_time):.2f} seconds.") export_kwargs = { "filepath": output_file, "visible_objects_only": False, "default_prim_path": "/World", "root_prim_path": "/World", "material_prim_path": "/World/materials", "generate_preview_surface": True, "export_materials": True, "export_uvmaps": True, "merge_transform_and_shape": True, "use_instancing": True, "export_textures": sceneopts.export_textures, } bpy.ops.wm.usd_export(**export_kwargs) export_time = time.time() print(f"Wrote optimized USD file: {output_file}") print(f"Export time: {(export_time - optimize_time):.2f} seconds.") print(f"Total time: {(export_time - start_time):.2f} seconds.") sys.exit(0)
4,378
Python
30.278571
157
0.693011
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/batch/uv.py
import argparse import os import sys from typing import * import bpy from bpy.types import (Collection, Context, Image, Object, Material, Mesh, Node, NodeSocket, NodeTree, Scene) from bpy.props import * from mathutils import * ## ====================================================================== OMNI_MATERIAL_NAME = "OmniUVTestMaterial" ## ====================================================================== def select_only(ob:Object): """ Ensure that only the specified object is selected. :param ob: Object to select """ bpy.ops.object.select_all(action="DESELECT") ob.select_set(state=True) bpy.context.view_layer.objects.active = ob ## -------------------------------------------------------------------------------- def _selected_meshes(context:Context) -> List[Mesh]: """ :return: List[Mesh] of all selected mesh objects in active Blender Scene. """ return [x for x in context.selected_objects if x.type == "MESH"] ## -------------------------------------------------------------------------------- def get_test_material() -> Material: image_name = "OmniUVGrid" if not image_name in bpy.data.images: bpy.ops.image.new(generated_type="COLOR_GRID", width=4096, height=4096, name=image_name, alpha=False) if not OMNI_MATERIAL_NAME in bpy.data.materials: image = bpy.data.images[image_name] material = bpy.data.materials.new(name=OMNI_MATERIAL_NAME) ## this creates the new graph material.use_nodes = True tree = material.node_tree shader = tree.nodes['Principled BSDF'] im_node = tree.nodes.new("ShaderNodeTexImage") im_node.location = [-300, 300] tree.links.new(im_node.outputs['Color'], shader.inputs['Base Color']) im_node.image = image return bpy.data.materials[OMNI_MATERIAL_NAME] ## -------------------------------------------------------------------------------- def apply_test_material(ob:Object): ##!TODO: Generate it select_only(ob) while len(ob.material_slots): bpy.ops.object.material_slot_remove() material = get_test_material() bpy.ops.object.material_slot_add() ob.material_slots[0].material = material ## -------------------------------------------------------------------------------- def unwrap_object(ob:Object, uv_layer_name="OmniUV", apply_material=False, margin=0.0): """ Unwraps the target object by creating a fixed duplicate and copying the UVs over to the original. """ old_mode = bpy.context.mode scene = bpy.context.scene if not old_mode == "OBJECT": bpy.ops.object.mode_set(mode="OBJECT") select_only(ob) uv_layers = list(ob.data.uv_layers) for layer in uv_layers: ob.data.uv_layers.remove(layer) bpy.ops.object.mode_set(mode="EDIT") bpy.ops.mesh.select_all(action='SELECT') bpy.ops.uv.cube_project() bpy.ops.object.mode_set(mode="OBJECT") duplicate = ob.copy() duplicate.data = ob.data.copy() scene.collection.objects.link(duplicate) ## if the two objects are sitting on each other it gets silly, ## so move the dupe over by double it's Y bounds size bound_size = Vector(duplicate.bound_box[0]) - Vector(duplicate.bound_box[-1]) duplicate.location.y += bound_size.y select_only(duplicate) bpy.ops.object.mode_set(mode="EDIT") bpy.ops.mesh.select_all(action='SELECT') bpy.ops.mesh.remove_doubles(threshold=0.01, use_unselected=True) bpy.ops.mesh.normals_make_consistent(inside=True) bpy.ops.object.mode_set(mode="OBJECT") bpy.ops.object.mode_set(mode="EDIT") bpy.ops.uv.select_all(action='SELECT') bpy.ops.uv.smart_project(island_margin=margin) bpy.ops.uv.average_islands_scale() bpy.ops.uv.pack_islands(margin=0) bpy.ops.object.mode_set(mode="OBJECT") ## copies from ACTIVE to all other SELECTED select_only(ob) ## This is incredibly broken # bpy.ops.object.data_transfer(data_type="UV") ## snap back now that good UVs exist; the two meshes need to be in the same ## position in space for the modifier to behave correctly. duplicate.matrix_world = ob.matrix_world.copy() modifier = ob.modifiers.new(type="DATA_TRANSFER", name="OmniBake_Transfer") modifier.object = duplicate modifier.use_loop_data = True modifier.data_types_loops = {'UV'} modifier.loop_mapping = 'NEAREST_NORMAL' select_only(ob) bpy.ops.object.modifier_apply(modifier=modifier.name) if apply_material: apply_test_material(ob) bpy.data.objects.remove(duplicate) ## -------------------------------------------------------------------------------- def unwrap_selected(uv_layer_name="OmniUV", apply_material=False, margin=0.0): old_mode = bpy.context.mode selected_objects = list(bpy.context.selected_objects) active = bpy.context.view_layer.objects.active selected_meshes = _selected_meshes(bpy.context) total = len(selected_meshes) count = 1 print(f"\n\n[ Unwrapping {total} meshes ]") for mesh in selected_meshes: padd = len(str(total)) - len(str(count)) print(f"[{'0'*padd}{count}/{total}] Unwrapping {mesh.name}...") unwrap_object(mesh, uv_layer_name=uv_layer_name, apply_material=apply_test_material) count += 1 print(f"\n[ Unwrapping complete ]\n\n") select_only(selected_objects[0]) for item in selected_objects[1:]: item.select_set(True) bpy.context.view_layer.objects.active = active if old_mode == "EDIT_MESH": bpy.ops.object.mode_set(mode="EDIT") ## -------------------------------------------------------------------------------- def import_usd_file(filepath:str, root_prim=None, visible_only=False): all_objects = bpy.context.scene.collection.all_objects names = [x.name for x in all_objects] try: bpy.ops.object.mode_set(mode="OBJECT") except RuntimeError: pass for name in names: ob = bpy.data.objects[name] bpy.data.objects.remove(ob) kwargs = { "filepath":filepath, "import_cameras": False, "import_curves": False, "import_lights": False, "import_materials": False, "import_blendshapes": False, "import_volumes": False, "import_skeletons": False, "import_shapes": False, "import_instance_proxies": True, "import_visible_only": visible_only, "read_mesh_uvs": False, "read_mesh_colors": False, } if root_prim: ## if you end with a slash it fails kwargs["prim_path_mask"] = root_prim[:-1] if root_prim.endswith("/") else root_prim bpy.ops.wm.usd_import(**kwargs) print(f"Imported USD file: {filepath}") ## -------------------------------------------------------------------------------- def export_usd_file(filepath:str): kwargs = { "filepath":filepath, "visible_objects_only": False, "default_prim_path": "/World", "root_prim_path": "/World", # "generate_preview_surface": False, # "generate_mdl": False, "merge_transform_and_shape": True, } bpy.ops.wm.usd_export(**kwargs) print(f"Wrote USD file with UVs: {filepath}") ## ====================================================================== if __name__ == "__main__": real_args = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] parser = argparse.ArgumentParser() parser.add_argument('--input', type=str, required=True, help="Path to input USD file") parser.add_argument('--output', type=str, help="Path to output USD file (default is input_UV.usd)") parser.add_argument('--margin', type=float, default=None, help="Island margin (default is 0.01)") parser.add_argument('--root_prim', type=str, default=None, help="Root Prim to import. If unspecified, the whole file will be imported.") parser.add_argument('--add_test_material', action="store_true") parser.add_argument('--visible_only', action="store_true", default=False) if not len(real_args): parser.print_help() sys.exit(1) args = parser.parse_args(real_args) input_file = os.path.abspath(args.input) split = input_file.rpartition(".") output_path = args.output or (split[0] + "_UV." + split[-1]) margin = args.margin or 0.0 import_usd_file(input_file, root_prim=args.root_prim, visible_only=args.visible_only) bpy.ops.object.select_all(action="SELECT") unwrap_selected(apply_material=args.add_test_material, margin=margin) export_usd_file(output_path) sys.exit(0)
8,005
Python
29.674329
103
0.639975
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/scripts/geo_nodes.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import bpy from mathutils import Vector # the type of geometry node tree to create: # geometry nodes is currently under development, so feature set is not yet at a stage to be fully utilized # this puts in place a framework for more customizable and easily implementable optimizations in the future # geometry nodes is a modifier, but unlike "DECIMATE" or "REMESH", geometry nodes can be customized with a wide array of options. # similar to other modifiers, if there are multiple objects with the same geo node modifier, the calculations are done independently for each object. # currently this setup can be used for generating convex hulls, creating bounding box meshes, and subdividing geometry. # (GeometryNodeConvexHull, GeometryNodeBoundBox, GeometryNodeSubdivisionSurface) # as the nodes options in blender expand, A lot more can be done wit it. # more on geometry nodes: https://docs.blender.org/manual/en/latest/modeling/geometry_nodes/index.html#geometry-nodes def new_GeometryNodes_group(): # create a new empty node group that can be used in a GeometryNodes modifier # tree only contains a simple input/output node setup # the input node gives a geometry, and the output node takes a geometry. # nodes then have input and output SOCKET(S). # this basic tree setup will accesses the output socket of the input node in order to connect it to the input socket of the output node # in order to make these connections, physical links between index values of inputs and outputs need to be made # this tree on its own will do nothing. In order to make changes to the geometry, more nodes must be inserted node_group = bpy.data.node_groups.new('GeometryNodes', 'GeometryNodeTree') # this is the container for the nodes inNode = node_group.nodes.new('NodeGroupInput') # this is the input node and gives the geometry to be modified. inNode.outputs.new('NodeSocketGeometry', 'Geometry') # gets reference to the output socket on the input node outNode = node_group.nodes.new('NodeGroupOutput') # this is the output node and returns the geometry that modified. outNode.inputs.new('NodeSocketGeometry', 'Geometry') # gets reference to the input socket on the output node node_group.links.new(inNode.outputs['Geometry'], outNode.inputs['Geometry']) # makes the link between the two nodes at the given sockets inNode.location = Vector((-1.5*inNode.width, 0)) # sets the position of the node in 2d space so that they are readable in the GUI outNode.location = Vector((1.5*outNode.width, 0)) return node_group # now that there is a basic node tree, additional nodes can be inserted into the tree to modify the geometry def geoTreeBasic(geo_tree, nodes, group_in, group_out, geo_type, attribute): # once the base geo tree has been created, we can insert additional pieces # this includes: convex hull, bounding box, subdivide new_node = nodes.new(geo_type) # create a new node of the specified type # insert that node between the input and output node geo_tree.links.new(group_in.outputs['Geometry'], new_node.inputs[0]) geo_tree.links.new(new_node.outputs[0], group_out.inputs['Geometry']) if geo_type == 'GeometryNodeSubdivisionSurface': # subsurf node requires an additional input value geo_tree.nodes["Subdivision Surface"].inputs[1].default_value = attribute def geoNodes(objects, geo_type, attribute): # TODO: When Geo Nodes develops further, hopefully all other modifier ops can be done through nodes # (currently does not support decimate/remesh) modifier = 'NODES' # create empty tree - this tree is a container for nodes geo_tree = new_GeometryNodes_group() # add tree to all objects for obj in objects: # for each object in selected objects, add the desired modifier and adjust its properties mod = obj.modifiers.new(name = modifier, type=modifier) # set name of modifier based on its type mod.node_group = geo_tree #bpy.data.node_groups[geo_tree.name] # alter tree - once the default tree has been created, additional nodes can be added in nodes = geo_tree.nodes group_in = nodes.get('Group Input') # keep track of the input node group_out = nodes.get('Group Output') # keep track of the output node geoTreeBasic(geo_tree, nodes, group_in, group_out, geo_type, attribute) # adds node to make modifications to the geometry
5,272
Python
63.304877
149
0.744499
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/scripts/run_ops_wo_update.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. from bpy.ops import _BPyOpsSubModOp view_layer_update = _BPyOpsSubModOp._view_layer_update def open_update(): # blender operator calls update the scene each time after running # updating the scene can take a long time, esp for large scenes. So we want to delay update until we are finished # there is not an official way to suppress this update, so we need to use a workaround def dummy_view_layer_update(context): # tricks blender into thinking the scene has been updated and instead passes pass _BPyOpsSubModOp._view_layer_update = dummy_view_layer_update def close_update(): # in the end, still need to update scene, so this manually calls update _BPyOpsSubModOp._view_layer_update = view_layer_update
1,619
Python
42.783783
118
0.731316
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/scripts/chop.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import bpy, bmesh from mathutils import Vector import time from . import blender_class, run_ops_wo_update, select_mesh, bounds, utils, fix_mesh class Chop(blender_class.BlenderClass): # settings for GUI version only bl_idname = "chop.scene" bl_label = "Chop Scene" bl_description = "Recursively split scene in half until reaches a desired threshold" bl_options = {"REGISTER", "UNDO"} print_results = True def __init__(self): self._default_attributes = dict( merge= True, # optionally merge meshes in each split chunk after split recursion is complete cut_meshes=True, # split all meshes intersecting each cut plane # Cannot set this very low since split creates new triangles(if quads...) max_vertices= 100000, # a vertex threshold value, that once a chunk is below, the splitting terminates min_box_size= 1, # a size threshold that once a chunk is smaller than, the splitting terminates max_depth= 16, # a recursion depth threshold that once is reached, the splitting terminates print_updated_results= True, # print progress to console create_bounds = False, # create new bounds objects for displaying the cut boundaries. Mostly useful for GUI selected_only = False # uses only objects selected in scene. For GUI version only ) def execute(self, in_attributes=None): attributes = self.get_attributes(in_attributes) context = bpy.context Chop.print_results = attributes["print_updated_results"] Stats.resetValues() Stats.startTime = time.time() then = Stats.startTime # select objects selected = select_mesh.setSelected(context, attributes["selected_only"], deselectAll = False) if len(selected): # run only if there are selected mesh objects in the scene self.split(context, selected, attributes) # starts the splitting process now = time.time() # time after it finished Stats.printTermination() if attributes['merge']: Stats.printMerge() print("TIME FOR SPLIT: ", round(now-then, 3)) else: utils.do_print_error("NO MESH OBJECTS") return {'FINISHED'} def getSplitPlane(self, obj_details): # the cut plane used in split. Aligned perpendicular to the longest dimension of the bounds # find longest side var = {obj_details.x.distance: "x", obj_details.y.distance: "y", obj_details.z.distance: "z"} max_dim = var.get(max(var)) # get the axis name of maximum of the three dims # adjust the plane normal depending on the axis with the largest dimension if max_dim == "x": normal = [1,0,0,0] axis = "x" elif max_dim == "y": normal = [0,1,0,0] axis = "y" else: normal = [0,0,1,0] axis = "z" # get data for sub-boxes midPt = [obj_details.x.mid,obj_details.y.mid,obj_details.z.mid] # get center of bounds to be able to create the next set of bounds return midPt, normal, axis def getSplitBoxes(self, obj_details, attributes): # get the bounds for the two successive splits during recursion # find longest side var = {obj_details.x.distance: "x", obj_details.y.distance: "y", obj_details.z.distance: "z"} mx = var.get(max(var)) # get the axis name of maximum of the three dims mid_0 = [obj_details.x.max, obj_details.y.max, obj_details.z.max] # the longest axis value will be replaced with a mid point high = mid_0.copy() # maximum value of bounds mid_1 = [obj_details.x.min, obj_details.y.min, obj_details.z.min] # the longest axis value will be replaced with a mid point low = mid_1.copy() # minimum value fo bounds midPt = [obj_details.x.mid,obj_details.y.mid,obj_details.z.mid] # center point of previous bounds # replace the mid point of new bounds depending on the axis with the largest dimension if mx == "x": mid_0[0] = midPt[0] mid_1[0] = midPt[0] elif mx == "y": mid_0[1] = midPt[1] mid_1[1] = midPt[1] else: mid_0[2] = midPt[2] mid_1[2] = midPt[2] # Create sub-bounds. These are the two halves of the previous bounds, split along the longest axis of the bounds # only need two points to calculate bounds, uses the maximum/minimum value point (high/low) and the set mid point (mid_0/mid_1) coords_1 = [high[:], mid_1[:]] # put the points in a list box_0 = bounds.bounds(coords_1) # gather attributes of new bounds (max, min, mid, and dim of each axis) coords_0 = [low[:], mid_0[:]] # put the points in a list box_1 = bounds.bounds(coords_0) # gather attributes of new bounds (max, min, mid, and dim of each axis) if attributes["create_bounds"]: # optionally create display objects for viewing bounds bounds.boundsObj(coords_1) bounds.boundsObj(coords_0) return box_0, box_1 def boxTooSmall(self, obj_details, attributes): # returns whether bounds of current occurrences is too small # find longest sides dims = [obj_details.x.distance, obj_details.y.distance, obj_details.z.distance] # get the dimensions of each axis of the bounds if max(dims) < attributes["min_box_size"]: # if the maximum of the three dims is less than the specified min_box_size return True # continue recursion return False # end recursion def parentEmpty(self, part, children): # for parenting new created objects from split parent_name = part.name # part is the original object that was split. keep track of its name parent_col = part.users_collection[0] # track the collection of the part as well parent_parent = part.parent # if the part object has an existing parent track that too bpy.data.objects.remove(part, do_unlink=True) # now that that info is stored, part can be deleted and removed from the scene # an empty will take the place of the original part obj = bpy.data.objects.new(parent_name, None) # create an empty object that will inherit the name of part parent_col.objects.link(obj) # connect this object to part's collection obj.parent = parent_parent # make this empty the child of part's parent for child in children: # make the newly created objects from the split operation children of the empty child.parent = obj def newObj(self, bm, parent): # create a new object for each half of a split obj = parent.copy() # parent is the original mesh being split. this contains data such as material, # so it is easiest to start with a copy of the object obj.data = parent.data.copy() # need to copy the object mesh data separately # TODO: obj.animation_data = sibling.animation_data.copy() # not sure if animation data should be copied. This would do that. parent.users_collection[0].objects.link(obj) # apply bmesh to new mesh bm.to_mesh(obj.data) # Once the new object is formed, bmesh data created during the split process can be transferred to the new obj bm.free() # always do this when finished with a bmesh return obj def checkIntersect(self, obj, axis, center): # for checking cut plane intersection while splitting # intersection is checked by testing the objects bounds rather than each vertex individually obj_details = bounds.bounds([obj.matrix_world @ Vector(v) for v in obj.bound_box]) tolerance = .01 # a tolerance value for intersection to prevent cutting a mesh that is in line with cut plane # TODO: may need to have user control over this tolerance, or define it relative to total scene size. # check for intersection depending on the direction of the cutting # boolean is created for both sides of cut plane. # rather than a single boolean checking for intersection, return if mesh is on one or both sides of cut plane. if axis == "x": intersect_0 = obj_details.x.max > center[0] + tolerance intersect_1 = obj_details.x.min < center[0] - tolerance elif axis == "y": intersect_0 = obj_details.y.max > center[1] + tolerance intersect_1 = obj_details.y.min < center[1] - tolerance elif axis == "z": intersect_0 = obj_details.z.max > center[2] + tolerance intersect_1 = obj_details.z.min < center[2] - tolerance return intersect_0, intersect_1 def doSplit(self, partsToSplit, planeOrigin, planeNormal, axis): # perform the actual split # split separates the occurrences into two. those halves need to be stored in their own new lists occurrences_0 = [] occurrences_1 = [] for part in partsToSplit: # iterate over occurrences intersect_0, intersect_1 = self.checkIntersect(part, axis, planeOrigin) # only perform split if object intersects the cut plane. if intersect_0 and intersect_1: # if mesh has vertices on both sides of cut plane Stats.printPart(part) # print the part being processed co = part.matrix_world.inverted() @ Vector(planeOrigin) # splitting takes place relative to object space not world space. normDir = part.matrix_world.transposed() @ Vector(planeNormal) # need to adjust plane origin and normal for each object. bmi = bmesh.new() # 'bmesh' in Blender is data type that contains the 'edit mesh' for an object # It allows for much greater control over mesh properties and operations bmi.from_mesh(part.data) # attach the mesh to the bmesh container so that changes can be made bmo = bmi.copy() # must use two separate bmesh objects because two new occurrence lists are being written to # bisect_plane is how to split a mesh using a plane. It can only save one side of the split result at a time, so it is done twice # save inner mesh data bmesh.ops.bisect_plane(bmi, geom=bmi.verts[:]+bmi.edges[:]+bmi.faces[:], # the geometry to be split, which is the first bmesh just created dist=0.0001, # a threshold value for the split to check vertex proximity to cut plane # TODO: may need to have user control over this tolerance, or define it relative to total scene size. plane_co=co, # the cut plane plane_no=(normDir.x,normDir.y,normDir.z), # the plane normal direction clear_inner=True, # remove the geometry on the positive side of the cut plane clear_outer=False) # keep the geometry on the negative side of the cut plane # save outer mesh data bmesh.ops.bisect_plane(bmo, geom=bmo.verts[:]+bmo.edges[:]+bmo.faces[:], # the geometry to be split, which is the second bmesh just created dist=0.0001, # a threshold value for the split to check vertex proximity to cut plane plane_co=co, # the cut plane plane_no=(normDir.x,normDir.y,normDir.z), # the plane normal direction clear_inner=False, # keep the geometry on the positive side of the cut plane clear_outer=True) # remove the geometry on the negative side of the cut plane # make the bmesh the object's mesh # need to transfer the altered bmesh data back to the original mesh children = [] # create a list that will contain the newly created split meshes obj = self.newObj(bmi, part) # create a new mesh object to attach the inner bmesh data to occurrences_0.append(obj) # add new object to inner occurrence list children.append(obj) # add new object to children list obj2 = self.newObj(bmo, part) # create a new mesh object to attach the outer bmesh data to occurrences_1.append(obj2) # add new object to outer occurrence list children.append(obj2) # add new object to children list self.parentEmpty(part, children) # use children list to fix object parents if Chop.print_results: utils.printClearLine() # clear last printed line before continuing # if there are vertices on only one side of the cut plane there is nothing to split so place the existing mesh into the appropriate list elif intersect_0: occurrences_0.append(part) # add object to inner occurrence list part.select_set(False) # deselect object else: occurrences_1.append(part )# add object to outer occurrence list part.select_set(False) # deselect object # bisect_plane can create empty objects, or zero vert count meshes. remove those objects before continuing occurrences_0 = fix_mesh.deleteEmptyXforms(occurrences_0) # update occurrences_0 occurrences_1 = fix_mesh.deleteEmptyXforms(occurrences_1) # update occurrences_1 return occurrences_0, occurrences_1 def doMerge(self, partsToMerge): # for merging individual meshes within each chunk after split is complete if len(partsToMerge) > 1: # if there is only one mesh or zero meshes, there is no merging to do then = time.time() # time at the beginning of merge ctx = bpy.context.copy() #making a copy of the current context allows for temporary modifications to be made # in this case, the temporary context is switching the active and selected objects # this allows avoiding needing to deselect and reselect after the merge ctx['selected_editable_objects'] = partsToMerge # set the meshes in the chunk being merged to be selected ctx['active_object'] = partsToMerge[0] # set active object. Blender needs active object to be the selected object parents = [] # a list that will contain the parent of each part being merged for merge in partsToMerge: parents.append(merge.parent) run_ops_wo_update.open_update() # allows for operators to be run without updating scene bpy.ops.object.join(ctx) # merges all parts into one run_ops_wo_update.close_update() # must always call close_update if open_update is called now = time.time() # time after merging is complete Stats.mergeTime += (now-then) # add time to total merge time to get an output of total time spent on merge def recursiveSplit(self, occurrences, attributes, obj_details, depth): # runs checks before each split, and handles recursion if not occurrences: # if there are no occurrences, end recursion Stats.printPercent(depth, True) # optionally print results before ending recursion return # Check for maximum recursive depth has been reached to terminate and merge if attributes["max_depth"] != 0 and depth >= attributes["max_depth"]: # if max recursion depth is 0, the check will be ignored Stats.chunks += 1 # each split creates a new chunk, adds only chunks from completed recursive branches Stats.printMsg_maxDepth += 1 # "REACHED MAX DEPTH" Stats.printPercent(depth) # optionally print results before ending recursion if attributes["merge"]: # if merging, do so now self.doMerge(occurrences) return # Check for vertex count threshold and bbox size to terminate and merge vertices = utils.getVertexCount(occurrences) if self.boxTooSmall(obj_details, attributes) or vertices < attributes["max_vertices"]: Stats.chunks += 1 # each split creates a new chunk, adds only chunks form completed recursive branches if vertices < attributes["max_vertices"]: Stats.printMsg_vertexGoal += 1 # "REACHED VERTEX GOAL" elif self.boxTooSmall(obj_details, attributes): # or vertices < attributes["max_vertices"]: Stats.printMsg_boxSize += 1 # "BOX TOO SMALL" Stats.printPercent(depth) # optionally print results before ending recursion if attributes["merge"]: # if merging, do so now self.doMerge(occurrences) return # Keep subdividing planeOrigin, planeNormal, axis = self.getSplitPlane(obj_details) # calculate components for cutter object # Do the split and merge if attributes["cut_meshes"]: # splits meshes in scene based on cut plane and separates them into two halves occurrences_0, occurrences_1 = self.doSplit(occurrences, planeOrigin, planeNormal, axis) depth += 1 # if split has taken place, increment recursive depth count # Recurse. Get bounding box for each half. box_0, box_1 = self.getSplitBoxes(obj_details, attributes) self.recursiveSplit(occurrences_0, attributes, box_0, depth) self.recursiveSplit(occurrences_1, attributes, box_1, depth) def split(self, context, selected, attributes): # preps original occurrences and file for split occurrences = selected # tracks the objects for each recursive split # on the first split, this is the selected objects. # Initial bbox includes all original occurrences boundsCombined = bounds.boundingBox(occurrences) # gets the combined bounds coordinates of the occurrences obj_details = bounds.bounds(boundsCombined) # create a dictionary of specific statistics for each axis of bounds if attributes["create_bounds"]: # optionally create a bounds object for each recursive split. target_coll_name = "BOUNDARIES" # put these objects in a separate collection to keep scene organized target_coll = bpy.data.collections.new(target_coll_name) # create a new collection in the master scene collection context.scene.collection.children.link(target_coll) # link the newly created collection to the scene bounds.boundsObj(boundsCombined) # create bounds obj depth = 0 # tracks recursive depth print("-----SPLIT HAS BEGUN-----") Stats.printPercent(depth) # for optionally printing progress of operation self.recursiveSplit(occurrences, attributes, obj_details, depth) # begin recursive split class Stats(): startTime= 0 # start time of script execution, used for calculating progress printMsg_vertexGoal = 0 # for tracking number of times recursion terminated because vertex goal was reached printMsg_boxSize = 0 # for tracking number of times recursion terminated because box was too small printMsg_maxDepth = 0 # for tracking number of times recursion terminated because max recursive depth was exceeded percent_worked = 0 # for tracking amount of scene that contains objects for progress calculation percent_empty = 0 # for tracking amount of scene that is empty for progress calculation chunks = 0 # the number of parts created after the recursive split. each chunk may contain multiple meshes/objects mergeTime = 0 # for tracking the amount of time spent merging chunks def resetValues(): # reset values before running Stats.startTime= 0 Stats.printMsg_vertexGoal = 0 Stats.printMsg_boxSize = 0 Stats.printMsg_maxDepth = 0 Stats.percent_worked = 0 Stats.percent_empty = 0 Stats.chunks = 0 Stats.mergeTime = 0 # for printing progress statistics to console def printTermination(): print("Reached Vertex Goal: ", Stats.printMsg_vertexGoal, # print number of times recursion terminated because vertex goal was reached " Box Too Small: ", Stats.printMsg_boxSize, # print number of times recursion terminated because box was too small " Exceeded Max Depth: ", Stats.printMsg_maxDepth) # print number of times recursion terminated because max recursive depth was exceeded print("chunks: ", Stats.chunks) # print total number of chunks created from split def printMerge(): print("merge time: ", Stats.mergeTime) # print the total time the merging took def printPart(part): if Chop.print_results: print("current part being split: ", part) # want to keep track of latest part being split in order to more easily debug if blender crashes def printPercent(depth, empty=False): # for printing progress of recursive split if Chop.print_results: if depth != 0: if empty: # generated chunk contains no geometry it is considered empty Stats.percent_empty += 100/pow(2,depth) # calculated as a fraction of 2 raised to the recursive depth. Gives a measurement of total volume complete elif depth: # cannot calculate if depth is zero due to division by zero Stats.percent_worked += 100/pow(2,depth) # calculated as a fraction of 2 raised to the recursive depth. Gives a measurement of total volume complete total = Stats.percent_empty + Stats.percent_worked # percent of bounds volume calculated. Includes empty and occupied chunks percent_real = Stats.percent_worked/(100-Stats.percent_empty)*100 # calculated based on a ratio of chunks with split meshes to empty chunks. # this results in a more accurate calculation of remaining time because empty chunks take virtually zero time to process #timer now = time.time() # current time elapsed in operation if percent_real > 0: # if at least one occupied chunk has been calculated est_comp_time = f"{((now-Stats.startTime)/percent_real*100 - (now-Stats.startTime)):1.0f}" # estimation of remaining time # based on what has already been processed else: est_comp_time = "Unknown" utils.printClearLine() utils.printClearLine() # print results to console print("\033[93m" + "Percent_empty: ", f"{Stats.percent_empty:.1f}" , "%, Percent_worked: ", f"{Stats.percent_worked:.1f}", "%, Total: ", f"{total:.1f}", "%, Real: ", f"{percent_real:.1f}", "%") print("Estimated time remaining: ", est_comp_time, "s, Depth: ", depth, "\033[0m") else: print() # empty lines to prep for the progress printing print() # empty lines to prep for the progress printing
23,807
Python
59.580153
168
0.656278
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/scripts/fix_mesh.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import bpy import bmesh import time from functools import reduce from . import blender_class, run_ops_wo_update, select_mesh, utils class FixMesh(blender_class.BlenderClass): # settings for GUI version only bl_idname = "fix.mesh" bl_label = "Fix Mesh" bl_description = "fix bad meshes in the scene" bl_options = {"REGISTER", "UNDO"} def __init__(self): self._default_attributes = dict( selected_only=False, # uses only objects selected in scene. For GUI version only fix_bad_mesh = True, # used to remove zero are faces and zero length edges based on the 'dissolve_threshold' dissolve_threshold = 0.08, # threshold value for 'fix_bad_mesh' merge_vertex = False, # merge connected and disconnected vertices of a mesh by a distance threshold merge_threshold = 0.01, # distance value to use for merge_vertex remove_existing_sharp = True, # when removing zero area faces, edge data can become messed up, causing bad normals. This helps minimize that. fix_normals = True, # optionally fix normals. useful for after 'fix_bad_mesh' to fix the normals as well. create_new_custom_normals = True # will auto generate new sharp edges (based on angle) ) def execute(self, in_attributes=None): attributes = self.get_attributes(in_attributes) context = bpy.context then = time.time() # start time of script execution if context.mode != 'OBJECT': # must be in object mode to perform the rest of the operations. bpy.ops.object.mode_set(mode='OBJECT') # select objects selected = select_mesh.setSelected(context, attributes["selected_only"], deselectAll = False) if len(selected): # run only if there are selected mesh objects in the scene # if removing zero-area-faces/zero-length-edges or merging vertices by distance: if attributes["fix_bad_mesh"] or attributes["merge_vertex"]: self.fixBadMesh( selected, attributes["dissolve_threshold"], attributes["fix_bad_mesh"], attributes["merge_vertex"], attributes["merge_threshold"], attributes["remove_existing_sharp"]) if attributes["fix_normals"]: # optionally fix bad normals (can often arise after fixing bad mesh) self.fixNormals(selected, attributes["create_new_custom_normals"]) else: utils.do_print_error("NO MESH OBJECTS") now = time.time() # time after it finished print("TIME FOR FIX MESH: ", round(now-then, 3)) return {'FINISHED'} def fixBadMesh(self, selected, dissolveThreshold = 0.08, fixBadMesh = False, mergeVertex = False, mergeThreshold = 0.1, removeExistingSharp = True): # once degenerate dissolve geometry node exists (needs to be developed by Blender), replace this with a GN setup # that would go towards producing non-destructive workflows, which is a goal for the GUI version # for printing vertex and face data startingVerts = utils.getVertexCount(selected) startingFaces = utils.getFaceCount(selected) bm = bmesh.new() # 'bmesh' in BLender is data type that contains the 'edit mesh' for an object # It allows for much greater control over mesh properties and operations for object in selected: # loop through each selected object utils.printPart(object) # print the current part being fixed. mesh = object.data # all mesh objects contain mesh data, that is what we need to alter, not the object itself bm.from_mesh(mesh) # attach the mesh to the bmesh container so that changes can be made if fixBadMesh: bmesh.ops.dissolve_degenerate( # for removing zero area faces and zero length edges bm, dist=dissolveThreshold, edges=bm.edges ) if mergeVertex: bmesh.ops.remove_doubles( bm, verts=bm.verts, dist=mergeThreshold ) # Clear sharp state for all edges. This step reduces problems that arise from bad normals if removeExistingSharp: for edge in bm.edges: edge.smooth = True # smooth is the opposite of sharp, so setting to smooth is the same as removing sharp bm.to_mesh(mesh) # need to transfer the altered bmesh data back to the original mesh bm.clear() # always clear a bmesh after use utils.printClearLine() # remove last print, so that printPart can be updated # print vertex and face data endingVerts = utils.getVertexCount(selected) endingFaces = utils.getFaceCount(selected) vertsRemoved = startingVerts-endingVerts facesRemoved = startingFaces-endingFaces print("Fix Mesh Statistics:") utils.do_print("Starting Verts: " + str(startingVerts) + ", Ending Verts: " + str(endingVerts) + ", Verts Removed: " + str(vertsRemoved)) utils.do_print("Starting Faces: " + str(startingFaces) + ", Ending Faces: " + str(endingFaces) + ", Faces Removed: " + str(facesRemoved)) def fixNormals(self, selected, createNewCustomNormals): run_ops_wo_update.open_update() # allows for operators to be run without updating scene # important especially when working with loops for o in selected: if o.type != 'MESH': continue bpy.context.view_layer.objects.active = o mesh = o.data if mesh.has_custom_normals: bpy.ops.mesh.customdata_custom_splitnormals_clear() if createNewCustomNormals: bpy.ops.mesh.customdata_custom_splitnormals_add() run_ops_wo_update.close_update() # must always call close_update if open_update is called def deleteEmptyXforms(occurrences): # Delete objects with no meshes, or zero vertex count meshes # first separate occurrences into two lists to get meshes with zero vertex count def partition(p, l): # uses lambda function to efficiently parse data return reduce(lambda x, y: x[not p(y)].append(y) or x, l, ([], [])) # if obj has vertices place in x, else place in y occurrences_clean, occurrences_dirty = partition(lambda obj:len(obj.data.vertices), occurrences) # delete obj with zero vertex count or no meshes for obj in occurrences_dirty: bpy.data.objects.remove(obj, do_unlink=True) # return good meshes return occurrences_clean
7,637
Python
48.597402
153
0.647506
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/scripts/bounds.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import bpy, bmesh from mathutils import Vector import collections def boundsObj(points): # for displaying the bounds of each split chunk mesh = bpy.data.meshes.new("mesh") # add a new mesh obj = bpy.data.objects.new("MyObject", mesh) # add a new object using the new mesh # link the new bounds object to the newly created collection in split. # this is the last collection added to the scene, hence index of len -1 bpy.context.scene.collection.children[len( bpy.context.scene.collection.children)-1].objects.link(obj) obj.display_type = 'BOUNDS' # display only the objects bounds in the Blender viewport. bm = bmesh.new() # 'bmesh' in Blender is data type that contains the 'edit mesh' for an object # allows control over vertices, edges, and faces for point in points: # iterate over input bounds(points) bm.verts.new(point) # add a new vert # make the bmesh the object's mesh bm.to_mesh(obj.data) # transfer bmesh data to the new obj bm.free() # always do this when finished with a bmesh return obj def boundingBox(objects): # the bounding box used for calculating the split plane if not isinstance(objects, list): # if objects is not a list convert it to one objects = [objects] points_co_global = [] # list of all vertices of all objects from list with global coordinates for obj in objects: # iterate over objects list and add its vertices to list points_co_global.extend([obj.matrix_world @ Vector(v) for v in obj.bound_box]) # must add points in world space return points_co_global def bounds(coords): # returns a dictionary containing details of split bounds zipped = zip(*coords) # The zip() function returns a zip object, which is an iterator of tuples push_axis = [] # list that will contain useful for each axis for (axis, _list) in zip('xyz', zipped): # for x, y, and z axis calculate set of values and add them to list info = lambda: None info.max = max(_list) # the maximum value of bounds for each axis info.min = min(_list) # the minimum value of bounds for each axis info.distance = info.max - info.min # the length of the bounds for each axis info.mid = (info.max + info.min)/2 # the center point of bounds for each axis push_axis.append(info) # add this info to push_axis originals = dict(zip(['x', 'y', 'z'], push_axis)) # create dictionary wit the values from push_axis o_details = collections.namedtuple('object_details', ['x', 'y', 'z']) # organize dictionary to be accessed easier return o_details(**originals)
3,481
Python
47.36111
119
0.703533
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/scripts/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
858
Python
44.210524
74
0.7331
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/scripts/remesh.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # Remeshing reconstructs a mesh to produce clean/uniform geometry, but removes all UV mappings from an object # There are four different remesh methods. (BLOCKS, SMOOTH, SHARP, VOXEL) # https://docs.blender.org/manual/en/latest/modeling/modifiers/generate/remesh.html#remesh-modifier def remesh(objects, remesh_type, prop): modifier = 'REMESH' # sets type of modifier to be used for obj in objects: # for each object in selected objects, add the desired modifier and adjust its properties mod = obj.modifiers.new(name = modifier, type=modifier) # set name of modifier based on its type mod.mode = remesh_type # sets remesh type (BLOCKS, SMOOTH, SHARP, VOXEL) # first three modes produce almost identical typology, but with differing amounts of smoothing (BLOCKS, SMOOTH, SHARP) if remesh_type == 'BLOCKS': # "There is no smoothing at all." mod.octree_depth = prop # controls the resolution of most of the remesh modifiers. # the higher the number, the more geometry created (2^x) elif remesh_type == 'SMOOTH': # "Output a smooth surface." mod.octree_depth = prop # the higher the number, the more geometry created (2^x) elif remesh_type == 'SHARP': # "Similar to Smooth, but preserves sharp edges and corners." mod.octree_depth = prop # the higher the number, the more geometry created (2^x) elif remesh_type == 'VOXEL': # "Uses an OpenVDB to generate a new manifold mesh from the current geometry # while trying to preserve the mesh’s original volume." mod.voxel_size = prop # used for voxel remesh to control resolution. the lower the number, the more geometry created (x) else: raise TypeError('Invalid Remesh Type') return
2,657
Python
54.374999
132
0.703049
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/scripts/process_attributes.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. from bpy.types import Operator from . import modify, fix_mesh, chop, uv, utils class OPTIMIZE_OT_Scene(Operator): bl_idname = "optimize.scene" bl_label = "Optimize Scene" bl_description = "Optimize scene based on operation and set parameters" bl_options = {"REGISTER", "UNDO"} def execute(self, context): self.get_attributes(context) return {'FINISHED'} def get_attributes(self, context): optimizeOptions = context.scene.optimize_options modifyOptions = context.scene.modify_options uvOptions = context.scene.uv_options chopOptions = context.scene.chop_options if optimizeOptions.operation == "modify": attributes = dict( selected_only= modifyOptions.selected_only, apply_mod= modifyOptions.apply_mod, fix_bad_mesh = modifyOptions.fix_bad_mesh, dissolve_threshold = modifyOptions.dissolve_threshold, merge_vertex = modifyOptions.merge_vertex, merge_threshold = modifyOptions.merge_threshold, remove_existing_sharp = modifyOptions.remove_existing_sharp, fix_normals = modifyOptions.fix_normals, create_new_custom_normals = modifyOptions.create_new_custom_normals, modifier= modifyOptions.modifier, # use_modifier_stack= modifyOptions.use_modifier_stack, # modifier_stack= modifyOptions.modifier_stack, decimate_type= modifyOptions.decimate_type, ratio= modifyOptions.ratio, iterations= modifyOptions.iterations, angle= modifyOptions.angle, remesh_type= modifyOptions.remesh_type, oDepth= modifyOptions.oDepth, voxel_size= modifyOptions.voxel_size, geo_type= modifyOptions.geo_type, geo_attribute= modifyOptions.geo_attribute ) elif optimizeOptions.operation == "fixMesh": attributes = dict( selected_only=modifyOptions.selected_only, fix_bad_mesh = modifyOptions.fix_bad_mesh, dissolve_threshold = modifyOptions.dissolve_threshold, merge_vertex = modifyOptions.merge_vertex, merge_threshold = modifyOptions.merge_threshold, remove_existing_sharp = modifyOptions.remove_existing_sharp, fix_normals = modifyOptions.fix_normals, create_new_custom_normals = modifyOptions.create_new_custom_normals ) elif optimizeOptions.operation == "uv": attributes = dict( selected_only= uvOptions.selected_only, scale_to_bounds = uvOptions.scale_to_bounds, clip_to_bounds = uvOptions.clip_to_bounds, unwrap_type = uvOptions.unwrap_type, use_set_size = uvOptions.use_set_size, set_size = uvOptions.set_size, print_updated_results= uvOptions.print_updated_results ) elif optimizeOptions.operation == "chop": attributes = dict( merge= chopOptions.merge, cut_meshes= chopOptions.cut_meshes, max_vertices= chopOptions.max_vertices, min_box_size= chopOptions.min_box_size, max_depth= chopOptions.max_depth, print_updated_results= chopOptions.print_updated_results, create_bounds = chopOptions.create_bounds, selected_only = chopOptions.selected_only ) if optimizeOptions.print_attributes: print(attributes) self.process_operation(optimizeOptions.operation, attributes) def process_operation(self, operation, attributes): start = utils.start_time() blender_cmd = None if operation == 'modify': # Modify Scene blender_cmd = modify.Modify() elif operation == 'fixMesh': # Clean Scene blender_cmd = fix_mesh.FixMesh() elif operation == 'chop': # Chop Scene blender_cmd = chop.Chop() elif operation == 'uv': # Unwrap scene blender_cmd = uv.uvUnwrap() elif operation == "noop": # Runs the load/save USD round trip without modifying the scene. utils.do_print("No-op for this scene") return else: utils.do_print_error("Unknown operation: " + operation + " - add function call to process_file in process.py") return # Run the command if blender_cmd: blender_cmd.execute(attributes) else: utils.do_print_error("No Blender class found to run") utils.report_time(start, "operation")
5,736
Python
40.273381
122
0.61175
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/scripts/utils.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # Generic utility functions for Blender import json import sys from timeit import default_timer as timer import bpy def do_print(msg): # Flush so prints immediately. print("\033[93m" + msg + "\033[0m", flush=True) def do_print_error(msg): # Flush so prints immediately. print("\033[91m" + msg + "\033[0m", flush=True) def start_time(): return timer() def report_time(start, msg): end = timer() do_print("Elapsed time for {}: {:.3f}".format(msg, end-start)) def print_python_version(): do_print("Python version: %s.%s" % (sys.version_info.major, sys.version_info.minor)) def open_file(inputPath): start = timer() # Load scene. Clears any existing file before loading if inputPath.endswith(tuple([".usd", ".usda", ".usdc"])): do_print("Load file: " + inputPath) bpy.ops.wm.usd_import(filepath=inputPath) elif inputPath.endswith(".fbx"): bpy.ops.import_scene.fbx(filepath=inputPath) else: do_print_error("Unrecognized file, not loaded: " + inputPath) return False end = timer() do_print("Elapsed time to load file: " + "{:.3f}".format(end-start)) return True def save_file(outputPath): # Save scene. Only writes diffs, so faster than export. start = timer() do_print("Save file: " + outputPath) bpy.ops.wm.usd_export(filepath=outputPath) end = timer() do_print("Elapsed time to save file: " + "{:.3f}".format(end-start)) return True def clear_scene(): # This seems to be difficult with Blender. Partially working code: bpy.ops.wm.read_factory_settings(use_empty=True) def process_json_config(operation): return json.loads(operation) if operation else None def getVertexCount(occurrences): # returns the vertex count of all current occurrences for threshold testing during recursion vertexCount = 0 for obj in occurrences: vertexCount += len(obj.data.vertices) return vertexCount def getFaceCount(occurrences): # returns the face count of all current occurrences for threshold testing during recursion faceCount = 0 for obj in occurrences: faceCount += len(obj.data.polygons) return faceCount def printPart(part): print("current part being operated on: ", part.name) def printClearLine(): LINE_UP = '\033[1A' # command to move up a line in the console LINE_CLEAR = '\x1b[2K' # command to clear current line in the console print(LINE_UP, end=LINE_CLEAR) # don't want endless print statements
3,371
Python
33.408163
125
0.69119
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/scripts/select_mesh.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # for selecting only mesh objects in the scene. To be used by multiple other files. def setSelected(context, selectedOnly = False, deselectAll = True): def select(input): for obj in input: if obj.type == 'MESH': # only mesh objects, ignore lights/cameras/curves/etc. selected.append(obj) # add object to array if deselectAll: # may want all objects deselected at end of processing obj.select_set(False) # make sure all objects are deselected before continuing. else: obj.select_set(obj.type == 'MESH') # select only mesh objects selected = [] # an empty array that will be used to store the objects that need to be unwrapped objects=[ob for ob in context.view_layer.objects if ob.visible_get()] # only want to look at visible objects. process will fail otherwise if not selectedOnly: # selectedOnly is for GUI version only select(objects) elif len(context.selected_objects): # run only if there are selected objects in the scene to isolate just the selected meshes select(context.selected_objects) return selected
2,025
Python
46.116278
141
0.698765
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/scripts/blender_class.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. from abc import ABC, abstractmethod import json from . import utils class BlenderClass(ABC): def __init__(self): self._default_attributes = dict() def get_attributes(self, in_attributes): attributes = {**self._default_attributes, **in_attributes} # utils.do_print("Attributes: " + json.dumps(attributes, indent=4, sort_keys=False)) return attributes @abstractmethod def execute(self, in_attributes=None): pass
1,332
Python
32.324999
92
0.705706
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/scripts/decimate.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # Decimation reduces geometry while maintaining form and UVs # There are three different decimation methods. Each method produces different results, with its own pros/cons) # https://docs.blender.org/manual/en/latest/modeling/modifiers/generate/decimate.html#decimate-modifier def decimate(objects, decimate_type, prop): modifier = 'DECIMATE' # sets type of modifier to be used for obj in objects: # for each object in selected objects, add the desired modifier and adjust its properties if len(obj.data.polygons) > 3: # decimation cannot be performed on meshes with 3 or less faces mod = obj.modifiers.new(name = modifier, type=modifier) # set name of modifier based on its type mod.decimate_type = decimate_type # sets decimation type if decimate_type == 'COLLAPSE': # "Merges vertices together progressively, taking the shape of the mesh into account."" mod.ratio = prop # the ratio value used for collapse decimation. Is a ratio of total faces. (x/1) elif decimate_type == 'UNSUBDIV': # "It is intended for meshes with a mainly grid-based topology (without giving uneven geometry)" mod.iterations = prop # the number of un-subdivisions performed. The higher the number, the less geometry remaining (1/2^x) elif decimate_type == 'DISSOLVE': # "It reduces details on forms comprised of mainly flat surfaces." mod.angle_limit = prop # the reduction is limited to an angle between faces (x degrees) mod.delimit = {'UV'} else: raise TypeError('Invalid Decimate Type') return
2,515
Python
54.91111
142
0.702982
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/scripts/modify.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import bpy import time import math from . import blender_class, select_mesh, fix_mesh, decimate, remesh, geo_nodes, utils # Master Class for all modifiers class Modify(blender_class.BlenderClass): # settings for GUI version only bl_idname = "modify.scene" bl_label = "Modify Scene" bl_description = "Modify the scene based on set parameters" bl_options = {"REGISTER", "UNDO"} def __init__(self): self._default_attributes = dict( selected_only=True, # uses only objects selected in scene. For GUI version only apply_mod=True, # applies the generated modifiers. Should always be true for command line running fix_bad_mesh = True, # used to remove zero are faces and zero length edges based on the 'dissolve_threshold' dissolve_threshold = .08, # threshold value for 'fix_bad_mesh' merge_vertex = False, # merge connected and disconnected vertices of a mesh by a distance threshold merge_threshold = 0.01, # distance value to use for merge_vertex remove_existing_sharp = True, # when removing zero area faces, edge data can become messed up, causing bad normals. This helps minimize that. fix_normals = True, # optionally fix normals. useful for after 'fix_bad_mesh' to fix the normals as well. create_new_custom_normals = True, # useful for after 'fix_bad_mesh' to fix the normals as well. modifier= "DECIMATE", # determines which modifier type to use if 'use_modifier_stack' is False. (DECIMATE, REMESH, NODES, or SUBSURF) # Some common modifier names for reference:'DECIMATE''REMESH''NODES''SUBSURF''SOLIDIFY''ARRAY''BEVEL' use_modifier_stack= False, # allows use of more that one modifier sequentially. Useful for more specific customizable workflows. modifier_stack=[["DECIMATE", "COLLAPSE", 0.5]], # determines which modifier(s) to use if 'use_modifier_stack' is True.(DECIMATE, REMESH, NODES) # Modifiers are procedural adjustments to a mesh. The modifiers are stored in 'modifier_stack'. # Most modifiers have different options for calculation. for instance the 'DECIMATE' modifier options are stored in 'decimate_type' decimate_type="COLLAPSE", # the type of decimation being performed(COLLAPSE, UNSUBDIV, or DISSOLVE) # Each method produces different results, with its own pros/cons) # https://docs.google.com/document/d/1pkMZxgW4Xn_KJymFlKOo5XIkK2YleVYtyLJztTUTyAY/edit # COLLAPSE: "Merges vertices together progressively, taking the shape of the mesh into account."" # UNSUBDIV: "It is intended for meshes with a mainly grid-based topology (without giving uneven geometry)" # DISSOLVE: "It reduces details on forms comprised of mainly flat surfaces." ratio=0.5, # the ratio value used for collapse decimation. iterations=2, # the number of un-subdivisions performed angle=15.0, # attribute used when performing dissolve decimation. remesh_type="VOXEL", # the type of remesh being performed(BLOCKS, SMOOTH, SHARP, VOXEL) # remeshing removes all UV mappings from an object # https://docs.blender.org/manual/en/latest/modeling/modifiers/generate/remesh.html#remesh-modifier # first three modes produce almost identical typology, but with differing amounts of smoothing (BLOCKS, SMOOTH, SHARP) # BLOCKS: "There is no smoothing at all." # SMOOTH: "Output a smooth surface." # SHARP: "Similar to Smooth, but preserves sharp edges and corners." # VOXEL: "Uses an OpenVDB to generate a new manifold mesh from the current geometry while trying to preserve the mesh’s original volume." oDepth=4, # stands for octree depth and controls the resolution of most of the remesh modifiers voxel_size=0.1, # used for voxel remesh to control resolution geo_type="GeometryNodeBoundBox", # the type of geometry node tree to create: # (GeometryNodeConvexHull, GeometryNodeBoundBox, GeometryNodeSubdivisionSurface) # geometry nodes is currently under development, so feature set is not yet at a stage to be fully utilized # this puts in place a framework for more customizable and easily implementable optimizations in the future # more on geometry nodes: https://docs.blender.org/manual/en/latest/modeling/geometry_nodes/index.html#geometry-nodes geo_attribute=2 # a generic attribute variable that can be used for the different geo node types ) def execute(self, in_attributes=None): attributes = self.get_attributes(in_attributes) context = bpy.context then = time.time() # start time of script execution. # shorthands for multi-used attributes modifier = attributes["modifier"] decimate_type = attributes["decimate_type"] angle = attributes["angle"] remesh_type = attributes["remesh_type"] if context.mode != 'OBJECT': # must be in object mode to perform the rest of the operations. bpy.ops.object.mode_set(mode='OBJECT') # select objects selected = select_mesh.setSelected(context, attributes["selected_only"], deselectAll = False) if len(selected): # run only if there are selected mesh objects in the scene if attributes["fix_bad_mesh"]: # optionally fix bad meshes. Can also be done separately before hand fix_mesh.FixMesh.fixBadMesh( self, selected, attributes["dissolve_threshold"], attributes["fix_bad_mesh"], attributes["merge_vertex"], attributes["merge_threshold"], attributes["remove_existing_sharp"]) if attributes["fix_normals"]: # optionally fix bad normals (can often arise after fixing bad mesh) fix_mesh.FixMesh.fixNormals(self, selected, attributes["create_new_custom_normals"]) # for printing vertex and face data startingVerts = utils.getVertexCount(selected) startingFaces = utils.getFaceCount(selected) if attributes["use_modifier_stack"]: for mod in attributes["modifier_stack"]: self.run_modifier(selected, mod[0], mod[1], mod[2]) else: #Decimate if modifier == 'DECIMATE': sub_mod = decimate_type if decimate_type == 'COLLAPSE': prop = attributes["ratio"] elif decimate_type == 'UNSUBDIV': prop = attributes["iterations"] elif decimate_type == 'DISSOLVE': angle = math.radians(angle) # need to change angle to radians for the modifier prop = angle #Remesh elif modifier == 'REMESH': sub_mod = remesh_type if remesh_type == 'BLOCKS' or remesh_type == 'SMOOTH' or remesh_type == 'SHARP': prop = attributes["oDepth"] if remesh_type == 'VOXEL': prop = attributes["voxel_size"] #Geometry Nodes elif modifier == 'NODES': sub_mod = attributes["geo_type"] prop = attributes["geo_attribute"] else: sub_mod = None prop = None self.run_modifier(selected, modifier, sub_mod, prop) raise RuntimeError # apply modifiers once above loop is complete if attributes["apply_mod"]: context.view_layer.objects.active = selected[0] # need to set one of the selected objects as the active object # arbitrarily choosing to set the first object in selected_objects list. (there can only be one AO, but multiple SO) # this is necessary for the applying the modifiers. bpy.ops.object.convert(target='MESH') # applies all modifiers of each selected mesh. this preps the scene for proper export. # print vertex and face data endingVerts = utils.getVertexCount(selected) endingFaces = utils.getFaceCount(selected) vertsRemoved = startingVerts-endingVerts facesRemoved = startingFaces-endingFaces print("Modify Mesh Statistics:") utils.do_print("Starting Verts: " + str(startingVerts) + ", Ending Verts: " + str(endingVerts) + ", Verts Removed: " + str(vertsRemoved)) utils.do_print("Starting Faces: " + str(startingFaces) + ", Ending Faces: " + str(endingFaces) + ", Faces Removed: " + str(facesRemoved)) else: utils.do_print_error("NO MESH OBJECTS") now = time.time() # time after it finished. print("TIME FOR MODIFY: ", round(now-then, 3)) return {'FINISHED'} # "return {"FINISHED"} (or return{"CANCELED"}) is how Blender understands that an operator call is complete def run_modifier(self, objects, modifier, sub_mod = None, prop = None): # RUN BASED ON TYPE OF MODIFIER AND MODIFIER SUB_TYPE. Each modifier requires different input variables/values # Decimate if modifier == 'DECIMATE': decimate.decimate(objects, sub_mod, prop) # Remesh elif modifier == 'REMESH': remesh.remesh(objects, sub_mod, prop) # Geometry Nodes elif modifier == 'NODES': geo_nodes.geoNodes(objects, sub_mod, prop)
10,769
Python
58.175824
155
0.626613
NVIDIA-Omniverse/blender_omniverse_addons/omni_optimization_panel/scripts/uv.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import bpy import time import contextlib from . import blender_class, run_ops_wo_update, select_mesh, utils class uvUnwrap(blender_class.BlenderClass): # settings for GUI version only bl_idname = "uv.unwrap_batch" bl_label = "Batch UV Unwrap" bl_description = "batch uv unwrap objects" bl_options = {"REGISTER", "UNDO"} def __init__(self): self._default_attributes = dict( selected_only= False, # uses only objects selected in scene. For GUI version only scale_to_bounds = False, # determines if the unwrapped map gets scaled to the square uv image bounds clip_to_bounds = False, # if unwrapping exceeds bounds, it will be clipped off unwrap_type = 'Cube', # the method for unwrapping (cube, sphere, cylinder, or smart) use_set_size = False, # for cube and cylinder project, use specified projection size for all objects. # Overrides scale_to_bounds to False set_size = 2, # projection size for cube and cylinder project print_updated_results= True # print progress to console ) def execute(self, in_attributes=None): attributes = self.get_attributes(in_attributes) context = bpy.context then = time.time() # start time of script execution # blender operates in modes/contexts, and certain operations can only be performed in certain contexts if bpy.context.mode != 'OBJECT': # make sure context is object mode. bpy.ops.object.mode_set(mode='OBJECT') # if it is not, set it to object mode run_ops_wo_update.open_update() # allows for operators to be run without updating scene # important especially when working with loops self.unwrap(context, attributes) run_ops_wo_update.close_update() # must always call close_update if open_update is called now = time.time() # time after it finished print("TIME FOR UNWRAP: ", round(now-then, 3)) return {"FINISHED"} def unwrap(self, context, attributes): scaleBounds = attributes["scale_to_bounds"] clipBounds = attributes["clip_to_bounds"] unwrapType = attributes["unwrap_type"] use_set_size = attributes["use_set_size"] set_size = attributes["set_size"] print_updated_results = attributes["print_updated_results"] # select objects selected = select_mesh.setSelected(context, attributes["selected_only"], deselectAll = True) if len(selected): # run only if there are mesh objects in the 'selected' array LINE_UP = '\033[1A' # command to move up a line in the console LINE_CLEAR = '\x1b[2K' # command to clear current line in the console count = 0 # counter for which object is being calculated then = time.time() # start time of loop execution for object in selected: # unwrap each object separately object.select_set(True) # select object. This is now the only selected object context.view_layer.objects.active = object # set active object. Blender needs active object to be the selected object bpy.ops.object.mode_set(mode='EDIT') # make sure context is edit mode. Context switching is object dependent, must be after selection bpy.ops.mesh.select_all(action='SELECT') # select all mesh vertices. only selected vertices will be uv unwrapped # for smart UV projection if unwrapType == "Smart": # smart UV can take a long time, so this prints out a progress bar if count and print_updated_results: # if the first object has already been calculated and results should be printed with contextlib.redirect_stdout(None): # smartUV prints an output sometimes. We don't want/need this output this suppresses it self.smartUV(scaleBounds) # perform the uv unwrap now = time.time() # time after unwrapping is complete timeElapsed = now - then remaining = len(selected)-count # number of remaining objects timeLeft = timeElapsed/count * remaining # estimation of remaining time print(LINE_UP, end=LINE_CLEAR) # don't want endless print statements print(LINE_UP, end=LINE_CLEAR) # don't want endless print statements # so move up and clear the previously printed lines and overwrite them print("Object Count = ", count, " Objects Remaining = ", remaining) print(" Elapsed Time = ", round(timeElapsed,3), " Time Remaining = ", round(timeLeft,3)) # print results to console else: # if calculating the first object or not printing results self.smartUV(scaleBounds) # perform the uv unwrap if print_updated_results: print("Object Count = 0") print("Time Remaining = UNKOWN") # for cube projection elif unwrapType == "Cube": self.cubeUV(scaleBounds, clipBounds, use_set_size, set_size) # perform the uv unwrap # for sphere projection elif unwrapType == "Sphere": self.sphereUV(scaleBounds, clipBounds) # perform the uv unwrap # for cylinder projection elif unwrapType == "Cylinder": self.cylinderUV(scaleBounds, clipBounds, use_set_size, set_size) # perform the uv unwrap bpy.ops.object.mode_set(mode='OBJECT') # once complete, make sure context is object mode. # Must be in object mode to select the next object object.select_set(False) # deselect the current object. Now there are again no objects selected count += 1 # increase the object counter for obj in selected: # reselect all originally selected meshes obj.select_set(True) else: utils.do_print_error("NO MESH OBJECTS") return {'FINISHED'} # methods for running each type of uv projection def smartUV(self, scale): bpy.ops.uv.smart_project(correct_aspect=True, scale_to_bounds=scale) def cubeUV(self, scale, clip, use_set_size, size): if use_set_size: # user sets cube_size value of cube projection bpy.ops.uv.cube_project(scale_to_bounds=False, clip_to_bounds=clip, cube_size=size) else: bpy.ops.uv.cube_project(scale_to_bounds=scale, clip_to_bounds=clip) def sphereUV(self, scale, clip): bpy.ops.uv.sphere_project(direction='ALIGN_TO_OBJECT', scale_to_bounds=scale, clip_to_bounds=clip) # 'ALIGN_TO_OBJECT' sets the direction of the projection to be consistent regardless of view position/direction def cylinderUV(self, scale, clip, use_set_size, size): if use_set_size: # user sets radius value of cylinder projection bpy.ops.uv.cylinder_project(direction='ALIGN_TO_OBJECT', scale_to_bounds=False, clip_to_bounds=clip, radius=size) else: bpy.ops.uv.cylinder_project(direction='ALIGN_TO_OBJECT', scale_to_bounds=scale, clip_to_bounds=clip)
8,297
Python
52.192307
150
0.632277
NVIDIA-Omniverse/blender_omniverse_addons/omni/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. """ To invoke in Blender script editor: import bpy bpy.ops.universalmaterialmap.generator() bpy.ops.universalmaterialmap.converter() INFO_HT_header Header VIEW3D_HT_tool_header Info Header: INFO_HT_HEADER 3D View Header: VIEW3D_HT_HEADER Timeline Header: TIME_HT_HEADER Outliner Header: OUTLINER_HT_HEADER Properties Header: PROPERTIES_HT_HEADER, etc. """ """ Menu location problem https://blender.stackexchange.com/questions/3393/add-custom-menu-at-specific-location-in-the-header#:~:text=Blender%20has%20a%20built%20in,%3EPython%2D%3EUI%20Menu. """ bl_info = { 'name': 'Universal Material Map', 'author': 'NVIDIA Corporation', 'description': 'A Blender AddOn based on the Universal Material Map framework.', 'blender': (3, 1, 0), 'location': 'View3D', 'warning': '', 'category': 'Omniverse' } import sys import importlib import bpy from .universalmaterialmap.blender import developer_mode if developer_mode: print('UMM DEBUG: Initializing "{0}"'.format(__file__)) ordered_module_names = [ 'omni.universalmaterialmap', 'omni.universalmaterialmap.core', 'omni.universalmaterialmap.core.feature', 'omni.universalmaterialmap.core.singleton', 'omni.universalmaterialmap.core.data', 'omni.universalmaterialmap.core.util', 'omni.universalmaterialmap.core.operator', 'omni.universalmaterialmap.core.service', 'omni.universalmaterialmap.core.service.core', 'omni.universalmaterialmap.core.service.delegate', 'omni.universalmaterialmap.core.service.resources', 'omni.universalmaterialmap.core.service.store', 'omni.universalmaterialmap.core.converter', 'omni.universalmaterialmap.core.converter.core', 'omni.universalmaterialmap.core.converter.util', 'omni.universalmaterialmap.core.generator', 'omni.universalmaterialmap.core.generator.core', 'omni.universalmaterialmap.core.generator.util', 'omni.universalmaterialmap.blender', 'omni.universalmaterialmap.blender.menu', 'omni.universalmaterialmap.blender.converter', 'omni.universalmaterialmap.blender.generator', 'omni.universalmaterialmap.blender.material', ] for module_name in sys.modules: if 'omni.' not in module_name: continue if module_name not in ordered_module_names: raise Exception('Unexpected module name in sys.modules: {0}'.format(module_name)) for module_name in ordered_module_names: if module_name in sys.modules: print('UMM reloading: {0}'.format(module_name)) importlib.reload(sys.modules.get(module_name)) if developer_mode: from .universalmaterialmap.blender.converter import OT_InstanceToDataConverter, OT_DataToInstanceConverter, OT_DataToDataConverter, OT_ApplyDataToInstance, OT_DescribeShaderGraph from .universalmaterialmap.blender.converter import OT_CreateTemplateOmniPBR, OT_CreateTemplateOmniGlass from .universalmaterialmap.blender.menu import UniversalMaterialMapMenu from .universalmaterialmap.blender.generator import OT_Generator else: from .universalmaterialmap.blender.converter import OT_CreateTemplateOmniPBR, OT_CreateTemplateOmniGlass from .universalmaterialmap.blender.menu import UniversalMaterialMapMenu def draw_item(self, context): layout = self.layout layout.menu(UniversalMaterialMapMenu.bl_idname) def register(): bpy.utils.register_class(OT_CreateTemplateOmniPBR) bpy.utils.register_class(OT_CreateTemplateOmniGlass) if developer_mode: bpy.utils.register_class(OT_DataToInstanceConverter) bpy.utils.register_class(OT_DataToDataConverter) bpy.utils.register_class(OT_ApplyDataToInstance) bpy.utils.register_class(OT_InstanceToDataConverter) bpy.utils.register_class(OT_DescribeShaderGraph) bpy.utils.register_class(OT_Generator) bpy.utils.register_class(UniversalMaterialMapMenu) # lets add ourselves to the main header bpy.types.NODE_HT_header.append(draw_item) def unregister(): bpy.utils.unregister_class(OT_CreateTemplateOmniPBR) bpy.utils.unregister_class(OT_CreateTemplateOmniGlass) if developer_mode: bpy.utils.unregister_class(OT_DataToInstanceConverter) bpy.utils.unregister_class(OT_DataToDataConverter) bpy.utils.unregister_class(OT_ApplyDataToInstance) bpy.utils.unregister_class(OT_InstanceToDataConverter) bpy.utils.unregister_class(OT_DescribeShaderGraph) bpy.utils.unregister_class(OT_Generator) bpy.utils.unregister_class(UniversalMaterialMapMenu) bpy.types.NODE_HT_header.remove(draw_item) if __name__ == "__main__": register() # The menu can also be called from scripts # bpy.ops.wm.call_menu(name=UniversalMaterialMapMenu.bl_idname)
5,725
Python
35.471337
182
0.731528
NVIDIA-Omniverse/blender_omniverse_addons/omni/universalmaterialmap/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
858
Python
44.210524
74
0.7331
NVIDIA-Omniverse/blender_omniverse_addons/omni/universalmaterialmap/core/util.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import typing import sys from .data import Plug def to_plug_value_type(value: typing.Any, assumed_value_type: str) -> str: """Returns matching :class:`omni.universalmaterialmap.core.data.Plug` value type.""" if sys.version_info.major < 3: if isinstance(value, basestring): return Plug.VALUE_TYPE_STRING else: if isinstance(value, str): return Plug.VALUE_TYPE_STRING if type(value) == bool: return Plug.VALUE_TYPE_BOOLEAN if isinstance(value, int): return Plug.VALUE_TYPE_INTEGER if isinstance(value, float): return Plug.VALUE_TYPE_FLOAT try: test = iter(value) is_iterable = True except TypeError: is_iterable = False if is_iterable: if assumed_value_type == Plug.VALUE_TYPE_LIST: return Plug.VALUE_TYPE_LIST bum_booleans = 0 num_integers = 0 num_floats = 0 num_strings = 0 for o in value: if sys.version_info.major < 3: if isinstance(value, basestring): num_strings += 1 continue else: if isinstance(value, str): num_strings += 1 continue if type(o) == bool: bum_booleans += 1 continue if isinstance(o, int): num_integers += 1 continue if isinstance(o, float): num_floats += 1 if num_floats > 0: if len(value) == 2: return Plug.VALUE_TYPE_VECTOR2 if len(value) == 3: return Plug.VALUE_TYPE_VECTOR3 if len(value) == 4: return Plug.VALUE_TYPE_VECTOR4 if len(value) == 2 and assumed_value_type == Plug.VALUE_TYPE_VECTOR2: return assumed_value_type if len(value) == 3 and assumed_value_type == Plug.VALUE_TYPE_VECTOR3: return assumed_value_type if len(value) == 4 and assumed_value_type == Plug.VALUE_TYPE_VECTOR4: return assumed_value_type return Plug.VALUE_TYPE_LIST return Plug.VALUE_TYPE_ANY def get_extension_from_image_file_format(format:str, base_name:str) -> str: """ For image formats that have multiple possible extensions, determine if we should stick with the current format specifier or use the one from the filename itself. """ format = format.lower() split = base_name.rpartition(".")[-1] extension = split.lower() if len(split) else None if format == "open_exr": format = "exr" elif format == "jpeg": format = extension if extension in {"jpeg", "jpg"} else "jpg" elif format == "tiff": format = extension if extension in {"tiff", "tif"} else "tif" elif format == "targa_raw": format = "tga" return format
3,780
Python
31.042373
88
0.598677
NVIDIA-Omniverse/blender_omniverse_addons/omni/universalmaterialmap/core/extension.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. from . import *
876
Python
38.863635
74
0.729452
NVIDIA-Omniverse/blender_omniverse_addons/omni/universalmaterialmap/core/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
859
Python
41.999998
74
0.732247
NVIDIA-Omniverse/blender_omniverse_addons/omni/universalmaterialmap/core/data.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import typing import uuid import sys import importlib from .service.core import IDelegate class ChangeNotification(object): def __init__(self, item: object, property_name: str, old_value: typing.Any, new_value: typing.Any): super(ChangeNotification, self).__init__() self._item: object = item self._property_name: str = property_name self._old_value: typing.Any = old_value self._new_value: typing.Any = new_value @property def item(self) -> object: """ """ return self._item @property def property_name(self) -> str: """ """ return self._property_name @property def old_value(self) -> typing.Any: """ """ return self._old_value @property def new_value(self) -> typing.Any: """ """ return self._new_value class Notifying(object): """Base class providing change notification capability""" def __init__(self): super(Notifying, self).__init__() self._changed_callbacks: typing.Dict[uuid.uuid4, typing.Callable[[ChangeNotification], typing.NoReturn]] = dict() def add_changed_fn(self, callback: typing.Callable[[ChangeNotification], typing.NoReturn]) -> uuid.uuid4: for key, value in self._changed_callbacks.items(): if value == callback: return key key = uuid.uuid4() self._changed_callbacks[key] = callback return key def remove_changed_fn(self, callback_id: uuid.uuid4) -> None: if callback_id in self._changed_callbacks.keys(): del self._changed_callbacks[callback_id] def _notify(self, notification: ChangeNotification): for callback in self._changed_callbacks.values(): callback(notification) def destroy(self): self._changed_callbacks = None class Subscribing(Notifying): def __init__(self): super(Subscribing, self).__init__() self._subscriptions: typing.Dict[Notifying, uuid.uuid4] = dict() def _subscribe(self, notifying: Notifying) -> uuid.uuid4: if notifying in self._subscriptions.keys(): return self._subscriptions[notifying] self._subscriptions[notifying] = notifying.add_changed_fn(self._on_notification) def _unsubscribe(self, notifying: Notifying) -> None: if notifying in self._subscriptions.keys(): callback_id = self._subscriptions[notifying] del self._subscriptions[notifying] notifying.remove_changed_fn(callback_id=callback_id) def _on_notification(self, notification: ChangeNotification) -> None: pass class ManagedListInsert(object): def __init__(self, notifying: Notifying, index: int): super(ManagedListInsert, self).__init__() self._notifying: Notifying = notifying self._index: int = index @property def notifying(self) -> Notifying: """ """ return self._notifying @property def index(self) -> int: """ """ return self._index class ManagedListRemove(object): def __init__(self, notifying: Notifying, index: int): super(ManagedListRemove, self).__init__() self._notifying: Notifying = notifying self._index: int = index @property def notifying(self) -> Notifying: """ """ return self._notifying @property def index(self) -> int: """ """ return self._index class ManagedListNotification(object): ADDED_ITEMS: int = 0 UPDATED_ITEMS: int = 1 REMOVED_ITEMS: int = 2 def __init__(self, managed_list: 'ManagedList', items: typing.List[typing.Union[ManagedListInsert, ChangeNotification, ManagedListRemove]]): super(ManagedListNotification, self).__init__() self._managed_list: ManagedList = managed_list self._inserted_items: typing.List[ManagedListInsert] = [] self._change_notifications: typing.List[ChangeNotification] = [] self._removed_items: typing.List[ManagedListRemove] = [] self._kind: int = -1 if isinstance(items[0], ManagedListInsert): self._kind = ManagedListNotification.ADDED_ITEMS self._inserted_items = typing.cast(typing.List[ManagedListInsert], items) elif isinstance(items[0], ChangeNotification): self._kind = ManagedListNotification.UPDATED_ITEMS self._change_notifications = typing.cast(typing.List[ChangeNotification], items) elif isinstance(items[0], ManagedListRemove): self._kind = ManagedListNotification.REMOVED_ITEMS self._removed_items = typing.cast(typing.List[ManagedListRemove], items) else: raise Exception('Unexpected object: "{0}" of type "{1}".'.format(items[0], type(items[0]))) @property def managed_list(self) -> 'ManagedList': """ """ return self._managed_list @property def kind(self) -> int: """ """ return self._kind @property def inserted_items(self) -> typing.List[ManagedListInsert]: """ """ return self._inserted_items @property def change_notifications(self) -> typing.List[ChangeNotification]: """ """ return self._change_notifications @property def removed_items(self) -> typing.List[ManagedListRemove]: """ """ return self._removed_items class ManagedList(object): def __init__(self, items: typing.List[Notifying] = None): super(ManagedList, self).__init__() self._subscriptions: typing.Dict[Notifying, uuid.uuid4] = dict() self._changed_callbacks: typing.Dict[uuid.uuid4, typing.Callable[[ManagedListNotification], typing.NoReturn]] = dict() self._managed_items: typing.List[Notifying] = [] if items: for o in items: self._manage_item(notifying=o) def __iter__(self): return iter(self._managed_items) def _manage_item(self, notifying: Notifying) -> typing.Union[Notifying, None]: """ Subscribes to managed item. Returns item only if it became managed. """ if notifying in self._managed_items: return None self._managed_items.append(notifying) self._subscriptions[notifying] = notifying.add_changed_fn(self._on_notification) return notifying def _unmanage_item(self, notifying: Notifying) -> typing.Union[typing.Tuple[Notifying, int], typing.Tuple[None, int]]: """ Unsubscribes to managed item. Returns item only if it became unmanaged. """ if notifying not in self._managed_items: return None, -1 index = self._managed_items.index(notifying) self._managed_items.remove(notifying) callback_id = self._subscriptions[notifying] del self._subscriptions[notifying] notifying.remove_changed_fn(callback_id=callback_id) return notifying, index def _on_notification(self, notification: ChangeNotification) -> None: self._notify( notification=ManagedListNotification( managed_list=self, items=[notification] ) ) def _notify(self, notification: ManagedListNotification): for callback in self._changed_callbacks.values(): callback(notification) def add_changed_fn(self, callback: typing.Callable[[ManagedListNotification], typing.NoReturn]) -> uuid.uuid4: for key, value in self._changed_callbacks.items(): if value == callback: return key key = uuid.uuid4() self._changed_callbacks[key] = callback return key def remove_changed_fn(self, callback_id: uuid.uuid4) -> None: if callback_id in self._changed_callbacks.keys(): del self._changed_callbacks[callback_id] def append(self, notifying: Notifying) -> None: if self._manage_item(notifying=notifying) is not None: self._notify( ManagedListNotification( managed_list=self, items=[ManagedListInsert(notifying=notifying, index=self.index(notifying=notifying))] ) ) def extend(self, notifying: typing.List[Notifying]) -> None: added = [] for o in notifying: o = self._manage_item(notifying=o) if o: added.append(o) if len(added) == 0: return self._notify( ManagedListNotification( managed_list=self, items=[ManagedListInsert(notifying=o, index=self.index(notifying=o)) for o in added] ) ) def remove(self, notifying: Notifying) -> None: notifying, index = self._unmanage_item(notifying=notifying) if notifying: self._notify( ManagedListNotification( managed_list=self, items=[ManagedListRemove(notifying=notifying, index=index)] ) ) def remove_all(self) -> None: items = [ManagedListRemove(notifying=o, index=i) for i, o in enumerate(self._managed_items)] for callback_id, notifying in self._subscriptions.items(): notifying.remove_changed_fn(callback_id=callback_id) self._subscriptions = dict() self._managed_items = [] self._notify( ManagedListNotification( managed_list=self, items=items ) ) def pop(self, index: int = 0) -> Notifying: notifying, index = self._unmanage_item(self._managed_items[index]) self._notify( ManagedListNotification( managed_list=self, items=[ManagedListRemove(notifying=notifying, index=index)] ) ) return notifying def index(self, notifying: Notifying) -> int: if notifying in self._managed_items: return self._managed_items.index(notifying) return -1 class Serializable(Subscribing): """Base class providing serialization method template""" def __init__(self): super(Serializable, self).__init__() def serialize(self) -> dict: """ """ return dict() def deserialize(self, data: dict) -> None: """ """ pass class Base(Serializable): """Base class providing id property""" @classmethod def Create(cls) -> 'Base': return cls() def __init__(self): super(Base, self).__init__() self._id: str = str(uuid.uuid4()) def serialize(self) -> dict: """ """ output = super(Base, self).serialize() output['_id'] = self._id return output def deserialize(self, data: dict) -> None: """ """ super(Base, self).deserialize(data=data) self._id = data['_id'] if '_id' in data.keys() else str(uuid.uuid4()) @property def id(self) -> str: """ """ return self._id class DagNode(Base): """Base class providing input and outputs of :class:`omni.universalmaterialmap.core.data.Plug` """ def __init__(self): super(DagNode, self).__init__() self._inputs: typing.List[Plug] = [] self._outputs: typing.List[Plug] = [] self._computing: bool = False def serialize(self) -> dict: """ """ output = super(DagNode, self).serialize() output['_inputs'] = [plug.serialize() for plug in self.inputs] output['_outputs'] = [plug.serialize() for plug in self.outputs] return output def deserialize(self, data: dict) -> None: """ """ super(DagNode, self).deserialize(data=data) old_inputs = self._inputs[:] old_outputs = self._outputs[:] while len(self._inputs): self._unsubscribe(notifying=self._inputs.pop()) while len(self._outputs): self._unsubscribe(notifying=self._outputs.pop()) plugs = [] if '_inputs' in data.keys(): for o in data['_inputs']: plug = Plug(parent=self) plug.deserialize(data=o) plugs.append(plug) self._inputs = plugs plugs = [] if '_outputs' in data.keys(): for o in data['_outputs']: plug = Plug(parent=self) plug.deserialize(data=o) plugs.append(plug) self._outputs = plugs for o in self._inputs: self._subscribe(notifying=o) for o in self._outputs: self._subscribe(notifying=o) if not old_inputs == self._inputs: self._notify( ChangeNotification( item=self, property_name='inputs', old_value=old_inputs, new_value=self._inputs[:] ) ) if not old_inputs == self._outputs: self._notify( ChangeNotification( item=self, property_name='outputs', old_value=old_outputs, new_value=self._outputs[:] ) ) def _on_notification(self, notification: ChangeNotification) -> None: if notification.item == self: return # Re-broadcast notification self._notify(notification=notification) def invalidate(self, plug: 'Plug'): pass def compute(self) -> None: """ """ if self._computing: return self._computing = True self._compute_inputs(input_plugs=self._inputs) self._compute_outputs(output_plugs=self._outputs) self._computing = False def _compute_inputs(self, input_plugs: typing.List['Plug']): # Compute dependencies for plug in input_plugs: if not plug.input: continue if not plug.input.parent: continue if not plug.input.is_invalid: continue plug.input.parent.compute() # Set computed_value for plug in input_plugs: if plug.input: plug.computed_value = plug.input.computed_value else: plug.computed_value = plug.value def _compute_outputs(self, output_plugs: typing.List['Plug']): # Compute dependencies for plug in output_plugs: if not plug.input: continue if not plug.input.parent: continue if not plug.input.is_invalid: continue plug.input.parent.compute() # Set computed_value for plug in output_plugs: if plug.input: plug.computed_value = plug.input.computed_value else: plug.computed_value = plug.value def add_input(self) -> 'Plug': raise NotImplementedError() def can_remove_plug(self, plug: 'Plug') -> bool: return plug.is_removable def remove_plug(self, plug: 'Plug') -> None: if not plug.is_removable: raise Exception('Plug is not removable') notifications = [] if plug in self._inputs: old_value = self._inputs[:] self._unsubscribe(notifying=plug) self._inputs.remove(plug) notifications.append( ChangeNotification( item=self, property_name='inputs', old_value=old_value, new_value=self._inputs[:] ) ) if plug in self._outputs: old_value = self._outputs[:] self._unsubscribe(notifying=plug) self._outputs.remove(plug) notifications.append( ChangeNotification( item=self, property_name='outputs', old_value=old_value, new_value=self._outputs[:] ) ) destination: Plug for destination in plug.outputs: destination.input = None for notification in notifications: self._notify(notification=notification) @property def can_add_input(self) -> bool: return False @property def inputs(self) -> typing.List['Plug']: """ """ return self._inputs @property def outputs(self) -> typing.List['Plug']: """ """ return self._outputs class GraphEntity(DagNode): """Base class providing omni.kit.widget.graph properties for a data item.""" OPEN = 0 MINIMIZED = 1 CLOSED = 2 def __init__(self): super(GraphEntity, self).__init__() self._display_name: str = '' self._position: typing.Union[typing.Tuple[float, float], None] = None self._expansion_state: int = GraphEntity.OPEN self._show_inputs: bool = True self._show_outputs: bool = True self._show_peripheral: bool = False def serialize(self) -> dict: """ """ output = super(GraphEntity, self).serialize() output['_display_name'] = self._display_name output['_position'] = self._position output['_expansion_state'] = self._expansion_state output['_show_inputs'] = self._show_inputs output['_show_outputs'] = self._show_outputs output['_show_peripheral'] = self._show_peripheral return output def deserialize(self, data: dict) -> None: """ """ super(GraphEntity, self).deserialize(data=data) self._display_name = data['_display_name'] if '_display_name' in data.keys() else '' self._position = data['_position'] if '_position' in data.keys() else None self._expansion_state = data['_expansion_state'] if '_expansion_state' in data.keys() else GraphEntity.OPEN self._show_inputs = data['_show_inputs'] if '_show_inputs' in data.keys() else True self._show_outputs = data['_show_outputs'] if '_show_outputs' in data.keys() else True self._show_peripheral = data['_show_peripheral'] if '_show_peripheral' in data.keys() else False @property def display_name(self) -> str: """ """ return self._display_name @display_name.setter def display_name(self, value: str) -> None: """ """ if self._display_name is value: return notification = ChangeNotification( item=self, property_name='display_name', old_value=self._display_name, new_value=value ) self._display_name = value self._notify(notification=notification) @property def position(self) -> typing.Union[typing.Tuple[float, float], None]: """ """ return self._position @position.setter def position(self, value: typing.Union[typing.Tuple[float, float], None]) -> None: """ """ if self._position is value: return notification = ChangeNotification( item=self, property_name='position', old_value=self._position, new_value=value ) self._position = value self._notify(notification=notification) @property def expansion_state(self) -> int: """ """ return self._expansion_state @expansion_state.setter def expansion_state(self, value: int) -> None: """ """ if self._expansion_state is value: return notification = ChangeNotification( item=self, property_name='expansion_state', old_value=self._expansion_state, new_value=value ) self._expansion_state = value self._notify(notification=notification) @property def show_inputs(self) -> bool: """ """ return self._show_inputs @show_inputs.setter def show_inputs(self, value: bool) -> None: """ """ if self._show_inputs is value: return notification = ChangeNotification( item=self, property_name='show_inputs', old_value=self._show_inputs, new_value=value ) self._show_inputs = value self._notify(notification=notification) @property def show_outputs(self) -> bool: """ """ return self._show_outputs @show_outputs.setter def show_outputs(self, value: bool) -> None: """ """ if self._show_outputs is value: return notification = ChangeNotification( item=self, property_name='show_outputs', old_value=self._show_outputs, new_value=value ) self._show_outputs = value self._notify(notification=notification) @property def show_peripheral(self) -> bool: """ """ return self._show_peripheral @show_peripheral.setter def show_peripheral(self, value: bool) -> None: """ """ if self._show_peripheral is value: return notification = ChangeNotification( item=self, property_name='show_peripheral', old_value=self._show_peripheral, new_value=value ) self._show_peripheral = value self._notify(notification=notification) class Connection(Serializable): def __init__(self): super(Connection, self).__init__() self._source_id = '' self._destination_id = '' def serialize(self) -> dict: output = super(Connection, self).serialize() output['_source_id'] = self._source_id output['_destination_id'] = self._destination_id return output def deserialize(self, data: dict) -> None: super(Connection, self).deserialize(data=data) self._source_id = data['_source_id'] if '_source_id' in data.keys() else '' self._destination_id = data['_destination_id'] if '_destination_id' in data.keys() else '' @property def source_id(self): return self._source_id @property def destination_id(self): return self._destination_id class Plug(Base): """ A Plug can be: a source an output both a source and an output a container for a static value - most likely as an output a container for an editable value - most likely as an output plug.default_value Starting point and for resetting. plug.value Apply as computed_value if there is no input or dependency providing a value. plug.computed_value Final value. Could be thought of as plug.output_value. Plug is_dirty on input connect input disconnect value change if not connected A Plug is_dirty if it is_dirty its input is_dirty any dependency is_dirty """ VALUE_TYPE_ANY = 'any' VALUE_TYPE_FLOAT = 'float' VALUE_TYPE_INTEGER = 'int' VALUE_TYPE_STRING = 'str' VALUE_TYPE_BOOLEAN = 'bool' VALUE_TYPE_NODE_ID = 'node_id' VALUE_TYPE_VECTOR2 = 'vector2' VALUE_TYPE_VECTOR3 = 'vector3' VALUE_TYPE_VECTOR4 = 'vector4' VALUE_TYPE_ENUM = 'enum' VALUE_TYPE_LIST = 'list' VALUE_TYPES = [ VALUE_TYPE_ANY, VALUE_TYPE_FLOAT, VALUE_TYPE_INTEGER, VALUE_TYPE_STRING, VALUE_TYPE_BOOLEAN, VALUE_TYPE_NODE_ID, VALUE_TYPE_VECTOR2, VALUE_TYPE_VECTOR3, VALUE_TYPE_VECTOR4, VALUE_TYPE_ENUM, VALUE_TYPE_LIST, ] @classmethod def Create( cls, parent: DagNode, name: str, display_name: str, value_type: str = 'any', editable: bool = False, is_removable: bool = False, ) -> 'Plug': instance = cls(parent=parent) instance._name = name instance._display_name = display_name instance._value_type = value_type instance._is_editable = editable instance._is_removable = is_removable return instance def __init__(self, parent: DagNode): super(Plug, self).__init__() self._parent: DagNode = parent self._name: str = '' self._display_name: str = '' self._value_type: str = Plug.VALUE_TYPE_ANY self._internal_value_type: str = Plug.VALUE_TYPE_ANY self._is_peripheral: bool = False self._is_editable: bool = False self._is_removable: bool = False self._default_value: typing.Any = None self._computed_value: typing.Any = None self._value: typing.Any = None self._is_invalid: bool = False self._input: typing.Union[Plug, typing.NoReturn] = None self._outputs: typing.List[Plug] = [] self._enum_values: typing.List = [] def serialize(self) -> dict: output = super(Plug, self).serialize() output['_name'] = self._name output['_display_name'] = self._display_name output['_value_type'] = self._value_type output['_internal_value_type'] = self._internal_value_type output['_is_peripheral'] = self._is_peripheral output['_is_editable'] = self._is_editable output['_is_removable'] = self._is_removable output['_default_value'] = self._default_value output['_value'] = self._value output['_enum_values'] = self._enum_values return output def deserialize(self, data: dict) -> None: super(Plug, self).deserialize(data=data) self._input = None self._name = data['_name'] if '_name' in data.keys() else '' self._display_name = data['_display_name'] if '_display_name' in data.keys() else '' self._value_type = data['_value_type'] if '_value_type' in data.keys() else Plug.VALUE_TYPE_ANY self._internal_value_type = data['_internal_value_type'] if '_internal_value_type' in data.keys() else None self._is_peripheral = data['_is_peripheral'] if '_is_peripheral' in data.keys() else False self._is_editable = data['_is_editable'] if '_is_editable' in data.keys() else False self._is_removable = data['_is_removable'] if '_is_removable' in data.keys() else False self._default_value = data['_default_value'] if '_default_value' in data.keys() else None self._value = data['_value'] if '_value' in data.keys() else self._default_value self._enum_values = data['_enum_values'] if '_enum_values' in data.keys() else [] def invalidate(self) -> None: if self._is_invalid: return self._is_invalid = True if self.parent: self.parent.invalidate(self) @property def parent(self) -> DagNode: return self._parent @property def name(self) -> str: return self._name @name.setter def name(self, value: str) -> None: if self._name is value: return notification = ChangeNotification( item=self, property_name='name', old_value=self._name, new_value=value ) self._name = value self._notify(notification=notification) @property def display_name(self) -> str: return self._display_name @display_name.setter def display_name(self, value: str) -> None: if self._display_name is value: return notification = ChangeNotification( item=self, property_name='display_name', old_value=self._display_name, new_value=value ) self._display_name = value self._notify(notification=notification) @property def value_type(self) -> str: return self._value_type @value_type.setter def value_type(self, value: str) -> None: if self._value_type is value: return notification = ChangeNotification( item=self, property_name='value_type', old_value=self._value_type, new_value=value ) self._value_type = value self._notify(notification=notification) @property def internal_value_type(self) -> str: return self._internal_value_type @internal_value_type.setter def internal_value_type(self, value: str) -> None: if self._internal_value_type is value: return notification = ChangeNotification( item=self, property_name='internal_value_type', old_value=self._internal_value_type, new_value=value ) self._internal_value_type = value self._notify(notification=notification) @property def is_removable(self) -> bool: return self._is_removable @property def is_peripheral(self) -> bool: return self._is_peripheral @is_peripheral.setter def is_peripheral(self, value: bool) -> None: if self._is_peripheral is value: return notification = ChangeNotification( item=self, property_name='is_peripheral', old_value=self._is_peripheral, new_value=value ) self._is_peripheral = value self._notify(notification=notification) @property def computed_value(self) -> typing.Any: return self._computed_value @computed_value.setter def computed_value(self, value: typing.Any) -> None: if self._computed_value is value: self._is_invalid = False self._value = self._computed_value return notification = ChangeNotification( item=self, property_name='computed_value', old_value=self._computed_value, new_value=value ) if self._input and self._input.is_invalid: print('WARNING: Universal Material Map: Compute encountered an unexpected state: input invalid after compute. Results may be incorrect.') print('\tplug: "{0}"'.format(self.name)) if self._parent: print('\tplug.parent: "{0}"'.format(self._parent.__class__.__name__)) print('\tplug.input: "{0}"'.format(self._input.name)) if self._input.parent: print('\tplug.input.parent: "{0}"'.format(self._input.parent.__class__.__name__)) return self._is_invalid = False self._computed_value = value self._value = self._computed_value self._notify(notification=notification) @property def value(self) -> typing.Any: return self._value @value.setter def value(self, value: typing.Any) -> None: if self._value is value: return notification = ChangeNotification( item=self, property_name='value', old_value=self._value, new_value=value ) self._value = value self._notify(notification=notification) if self._input is None: self.invalidate() @property def is_invalid(self) -> typing.Any: if self._input and self._input._is_invalid: return True return self._is_invalid @property def input(self) -> typing.Union['Plug', typing.NoReturn]: return self._input @input.setter def input(self, value: typing.Union['Plug', typing.NoReturn]) -> None: if self._input is value: return notification = ChangeNotification( item=self, property_name='input', old_value=self._input, new_value=value ) self._input = value self._notify(notification=notification) self.invalidate() @property def outputs(self) -> typing.List['Plug']: return self._outputs @property def is_editable(self) -> bool: return self._is_editable @is_editable.setter def is_editable(self, value: bool) -> None: if self._is_editable is value: return notification = ChangeNotification( item=self, property_name='is_editable', old_value=self._is_editable, new_value=value ) self._is_editable = value self._notify(notification=notification) @property def default_value(self) -> typing.Any: return self._default_value @default_value.setter def default_value(self, value: typing.Any) -> None: if self._default_value is value: return notification = ChangeNotification( item=self, property_name='default_value', old_value=self._default_value, new_value=value ) self._default_value = value self._notify(notification=notification) @property def enum_values(self) -> typing.List: return self._enum_values @enum_values.setter def enum_values(self, value: typing.List) -> None: if self._enum_values is value: return notification = ChangeNotification( item=self, property_name='enum_values', old_value=self._enum_values, new_value=value ) self._enum_values = value self._notify(notification=notification) class Node(DagNode): @classmethod def Create(cls, class_name: str) -> 'Node': instance = typing.cast(Node, super(Node, cls).Create()) instance._class_name = class_name return instance def __init__(self): super(Node, self).__init__() self._class_name: str = '' def serialize(self) -> dict: output = super(Node, self).serialize() output['_class_name'] = self._class_name return output def deserialize(self, data: dict) -> None: super(Node, self).deserialize(data=data) self._class_name = data['_class_name'] if '_class_name' in data.keys() else '' @property def class_name(self): return self._class_name class Client(Serializable): ANY_VERSION = 'any' NO_VERSION = 'none' DCC_OMNIVERSE_CREATE = 'Omniverse Create' DCC_3DS_MAX = '3ds MAX' DCC_MAYA = 'Maya' DCC_HOUDINI = 'Houdini' DCC_SUBSTANCE_DESIGNER = 'Substance Designer' DCC_SUBSTANCE_PAINTER = 'Substance Painter' DCC_BLENDER = 'Blender' @classmethod def Autodesk_3dsMax(cls, version: str = ANY_VERSION) -> 'Client': instance = Client() instance._name = Client.DCC_3DS_MAX instance._version = version return instance @classmethod def Autodesk_Maya(cls, version: str = ANY_VERSION) -> 'Client': instance = Client() instance._name = Client.DCC_MAYA instance._version = version return instance @classmethod def OmniverseCreate(cls, version: str = ANY_VERSION) -> 'Client': instance = Client() instance._name = Client.DCC_OMNIVERSE_CREATE instance._version = version return instance @classmethod def Blender(cls, version: str = ANY_VERSION) -> 'Client': instance = Client() instance._name = Client.DCC_BLENDER instance._version = version return instance def __init__(self): super(Client, self).__init__() self._name: str = '' self._version: str = '' def __eq__(self, other: 'Client') -> bool: if not isinstance(other, Client): return False return other.name == self._name and other.version == self._version def is_compatible(self, other: 'Client') -> bool: if not isinstance(other, Client): return False if other == self: return True return other._version == Client.ANY_VERSION or self._version == Client.ANY_VERSION def serialize(self) -> dict: output = super(Client, self).serialize() output['_name'] = self._name output['_version'] = self._version return output def deserialize(self, data: dict) -> None: super(Client, self).deserialize(data=data) self._name = data['_name'] if '_name' in data.keys() else '' self._version = data['_version'] if '_version' in data.keys() else '' @property def name(self) -> str: return self._name @name.setter def name(self, value: str) -> None: self._name = value @property def version(self) -> str: return self._version @version.setter def version(self, value: str) -> None: self._version = value class AssemblyMetadata(Serializable): CATEGORY_BASE = 'Base Materials' CATEGORY_CONNECTOR = 'Connector Materials' CATEGORIES = [ CATEGORY_BASE, CATEGORY_CONNECTOR, ] def __init__(self): super(AssemblyMetadata, self).__init__() self._category = '' self._name = '' self._keywords: typing.List[str] = [] self._supported_clients: typing.List[Client] = [] def serialize(self) -> dict: output = super(AssemblyMetadata, self).serialize() output['_category'] = self._category output['_name'] = self._name output['_keywords'] = self._keywords output['_supported_clients'] = [o.serialize() for o in self._supported_clients] return output def deserialize(self, data: dict) -> None: super(AssemblyMetadata, self).deserialize(data=data) self._category = data['_category'] if '_category' in data.keys() else '' self._name = data['_name'] if '_name' in data.keys() else '' self._keywords = data['_keywords'] if '_keywords' in data.keys() else '' items = [] if '_supported_clients' in data.keys(): for o in data['_supported_clients']: item = Client() item.deserialize(data=o) items.append(item) self._supported_clients = items @property def category(self) -> str: return self._category @category.setter def category(self, value: str) -> None: self._category = value @property def name(self) -> str: return self._name @name.setter def name(self, value: str) -> None: self._name = value @property def keywords(self) -> typing.List[str]: return self._keywords @keywords.setter def keywords(self, value: typing.List[str]) -> None: self._keywords = value @property def supported_clients(self) -> typing.List[Client]: return self._supported_clients class Target(GraphEntity): def __init__(self): super(Target, self).__init__() self._nodes: typing.List[Node] = [] self._metadata: AssemblyMetadata = AssemblyMetadata() self._root_node_id: str = '' self._root_node: Node = None self._revision: int = 0 self._store_id: str = '' self._connections: typing.List[Connection] = [] def serialize(self) -> dict: output = super(Target, self).serialize() output['_nodes'] = [node.serialize() for node in self.nodes] output['_metadata'] = self._metadata.serialize() output['_root_node_id'] = self._root_node_id output['_revision'] = self._revision output['_connections'] = [o.serialize() for o in self._connections] return output def deserialize(self, data: dict) -> None: super(Target, self).deserialize(data=data) self._root_node_id = data['_root_node_id'] if '_root_node_id' in data.keys() else '' nodes = [] if '_nodes' in data.keys(): for o in data['_nodes']: node = Node() node.deserialize(data=o) nodes.append(node) self._nodes = nodes root_node = None if self._root_node_id: for node in self._nodes: if node.id == self._root_node_id: root_node = node break self._root_node = root_node metadata = AssemblyMetadata() if '_metadata' in data.keys(): metadata.deserialize(data=data['_metadata']) self._metadata = metadata self._revision = data['_revision'] if '_revision' in data.keys() else 0 items = [] if '_connections' in data.keys(): for o in data['_connections']: item = Connection() item.deserialize(data=o) items.append(item) self._connections = items for connection in self._connections: input_plug: Plug = None output_plug: Plug = None for node in self._nodes: for plug in node.inputs: if connection.source_id == plug.id: input_plug = plug elif connection.destination_id == plug.id: input_plug = plug for plug in node.outputs: if connection.source_id == plug.id: output_plug = plug elif connection.destination_id == plug.id: output_plug = plug if input_plug is not None and output_plug is not None: break if input_plug is None or output_plug is None: continue if output_plug not in input_plug.outputs: input_plug.outputs.append(output_plug) output_plug.input = input_plug def connect(self, source: Plug, destination: Plug) -> None: for connection in self._connections: if connection.source_id == source.id and connection.destination_id == destination.id: return connection = Connection() connection._source_id = source.id connection._destination_id = destination.id self._connections.append(connection) if destination not in source.outputs: source.outputs.append(destination) destination.input = source @property def nodes(self) -> typing.List[Node]: return self._nodes @property def metadata(self) -> AssemblyMetadata: return self._metadata @property def root_node(self) -> Node: return self._root_node @root_node.setter def root_node(self, value: Node) -> None: self._root_node = value self._root_node_id = self._root_node.id if self._root_node else '' @property def revision(self) -> int: return self._revision @revision.setter def revision(self, value: int) -> None: self._revision = value @property def store_id(self) -> str: return self._store_id @store_id.setter def store_id(self, value: int) -> None: if self._store_id is value: return notification = ChangeNotification( item=self, property_name='store_id', old_value=self._store_id, new_value=value ) self._store_id = value self._notify(notification=notification) class TargetInstance(GraphEntity): @classmethod def FromAssembly(cls, assembly: Target) -> 'TargetInstance': instance = cls() instance._target_id = assembly.id instance.target = assembly instance.display_name = assembly.display_name return instance def __init__(self): super(TargetInstance, self).__init__() self._target_id: str = '' self._target: typing.Union[Target, typing.NoReturn] = None self._is_setting_target = False def serialize(self) -> dict: super(TargetInstance, self).serialize() output = GraphEntity.serialize(self) output['_target_id'] = self._target_id output['_inputs'] = [] output['_outputs'] = [] return output def deserialize(self, data: dict) -> None: """ Does not invoke super on DagNode base class because inputs and outputs are derived from assembly instance. """ data['_inputs'] = [] data['_outputs'] = [] GraphEntity.deserialize(self, data=data) self._target_id = data['_target_id'] if '_target_id' in data.keys() else '' def invalidate(self, plug: 'Plug' = None): """ Invalidate any plug that is a destination of an output plug named plug.name. """ # If a destination is invalidated it is assumed compute will be invoked once a destination endpoint has been found do_compute = True output: Plug destination: Plug for output in self.outputs: if not plug or output.name == plug.name: for destination in output.outputs: destination.invalidate() do_compute = False if do_compute: self.compute() @property def target_id(self) -> str: return self._target_id @property def target(self) -> typing.Union[Target, typing.NoReturn]: return self._target @target.setter def target(self, value: typing.Union[Target, typing.NoReturn]) -> None: if self._target is value: return if not self._target_id and value: raise Exception('Target ID "" does not match assembly instance "{0}".'.format(value.id)) if self._target_id and not value: raise Exception('Target ID "{0}" does not match assembly instance "None".'.format(self._target_id)) if self._target_id and value and not self._target_id == value.id: raise Exception('Target ID "{0}" does not match assembly instance "{1}".'.format(self._target_id, value.id)) self._is_setting_target = True notification = ChangeNotification( item=self, property_name='target', old_value=self._target, new_value=value ) self._target = value self._inputs = [] self._outputs = [] if self._target: node_id_plug = Plug.Create( parent=self, name='node_id_output', display_name='Node Id', value_type=Plug.VALUE_TYPE_STRING ) node_id_plug._id = self._target.id node_id_plug.value = self._target.id self._outputs.append(node_id_plug) for node in self._target.nodes: for o in node.inputs: plug = Plug(parent=self) plug.deserialize(data=o.serialize()) self._inputs.append(plug) for o in node.outputs: plug = Plug(parent=self) plug.deserialize(data=o.serialize()) self._outputs.append(plug) self._is_setting_target = False self._notify(notification=notification) self.invalidate() class Operator(Base): def __init__( self, id: str, name: str, required_inputs: int, min_inputs: int, max_inputs: int, num_outputs: int, ): super(Operator, self).__init__() self._id = id self._name: str = name self._required_inputs: int = required_inputs self._min_inputs: int = min_inputs self._max_inputs: int = max_inputs self._num_outputs: int = num_outputs self._computing: bool = False def compute(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): """ Base class only computes input_plugs. It is assumed that extending class computes output plugs. """ if self._computing: return self._computing = True if len(input_plugs) < self._required_inputs: raise Exception('Array of inputs not of required length "{0}". Actual length "{1}". Operator: "{2}"'.format(self._required_inputs, len(input_plugs), self.__class__.__name__)) for plug in input_plugs: if plug.input: if plug.input in input_plugs: print('WARNING: Universal Material Map: Invalid state in compute graph. Compute cancelled.') print('\tInput {0}.{1} is dependent on another input on the same node.'.format(plug.parent.display_name, plug.name)) print('\tDependency: {0}.{1}'.format(plug.input.parent.display_name, plug.input.name)) print('\tThis is not supported.') print('\tComputations likely to not behave as expected. It is recommended you restart the solution using this data.') self._computing = False return if plug.input in output_plugs: print('WARNING: Universal Material Map: Invalid state in compute graph. Compute cancelled.') print('\tInput {0}.{1} is dependent on another output on the same node.'.format( plug.parent.display_name, plug.name)) print('\tDependency: {0}.{1}'.format(plug.input.parent.display_name, plug.input.name)) print('\tThis is not supported.') print('\tComputations likely to not behave as expected. It is recommended you restart the solution using this data.') self._computing = False return for plug in output_plugs: if plug.input: if plug.input in output_plugs: print('WARNING: Universal Material Map: Invalid state in compute graph. Compute cancelled.') print('\tInput {0}.{1} is dependent on another output on the same node.'.format( plug.parent.display_name, plug.name)) print('\tDependency: {0}.{1}'.format(plug.input.parent.display_name, plug.input.name)) print('\tThis is not supported.') print('\tComputations likely to not behave as expected. It is recommended you restart the solution using this data.') self._computing = False return self._compute_inputs(input_plugs=input_plugs) self._compute_outputs(input_plugs=input_plugs, output_plugs=output_plugs) self._computing = False def _compute_inputs(self, input_plugs: typing.List[Plug]): # Compute dependencies for plug in input_plugs: if not plug.input: continue if not plug.input.parent: continue if not plug.input.is_invalid: continue plug.input.parent.compute() # Set computed_value for plug in input_plugs: if plug.input: plug.computed_value = plug.input.computed_value else: plug.computed_value = plug.value def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): raise NotImplementedError(self.__class__) def generate_input(self, parent: 'DagNode', index: int) -> Plug: """ Base class provides method template but does nothing. """ pass def generate_output(self, parent: 'DagNode', index: int) -> Plug: """ Base class provides method template but does nothing. """ pass def test(self) -> None: parent = OperatorInstance() inputs = [] while len(inputs) < self.min_inputs: inputs.append( self.generate_input(parent=parent, index=len(inputs)) ) outputs = [] while len(outputs) < self.num_outputs: outputs.append( self.generate_output(parent=parent, index=len(outputs)) ) self._prepare_plugs_for_test(input_plugs=inputs, output_plugs=outputs) self._perform_test(input_plugs=inputs, output_plugs=outputs) self._assert_test(input_plugs=inputs, output_plugs=outputs) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): pass def _perform_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): self.compute(input_plugs=input_plugs, output_plugs=output_plugs) def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): raise NotImplementedError() def remove_plug(self, operator_instance: 'OperatorInstance', plug: 'Plug') -> None: if not plug.is_removable: raise Exception('Plug is not removable') notifications = [] if plug in operator_instance._inputs: old_value = operator_instance._inputs[:] operator_instance._inputs.remove(plug) operator_instance._unsubscribe(notifying=plug) notifications.append( ChangeNotification( item=operator_instance, property_name='inputs', old_value=old_value, new_value=operator_instance._inputs[:] ) ) if plug in operator_instance._outputs: old_value = operator_instance._outputs[:] operator_instance._outputs.remove(plug) operator_instance._unsubscribe(notifying=plug) notifications.append( ChangeNotification( item=operator_instance, property_name='outputs', old_value=old_value, new_value=operator_instance._outputs[:] ) ) destination: Plug for destination in plug.outputs: destination.input = None for notification in notifications: for callback in operator_instance._changed_callbacks.values(): callback(notification) @property def name(self) -> str: return self._name @property def min_inputs(self) -> int: return self._min_inputs @property def max_inputs(self) -> int: return self._max_inputs @property def required_inputs(self) -> int: return self._required_inputs @property def num_outputs(self) -> int: return self._num_outputs class GraphOutput(Operator): """ Output resolves to a node id. """ def __init__(self): super(GraphOutput, self).__init__( id='5f39ab48-5bee-46fe-9a22-0f678013568e', name='Graph Output', required_inputs=1, min_inputs=1, max_inputs=1, num_outputs=1 ) def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='input_node_id', display_name='Node Id', value_type=Plug.VALUE_TYPE_NODE_ID) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='output_node_id', display_name='Node Id', value_type=Plug.VALUE_TYPE_NODE_ID) raise Exception('Output index "{0}" not supported.'.format(index)) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].computed_value = input_plugs[0].computed_value def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): input_plugs[0].computed_value = self.id def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): for output in output_plugs: if not output.computed_value == self.id: raise Exception('Test failed.') class OperatorInstance(GraphEntity): @classmethod def FromOperator(cls, operator: Operator) -> 'OperatorInstance': instance = OperatorInstance() instance._is_deserializing = True instance._operator = operator instance._display_name = operator.name while len(instance._inputs) < operator.min_inputs: instance._inputs.append( operator.generate_input(parent=instance, index=len(instance._inputs)) ) while len(instance._outputs) < operator.num_outputs: instance._outputs.append( operator.generate_output(parent=instance, index=len(instance._outputs)) ) instance._operator_module = operator.__class__.__module__ instance._operator_class_name = operator.__class__.__name__ instance._is_deserializing = False instance.invalidate() return instance def __init__(self): super(OperatorInstance, self).__init__() self._description: str = '' self._operator_module: str = '' self._operator_class_name: str = '' self._operator: Operator = None self._is_deserializing = False def serialize(self) -> dict: output = super(OperatorInstance, self).serialize() output['_description'] = self._description output['_operator_module'] = self._operator_module output['_operator_class_name'] = self._operator_class_name return output def deserialize(self, data: dict) -> None: self._is_deserializing = True super(OperatorInstance, self).deserialize(data=data) self._description = data['_description'] if '_description' in data.keys() else '' self._operator_module = data['_operator_module'] if '_operator_module' in data.keys() else '' self._operator_class_name = data['_operator_class_name'] if '_operator_class_name' in data.keys() else '' if not self._operator_module: raise Exception('Unexpected data: no valid "operator module" defined') if not self._operator_class_name: raise Exception('Unexpected data: no valid "operator class name" defined') if self._operator_module not in sys.modules.keys(): importlib.import_module(self._operator_module) module_pointer = sys.modules[self._operator_module] class_pointer = module_pointer.__dict__[self._operator_class_name] self._operator = typing.cast(Operator, class_pointer()) notifying = [] while len(self._inputs) < self._operator.min_inputs: plug = self._operator.generate_input(parent=self, index=len(self._inputs)) self._inputs.append(plug) notifying.append(plug) while len(self._outputs) < self._operator.num_outputs: plug = self._operator.generate_output(parent=self, index=len(self._outputs)) self._outputs.append(plug) notifying.append(plug) self._is_deserializing = False for o in notifying: self._subscribe(notifying=o) self.invalidate() def invalidate(self, plug: 'Plug' = None): """ Because one plug changed we assume any connected plug to any output needs to be invalidated. """ if self._is_deserializing: return # Set all outputs to invalid output: Plug for output in self.outputs: output._is_invalid = True # If a destination is invalidated it is assumed compute will be invoked once a destination endpoint has been found do_compute = True destination: Plug for output in self.outputs: for destination in output.outputs: destination.invalidate() do_compute = False if do_compute: self.compute() def compute(self) -> None: if self._operator: self._operator.compute(input_plugs=self._inputs, output_plugs=self._outputs) def add_input(self) -> Plug: if not self.can_add_input: raise Exception('Cannot add another input.') old_value = self._inputs[:] plug = self._operator.generate_input(parent=self, index=len(self._inputs)) self._inputs.append(plug) self._subscribe(notifying=plug) notification = ChangeNotification( item=self, property_name='inputs', old_value=old_value, new_value=self._inputs[:] ) self._notify(notification=notification) for o in self.outputs: o.invalidate() return plug def remove_plug(self, plug: 'Plug') -> None: self._operator.remove_plug(operator_instance=self, plug=plug) @property def operator(self) -> Operator: return self._operator @property def description(self) -> str: return self._description @description.setter def description(self, value: str) -> None: if self._description is value: return notification = ChangeNotification( item=self, property_name='description', old_value=self._description, new_value=value ) self._description = value self._notify(notification=notification) @DagNode.can_add_input.getter def can_add_input(self) -> bool: if self._operator.max_inputs == -1: return True return len(self._inputs) < self._operator.max_inputs - 1 class StyleInfo(object): def __init__( self, name: str, background_color: int, border_color: int, connection_color: int, node_background_color: int, footer_icon_filename: str, ): super(StyleInfo, self).__init__() self._name: str = name self._background_color: int = background_color self._border_color: int = border_color self._connection_color: int = connection_color self._node_background_color: int = node_background_color self._footer_icon_filename: str = footer_icon_filename @property def name(self) -> str: return self._name @property def background_color(self) -> int: return self._background_color @property def border_color(self) -> int: return self._border_color @property def connection_color(self) -> int: return self._connection_color @property def node_background_color(self) -> int: return self._node_background_color @property def footer_icon_filename(self) -> str: return self._footer_icon_filename class ConversionGraph(Base): # STYLE_OUTPUT: StyleInfo = StyleInfo( # name='output', # background_color=0xFF2E2E2E, # border_color=0xFFB97E9C, # connection_color=0xFF80C26F, # node_background_color=0xFF444444, # footer_icon_filename='Material.svg' # ) STYLE_SOURCE_NODE: StyleInfo = StyleInfo( name='source_node', background_color=0xFF2E2E2E, border_color=0xFFE5AAC8, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='Material.svg' ) STYLE_ASSEMBLY_REFERENCE: StyleInfo = StyleInfo( name='assembly_reference', background_color=0xFF2E2E2E, border_color=0xFFB97E9C, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='Material.svg' ) STYLE_OPERATOR_INSTANCE: StyleInfo = StyleInfo( name='operator_instance', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='constant_color.svg' ) STYLE_VALUE_RESOLVER: StyleInfo = StyleInfo( name='value_resolver', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='value_resolver.svg' ) STYLE_BOOLEAN_SWITCH: StyleInfo = StyleInfo( name='boolean_switch', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='boolean_switch.svg' ) STYLE_CONSTANT_BOOLEAN: StyleInfo = StyleInfo( name='constant_boolean', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='constant_boolean.svg' ) STYLE_CONSTANT_COLOR: StyleInfo = StyleInfo( name='constant_color', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='constant_color.svg' ) STYLE_CONSTANT_FLOAT: StyleInfo = StyleInfo( name='constant_float', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='constant_float.svg' ) STYLE_CONSTANT_INTEGER: StyleInfo = StyleInfo( name='constant_integer', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='constant_integer.svg' ) STYLE_CONSTANT_STRING: StyleInfo = StyleInfo( name='constant_string', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='constant_string.svg' ) STYLE_EQUAL: StyleInfo = StyleInfo( name='equal', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='equal.svg' ) STYLE_GREATER_THAN: StyleInfo = StyleInfo( name='greater_than', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='greater_than.svg' ) STYLE_LESS_THAN: StyleInfo = StyleInfo( name='less_than', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='less_than.svg' ) STYLE_MERGE_RGB: StyleInfo = StyleInfo( name='merge_rgb', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='merge_rgb.svg' ) STYLE_NOT: StyleInfo = StyleInfo( name='not', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='not.svg' ) STYLE_OR: StyleInfo = StyleInfo( name='or', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='or.svg' ) STYLE_SPLIT_RGB: StyleInfo = StyleInfo( name='split_rgb', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='split_rgb.svg' ) STYLE_TRANSPARENCY_RESOLVER: StyleInfo = StyleInfo( name='transparency_resolver', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='transparency_resolver.svg' ) STYLE_OUTPUT: StyleInfo = StyleInfo( name='output', background_color=0xFF34302A, border_color=0xFFCD923A, connection_color=0xFF80C26F, node_background_color=0xFF444444, footer_icon_filename='output.svg' ) STYLE_INFOS = ( STYLE_OUTPUT, STYLE_SOURCE_NODE, STYLE_ASSEMBLY_REFERENCE, STYLE_OPERATOR_INSTANCE, STYLE_VALUE_RESOLVER, STYLE_BOOLEAN_SWITCH, STYLE_CONSTANT_BOOLEAN, STYLE_CONSTANT_COLOR, STYLE_CONSTANT_FLOAT, STYLE_CONSTANT_INTEGER, STYLE_CONSTANT_STRING, STYLE_EQUAL, STYLE_GREATER_THAN, STYLE_LESS_THAN, STYLE_NOT, STYLE_OR, STYLE_SPLIT_RGB, STYLE_TRANSPARENCY_RESOLVER, STYLE_MERGE_RGB, ) def __init__(self): super(ConversionGraph, self).__init__() self._graph_output: OperatorInstance = OperatorInstance.FromOperator(operator=GraphOutput()) self._target_instances: typing.List[TargetInstance] = [] self._operator_instances: typing.List[OperatorInstance] = [self._graph_output] self._connections: typing.List[Connection] = [] self._library: Library = None self._source_node_id: str = '' self._source_node: TargetInstance = None self._filename: str = '' self._exists_on_disk: bool = False self._revision: int = 0 def _on_notification(self, notification: ChangeNotification) -> None: if notification.item == self: return # Re-broadcast notification self._notify(notification=notification) def serialize(self) -> dict: output = super(ConversionGraph, self).serialize() output['_target_instances'] = [o.serialize() for o in self._target_instances] output['_operator_instances'] = [o.serialize() for o in self._operator_instances] output['_connections'] = [o.serialize() for o in self._connections] output['_source_node_id'] = self._source_node_id output['_revision'] = self._revision return output def deserialize(self, data: dict) -> None: super(ConversionGraph, self).deserialize(data=data) notifications = [] # _source_node_id old = self._source_node_id new = data['_source_node_id'] if '_source_node_id' in data.keys() else '' if not old == new: self._source_node_id = new notifications.append( ChangeNotification( item=self, property_name='source_node_id', old_value=old, new_value=new ) ) # _revision old = self._revision new = data['_revision'] if '_revision' in data.keys() else 0 if not old == new: self._revision = new notifications.append( ChangeNotification( item=self, property_name='revision', old_value=old, new_value=new ) ) # _target_instances old = self._target_instances[:] while len(self._target_instances): self._unsubscribe(notifying=self._target_instances.pop()) items = [] if '_target_instances' in data.keys(): for o in data['_target_instances']: item = TargetInstance() item.deserialize(data=o) items.append(item) self._target_instances = items if not self._target_instances == old: notifications.append( ChangeNotification( item=self, property_name='target_instances', old_value=old, new_value=self._target_instances ) ) # _source_node old = self._source_node source_node = None if self._source_node_id: items = [o for o in self._target_instances if o.id == self._source_node_id] source_node = items[0] if len(items) else None self._source_node = source_node if not self._source_node == old: notifications.append( ChangeNotification( item=self, property_name='source_node', old_value=old, new_value=self._source_node ) ) # _operator_instances # _graph_output old_operator_instances = self._operator_instances old_graph_output = self._graph_output items = [] self._graph_output = None if '_operator_instances' in data.keys(): for o in data['_operator_instances']: item = OperatorInstance() item.deserialize(data=o) items.append(item) if isinstance(item.operator, GraphOutput): self._graph_output = item if not self._graph_output: self._graph_output = OperatorInstance.FromOperator(operator=GraphOutput()) items.insert(0, self._graph_output) self._operator_instances = items if not self._operator_instances == old_operator_instances: notifications.append( ChangeNotification( item=self, property_name='operator_instances', old_value=old_operator_instances, new_value=self._operator_instances ) ) if not self._graph_output == old_graph_output: notifications.append( ChangeNotification( item=self, property_name='old_graph_output', old_value=old_operator_instances, new_value=self._graph_output ) ) items = [] if '_connections' in data.keys(): for o in data['_connections']: item = Connection() item.deserialize(data=o) items.append(item) self._connections = items for o in self._target_instances: self._subscribe(notifying=o) for o in self._operator_instances: self._subscribe(notifying=o) for o in notifications: self._notify(notification=o) def build_dag(self) -> None: for connection in self._connections: source = self._get_plug(plug_id=connection.source_id) destination = self._get_plug(plug_id=connection.destination_id) if not source or not destination: continue if destination not in source.outputs: source.outputs.append(destination) destination.input = source def _get_plug(self, plug_id: str) -> typing.Union[Plug, typing.NoReturn]: for assembly_reference in self._target_instances: for plug in assembly_reference.inputs: if plug.id == plug_id: return plug for plug in assembly_reference.outputs: if plug.id == plug_id: return plug for operator_instance in self._operator_instances: for plug in operator_instance.outputs: if plug.id == plug_id: return plug for plug in operator_instance.inputs: if plug.id == plug_id: return plug return None def add_node(self, node: OperatorInstance) -> None: self._operator_instances.append(node) def add_connection(self, source: Plug, destination: Plug) -> None: connection = Connection() connection._source_id = source.id connection._destination_id = destination.id self._connections.append(connection) if destination not in source.outputs: source.outputs.append(destination) destination.input = source def add(self, entity: GraphEntity) -> None: if isinstance(entity, TargetInstance): if entity in self._target_instances: return self._target_instances.append(entity) self._subscribe(notifying=entity) return if isinstance(entity, OperatorInstance): if entity in self._operator_instances: return self._operator_instances.append(entity) self._subscribe(notifying=entity) return raise NotImplementedError() def can_be_removed(self, entity: GraphEntity) -> bool: if not entity: return False if entity not in self._target_instances and entity not in self._operator_instances: return False if entity == self._graph_output: return False return True def remove(self, entity: GraphEntity) -> None: if not self.can_be_removed(entity=entity): raise Exception('Not allowed: entity is not allowed to be deleted.') if isinstance(entity, TargetInstance): if entity in self._target_instances: self._unsubscribe(notifying=entity) self._target_instances.remove(entity) to_remove = [] for connection in self._connections: if connection.source_id == entity.id or connection.destination_id == entity.id: to_remove.append(connection) for connection in to_remove: self.remove_connection(connection=connection) return if isinstance(entity, OperatorInstance): if entity in self._operator_instances: self._unsubscribe(notifying=entity) self._operator_instances.remove(entity) to_remove = [] for connection in self._connections: if connection.source_id == entity.id or connection.destination_id == entity.id: to_remove.append(connection) for connection in to_remove: self.remove_connection(connection=connection) return raise NotImplementedError() def remove_connection(self, connection: Connection) -> None: if connection in self._connections: self._connections.remove(connection) source = self._get_plug(plug_id=connection.source_id) destination = self._get_plug(plug_id=connection.destination_id) if source and destination: if destination in source.outputs: source.outputs.remove(destination) if destination.input == source: destination.input = None def get_entity_by_id(self, identifier: str) -> typing.Union[GraphEntity, typing.NoReturn]: entities = [entity for entity in self._target_instances if entity.id == identifier] if len(entities): return entities[0] entities = [entity for entity in self._operator_instances if entity.id == identifier] if len(entities): return entities[0] return None def get_output_entity(self) -> typing.Union[TargetInstance, typing.NoReturn]: """ Computes the dependency graph and returns the resulting Target reference. Make sure relevant source node plug values have been set prior to invoking this method. """ if not self._graph_output: return None self._graph_output.invalidate() assembly_id = self._graph_output.outputs[0].computed_value for item in self._target_instances: if item.target_id == assembly_id: return item return None def get_object_style_name(self, entity: GraphEntity) -> str: if not entity: return '' # TODO: Style computed output entity # if entity == self.get_output_entity(): # return ConversionGraph.STYLE_OUTPUT.name if entity == self.source_node: return ConversionGraph.STYLE_SOURCE_NODE.name if isinstance(entity, TargetInstance): return ConversionGraph.STYLE_ASSEMBLY_REFERENCE.name if isinstance(entity, OperatorInstance): if entity.operator: if entity.operator.__class__.__name__ == 'ConstantBoolean': return ConversionGraph.STYLE_CONSTANT_BOOLEAN.name if entity.operator.__class__.__name__ == 'ConstantColor': return ConversionGraph.STYLE_CONSTANT_COLOR.name if entity.operator.__class__.__name__ == 'ConstantFloat': return ConversionGraph.STYLE_CONSTANT_FLOAT.name if entity.operator.__class__.__name__ == 'ConstantInteger': return ConversionGraph.STYLE_CONSTANT_INTEGER.name if entity.operator.__class__.__name__ == 'ConstantString': return ConversionGraph.STYLE_CONSTANT_STRING.name if entity.operator.__class__.__name__ == 'BooleanSwitch': return ConversionGraph.STYLE_BOOLEAN_SWITCH.name if entity.operator.__class__.__name__ == 'ValueResolver': return ConversionGraph.STYLE_VALUE_RESOLVER.name if entity.operator.__class__.__name__ == 'SplitRGB': return ConversionGraph.STYLE_SPLIT_RGB.name if entity.operator.__class__.__name__ == 'MergeRGB': return ConversionGraph.STYLE_MERGE_RGB.name if entity.operator.__class__.__name__ == 'LessThan': return ConversionGraph.STYLE_LESS_THAN.name if entity.operator.__class__.__name__ == 'GreaterThan': return ConversionGraph.STYLE_GREATER_THAN.name if entity.operator.__class__.__name__ == 'Or': return ConversionGraph.STYLE_OR.name if entity.operator.__class__.__name__ == 'Equal': return ConversionGraph.STYLE_EQUAL.name if entity.operator.__class__.__name__ == 'Not': return ConversionGraph.STYLE_NOT.name if entity.operator.__class__.__name__ == 'MayaTransparencyResolver': return ConversionGraph.STYLE_TRANSPARENCY_RESOLVER.name if entity.operator.__class__.__name__ == 'GraphOutput': return ConversionGraph.STYLE_OUTPUT.name return ConversionGraph.STYLE_OPERATOR_INSTANCE.name return '' def get_output_targets(self) -> typing.List[TargetInstance]: return [o for o in self._target_instances if not o == self._source_node] @property def target_instances(self) -> typing.List[TargetInstance]: return self._target_instances[:] @property def operator_instances(self) -> typing.List[OperatorInstance]: return self._operator_instances[:] @property def connections(self) -> typing.List[Connection]: return self._connections[:] @property def filename(self) -> str: return self._filename @filename.setter def filename(self, value: str) -> None: if self._filename is value: return notification = ChangeNotification( item=self, property_name='filename', old_value=self._filename, new_value=value ) self._filename = value self._notify(notification=notification) @property def library(self) -> 'Library': return self._library @property def graph_output(self) -> OperatorInstance: return self._graph_output @property def source_node(self) -> TargetInstance: return self._source_node @source_node.setter def source_node(self, value: TargetInstance) -> None: if self._source_node is value: return node_notification = ChangeNotification( item=self, property_name='source_node', old_value=self._source_node, new_value=value ) node_id_notification = ChangeNotification( item=self, property_name='source_node_id', old_value=self._source_node_id, new_value=value.id if value else '' ) self._source_node = value self._source_node_id = self._source_node.id if self._source_node else '' self._notify(notification=node_notification) self._notify(notification=node_id_notification) @property def exists_on_disk(self) -> bool: return self._exists_on_disk @property def revision(self) -> int: return self._revision @revision.setter def revision(self, value: int) -> None: if self._revision is value: return notification = ChangeNotification( item=self, property_name='revision', old_value=self._revision, new_value=value ) self._revision = value self._notify(notification=notification) class FileHeader(Serializable): @classmethod def FromInstance(cls, instance: Serializable) -> 'FileHeader': header = cls() header._module = instance.__class__.__module__ header._class_name = instance.__class__.__name__ return header @classmethod def FromData(cls, data: dict) -> 'FileHeader': if '_module' not in data.keys(): raise Exception('Unexpected data: key "_module" not in dictionary') if '_class_name' not in data.keys(): raise Exception('Unexpected data: key "_class_name" not in dictionary') header = cls() header._module = data['_module'] header._class_name = data['_class_name'] return header def __init__(self): super(FileHeader, self).__init__() self._module = '' self._class_name = '' def serialize(self) -> dict: output = dict() output['_module'] = self._module output['_class_name'] = self._class_name return output @property def module(self) -> str: return self._module @property def class_name(self) -> str: return self._class_name class FileUtility(Serializable): @classmethod def FromInstance(cls, instance: Serializable) -> 'FileUtility': utility = cls() utility._header = FileHeader.FromInstance(instance=instance) utility._content = instance return utility @classmethod def FromData(cls, data: dict) -> 'FileUtility': if '_header' not in data.keys(): raise Exception('Unexpected data: key "_header" not in dictionary') if '_content' not in data.keys(): raise Exception('Unexpected data: key "_content" not in dictionary') utility = cls() utility._header = FileHeader.FromData(data=data['_header']) if utility._header.module not in sys.modules.keys(): importlib.import_module(utility._header.module) module_pointer = sys.modules[utility._header.module] class_pointer = module_pointer.__dict__[utility._header.class_name] utility._content = class_pointer() if isinstance(utility._content, Serializable): utility._content.deserialize(data=data['_content']) return utility def __init__(self): super(FileUtility, self).__init__() self._header: FileHeader = None self._content: Serializable = None def serialize(self) -> dict: output = dict() output['_header'] = self._header.serialize() output['_content'] = self._content.serialize() return output def assert_content_serializable(self): data = self.content.serialize() self._assert(data=data) def _assert(self, data: dict): for key, value in data.items(): if isinstance(value, dict): self._assert(data=value) elif isinstance(value, list): for item in value: if isinstance(item, dict): self._assert(data=item) else: print(item) else: print(key, value) @property def header(self) -> FileHeader: return self._header @property def content(self) -> Serializable: return self._content class Library(Base): """ A Library represents a UMM data set. It can contain any of the following types of files: - Settings - Conversion Graph - Target - Conversion Manifest A Library is divided into a "core" and a "user" data set. "core": - Files provided by NVIDIA. - Installed and updated by UMM. - Adding, editing, and deleting files require running in "Developer Mode". - Types: - Conversion Graph - Target - Conversion Manifest "user" - Files created and updated by user. - Types: - Conversion Graph - Target - Conversion Manifest Overrides ./core/Conversion Manifest ...or... each file header has an attribute: source = core, source = user if source == core then it is read-only to users. TARGET: problem with that is what if user needs to update an existing target? ...why would they? ...because they may want to edit property states in the Target... would want their own. CONVERSION GRAPH ...they could just Save As and make a different one. no problem here. do need to change the 'source' attribute to 'user' though. CONVERSION MANIFEST 2 files ConversionManifest.json ConversionManifest_user.json (overrides ConversionManifest.json) Limitation: User cannot all together remove a manifest item """ @classmethod def Create( cls, library_id: str, name: str, manifest: IDelegate = None, conversion_graph: IDelegate = None, target: IDelegate = None, settings: IDelegate = None ) -> 'Library': instance = typing.cast(Library, super(Library, cls).Create()) instance._id = library_id instance._name = name instance._manifest = manifest instance._conversion_graph = conversion_graph instance._target = target instance._settings = settings return instance def __init__(self): super(Library, self).__init__() self._name: str = '' self._manifest: typing.Union[IDelegate, typing.NoReturn] = None self._conversion_graph: typing.Union[IDelegate, typing.NoReturn] = None self._target: typing.Union[IDelegate, typing.NoReturn] = None self._settings: typing.Union[IDelegate, typing.NoReturn] = None def serialize(self) -> dict: output = super(Library, self).serialize() output['_name'] = self._name return output def deserialize(self, data: dict) -> None: super(Library, self).deserialize(data=data) self._name = data['_name'] if '_name' in data.keys() else '' @property def name(self) -> str: return self._name @name.setter def name(self, value: str) -> None: self._name = value @property def manifest(self) -> typing.Union[IDelegate, typing.NoReturn]: return self._manifest @property def conversion_graph(self) -> typing.Union[IDelegate, typing.NoReturn]: return self._conversion_graph @property def target(self) -> typing.Union[IDelegate, typing.NoReturn]: return self._target @property def settings(self) -> typing.Union[IDelegate, typing.NoReturn]: return self._settings @property def is_read_only(self) -> bool: return not self._conversion_graph or not self._target or not self._conversion_graph class Settings(Serializable): def __init__(self): super(Settings, self).__init__() self._libraries: typing.List[Library] = [] self._store_id = 'Settings.json' self._render_contexts: typing.List[str] = [] def serialize(self) -> dict: output = super(Settings, self).serialize() output['_libraries'] = [o.serialize() for o in self._libraries] output['_render_contexts'] = self._render_contexts return output def deserialize(self, data: dict) -> None: super(Settings, self).deserialize(data=data) items = [] if '_libraries' in data.keys(): for o in data['_libraries']: item = Library() item.deserialize(data=o) items.append(item) self._libraries = items self._render_contexts = data['_render_contexts'] if '_render_contexts' in data.keys() else [] @property def libraries(self) -> typing.List[Library]: return self._libraries @property def store_id(self) -> str: return self._store_id @property def render_contexts(self) -> typing.List[str]: return self._render_contexts class ClassInfo(object): def __init__(self, display_name: str, class_name: str): super(ClassInfo, self).__init__() self._display_name = display_name self._class_name = class_name @property def display_name(self) -> str: return self._display_name @property def class_name(self) -> str: return self._class_name class OmniMDL(object): OMNI_GLASS: ClassInfo = ClassInfo(display_name='Omni Glass', class_name='OmniGlass.mdl|OmniGlass') OMNI_GLASS_OPACITY: ClassInfo = ClassInfo(display_name='Omni Glass Opacity', class_name='OmniGlass_Opacity.mdl|OmniGlass_Opacity') OMNI_PBR: ClassInfo = ClassInfo(display_name='Omni PBR', class_name='OmniPBR.mdl|OmniPBR') OMNI_PBR_CLEAR_COAT: ClassInfo = ClassInfo(display_name='Omni PBR Clear Coat', class_name='OmniPBR_ClearCoat.mdl|OmniPBR_ClearCoat') OMNI_PBR_CLEAR_COAT_OPACITY: ClassInfo = ClassInfo(display_name='Omni PBR Clear Coat Opacity', class_name='OmniPBR_ClearCoat_Opacity.mdl|OmniPBR_ClearCoat_Opacity') OMNI_PBR_OPACITY = ClassInfo(display_name='Omni PBR Opacity', class_name='OmniPBR_Opacity.mdl|OmniPBR_Opacity') OMNI_SURFACE: ClassInfo = ClassInfo(display_name='OmniSurface', class_name='OmniSurface.mdl|OmniSurface') OMNI_SURFACE_LITE: ClassInfo = ClassInfo(display_name='OmniSurfaceLite', class_name='OmniSurfaceLite.mdl|OmniSurfaceLite') OMNI_SURFACE_UBER: ClassInfo = ClassInfo(display_name='OmniSurfaceUber', class_name='OmniSurfaceUber.mdl|OmniSurfaceUber') class MayaShader(object): LAMBERT: ClassInfo = ClassInfo(display_name='Lambert', class_name='lambert') class ConversionMap(Serializable): @classmethod def Create( cls, render_context: str, application: str, document: ConversionGraph, ) -> 'ConversionMap': if not isinstance(document, ConversionGraph): raise Exception('Argument "document" unexpected class: "{0}"'.format(type(document))) instance = cls() instance._render_context = render_context instance._application = application instance._conversion_graph_id = document.id instance._conversion_graph = document return instance def __init__(self): super(ConversionMap, self).__init__() self._render_context: str = '' self._application: str = '' self._conversion_graph_id: str = '' self._conversion_graph: ConversionGraph = None def __eq__(self, other: 'ConversionMap') -> bool: if not isinstance(other, ConversionMap): return False if not self.render_context == other.render_context: return False if not self.application == other.application: return False if not self.conversion_graph_id == other.conversion_graph_id: return False return True def serialize(self) -> dict: output = super(ConversionMap, self).serialize() output['_render_context'] = self._render_context output['_application'] = self._application output['_conversion_graph_id'] = self._conversion_graph_id return output def deserialize(self, data: dict) -> None: super(ConversionMap, self).deserialize(data=data) self._render_context = data['_render_context'] if '_render_context' in data.keys() else '' self._application = data['_application'] if '_application' in data.keys() else '' self._conversion_graph_id = data['_conversion_graph_id'] if '_conversion_graph_id' in data.keys() else '' self._conversion_graph = None @property def render_context(self) -> str: return self._render_context @property def application(self) -> str: return self._application @property def conversion_graph_id(self) -> str: return self._conversion_graph_id @property def conversion_graph(self) -> ConversionGraph: return self._conversion_graph class ConversionManifest(Serializable): def __init__(self): super(ConversionManifest, self).__init__() self._version_major: int = 100 self._version_minor: int = 0 self._conversion_maps: typing.List[ConversionMap] = [] self._store_id = 'ConversionManifest.json' def serialize(self) -> dict: output = super(ConversionManifest, self).serialize() output['_version_major'] = self._version_major output['_version_minor'] = self._version_minor output['_conversion_maps'] = [o.serialize() for o in self._conversion_maps] return output def deserialize(self, data: dict) -> None: super(ConversionManifest, self).deserialize(data=data) self._version_major = data['_version_major'] if '_version_major' in data.keys() else 100 self._version_minor = data['_version_minor'] if '_version_minor' in data.keys() else 0 items = [] if '_conversion_maps' in data.keys(): for o in data['_conversion_maps']: item = ConversionMap() item.deserialize(data=o) items.append(item) self._conversion_maps = items def set_version(self, major: int = 100, minor: int = 0) -> None: self._version_major = major self._version_minor = minor def add( self, render_context: str, application: str, document: ConversionGraph, ) -> ConversionMap: item = ConversionMap.Create( render_context=render_context, application=application, document=document, ) self._conversion_maps.append(item) return item def remove(self, item: ConversionMap) -> None: if item in self._conversion_maps: self._conversion_maps.remove(item) @property def conversion_maps(self) -> typing.List[ConversionMap]: return self._conversion_maps[:] @property def version(self) -> str: return '{0}.{1}'.format(self._version_major, self._version_minor) @property def version_major(self) -> int: return self._version_major @property def version_minor(self) -> int: return self._version_minor @property def store_id(self) -> str: return self._store_id
100,965
Python
32.949563
187
0.58241
NVIDIA-Omniverse/blender_omniverse_addons/omni/universalmaterialmap/core/feature.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. VIEWPORT: bool = False """ BROWSE_FOR_LIBRARY - add ability to browse for a UMM library. - includes creating a new one. Without this features it is up to Connectors to create and register libraries on install. """ BROWSE_FOR_LIBRARY: bool = False POLLING: bool = False COPY: bool = True
1,155
Python
32.028571
89
0.730736
NVIDIA-Omniverse/blender_omniverse_addons/omni/universalmaterialmap/core/operator.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import sys import typing from .data import Operator, Plug, DagNode, OperatorInstance from . import util class ConstantFloat(Operator): def __init__(self): super(ConstantFloat, self).__init__( id='293c38db-c9b3-4b37-ab02-c4ff6052bcb6', name='Constant Float', required_inputs=0, min_inputs=0, max_inputs=0, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].computed_value = output_plugs[0].value if output_plugs[0].value else 0.0 def generate_input(self, parent: DagNode, index: int) -> Plug: raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='value', display_name='Float', value_type=Plug.VALUE_TYPE_FLOAT, editable=True ) plug.value = 0.0 return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].value = len(self.id) * 0.3 def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): for output in output_plugs: if not output.computed_value == len(self.id) * 0.3: raise Exception('Test failed.') class ConstantInteger(Operator): def __init__(self): super(ConstantInteger, self).__init__( id='293c38db-c9b3-4b37-ab02-c4ff6052bcb7', name='Constant Integer', required_inputs=0, min_inputs=0, max_inputs=0, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].computed_value = output_plugs[0].value if output_plugs[0].value else 0 def generate_input(self, parent: DagNode, index: int) -> Plug: raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='value', display_name='Integer', value_type=Plug.VALUE_TYPE_INTEGER, editable=True ) plug.value = 0 return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].value = len(self.id) def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): for output in output_plugs: if not output.computed_value == len(self.id): raise Exception('Test failed.') class ConstantBoolean(Operator): def __init__(self): super(ConstantBoolean, self).__init__( id='293c38db-c9b3-4b37-ab02-c4ff6052bcb8', name='Constant Boolean', required_inputs=0, min_inputs=0, max_inputs=0, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].computed_value = output_plugs[0].value if output_plugs[0].value else False def generate_input(self, parent: DagNode, index: int) -> Plug: raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='value', display_name='Boolean', value_type=Plug.VALUE_TYPE_BOOLEAN, editable=True ) plug.value = True return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].value = False def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): for output in output_plugs: if output.computed_value: raise Exception('Test failed.') class ConstantString(Operator): def __init__(self): super(ConstantString, self).__init__( id='cb169ec0-5ddb-45eb-98d1-5d09f1ca759g', name='Constant String', required_inputs=0, min_inputs=0, max_inputs=0, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].computed_value = output_plugs[0].value if output_plugs[0].value else '' # print('ConstantString._compute_outputs(): output_plugs[0].computed_value', output_plugs[0].computed_value) def generate_input(self, parent: DagNode, index: int) -> Plug: raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='value', display_name='String', value_type=Plug.VALUE_TYPE_STRING, editable=True ) plug.value = '' plug.default_value = '' return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].value = self.id def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): for output in output_plugs: if not output.computed_value == self.id: raise Exception('Test failed.') class ConstantRGB(Operator): def __init__(self): super(ConstantRGB, self).__init__( id='60f21797-dd62-4b06-9721-53882aa42e81', name='Constant RGB', required_inputs=0, min_inputs=0, max_inputs=0, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].computed_value = output_plugs[0].value if output_plugs[0].value else (0, 0, 0) def generate_input(self, parent: DagNode, index: int) -> Plug: raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='value', display_name='Color', value_type=Plug.VALUE_TYPE_VECTOR3, editable=True ) plug.value = (0, 0, 0) return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].value = (0.1, 0.2, 0.3) def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): for output in output_plugs: if not output.computed_value == (0.1, 0.2, 0.3): raise Exception('Test failed.') class ConstantRGBA(Operator): def __init__(self): super(ConstantRGBA, self).__init__( id='0ab39d82-5862-4332-af7a-329200ae1d14', name='Constant RGBA', required_inputs=0, min_inputs=0, max_inputs=0, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].computed_value = output_plugs[0].value if output_plugs[0].value else (0, 0, 0, 0) def generate_input(self, parent: DagNode, index: int) -> Plug: raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='value', display_name='Color', value_type=Plug.VALUE_TYPE_VECTOR4, editable=True ) plug.value = (0, 0, 0, 1) return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].value = (0.1, 0.2, 0.3, 0.4) def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): for output in output_plugs: if not output.computed_value == (0.1, 0.2, 0.3, 0.4): raise Exception('Test failed.') class BooleanSwitch(Operator): """ Outputs the value of input 2 if input 1 is TRUE. Otherwise input 3 will be output. Input 1 must be a boolean. Input 2 and 3 can be of any value type. """ def __init__(self): super(BooleanSwitch, self).__init__( id='a628ab13-f19f-45b3-81cf-6824dd6e7b5d', name='Boolean Switch', required_inputs=3, min_inputs=3, max_inputs=3, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): debug = False value = None if debug: print('BooleanSwitch') print('\tinput_plugs[0].input:', input_plugs[0].input) if input_plugs[0].input is not None: if debug: print('\tinput_plugs[0].input.computed_value:', input_plugs[0].input.computed_value) print('\tinput_plugs[1].input:', input_plugs[1].input) if input_plugs[1].input is not None: print('\tinput_plugs[1].input.computed_value:', input_plugs[1].input.computed_value) print('\tinput_plugs[2].input:', input_plugs[2].input) if input_plugs[2].input is not None: print('\tinput_plugs[2].input.computed_value:', input_plugs[2].input.computed_value) if input_plugs[0].input.computed_value: value = input_plugs[1].input.computed_value if input_plugs[1].input is not None else False else: value = input_plugs[2].input.computed_value if input_plugs[2].input is not None else False elif debug: print('\tskipping evaluating inputs') if debug: print('\tvalue:', value) print('\toutput_plugs[0].computed_value is value', output_plugs[0].computed_value is value) output_plugs[0].computed_value = value if value is not None else False def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create(parent=parent, name='input_boolean', display_name='Boolean', value_type=Plug.VALUE_TYPE_BOOLEAN) plug.value = False return plug if index == 1: return Plug.Create(parent=parent, name='on_true', display_name='True Output', value_type=Plug.VALUE_TYPE_ANY) if index == 2: return Plug.Create(parent=parent, name='on_false', display_name='False Output', value_type=Plug.VALUE_TYPE_ANY) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create(parent=parent, name='output', display_name='Output', value_type=Plug.VALUE_TYPE_ANY) plug.value = False return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantBoolean()) fake.outputs[0].value = True input_plugs[0].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantString()) fake.outputs[0].value = 'Input 1 value' input_plugs[1].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantString()) fake.outputs[0].value = 'Input 2 value' input_plugs[2].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): for output in output_plugs: if not output.computed_value == 'Input 1 value': raise Exception('Test failed.') class SplitRGB(Operator): def __init__(self): super(SplitRGB, self).__init__( id='1cbcf8c6-328c-49b6-b4fc-d16fd78d4868', name='Split RGB', required_inputs=1, min_inputs=1, max_inputs=1, num_outputs=3 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if input_plugs[0].input is None: output_plugs[0].computed_value = 0 output_plugs[1].computed_value = 0 output_plugs[2].computed_value = 0 else: value = input_plugs[0].input.computed_value try: test = iter(value) is_iterable = True except TypeError: is_iterable = False if is_iterable and len(value) == 3: output_plugs[0].computed_value = value[0] output_plugs[1].computed_value = value[1] output_plugs[2].computed_value = value[2] else: output_plugs[0].computed_value = output_plugs[0].default_value output_plugs[1].computed_value = output_plugs[1].default_value output_plugs[2].computed_value = output_plugs[2].default_value def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='input_rgb', display_name='RGB', value_type=Plug.VALUE_TYPE_VECTOR3) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='red', display_name='Red', value_type=Plug.VALUE_TYPE_FLOAT, editable=False ) plug.value = 0 return plug if index == 1: plug = Plug.Create( parent=parent, name='green', display_name='Green', value_type=Plug.VALUE_TYPE_FLOAT, editable=False ) plug.value = 0 return plug if index == 2: plug = Plug.Create( parent=parent, name='blue', display_name='Blue', value_type=Plug.VALUE_TYPE_FLOAT, editable=False ) plug.value = 0 return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantRGB()) fake.outputs[0].value = (0.1, 0.2, 0.3) input_plugs[0].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == 0.1: raise Exception('Test failed.') if not output_plugs[1].computed_value == 0.2: raise Exception('Test failed.') if not output_plugs[2].computed_value == 0.3: raise Exception('Test failed.') class MergeRGB(Operator): def __init__(self): super(MergeRGB, self).__init__( id='1cbcf8c6-328d-49b6-b4fc-d16fd78d4868', name='Merge RGB', required_inputs=3, min_inputs=3, max_inputs=3, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): rgb = [0.0, 0.0, 0.0] for i in range(3): if input_plugs[i].input is not None: assumed_value_type = input_plugs[i].input.value_type if util.to_plug_value_type(value=input_plugs[i].input.computed_value, assumed_value_type=assumed_value_type) == Plug.VALUE_TYPE_FLOAT: rgb[i] = input_plugs[i].input.computed_value output_plugs[0].computed_value = tuple(rgb) def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='input_r', display_name='R', value_type=Plug.VALUE_TYPE_FLOAT) if index == 1: return Plug.Create(parent=parent, name='input_g', display_name='G', value_type=Plug.VALUE_TYPE_FLOAT) if index == 2: return Plug.Create(parent=parent, name='input_B', display_name='B', value_type=Plug.VALUE_TYPE_FLOAT) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='rgb', display_name='RGB', value_type=Plug.VALUE_TYPE_VECTOR3, editable=False ) plug.value = (0, 0, 0) return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.1 input_plugs[0].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.2 input_plugs[1].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.3 input_plugs[2].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == (0.1, 0.2, 0.3): raise Exception('Test failed.') class SplitRGBA(Operator): def __init__(self): super(SplitRGBA, self).__init__( id='2c48e13c-2b58-48b9-a3b6-5f977c402b2e', name='Split RGBA', required_inputs=1, min_inputs=1, max_inputs=1, num_outputs=4 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if input_plugs[0].input is None: output_plugs[0].computed_value = 0 output_plugs[1].computed_value = 0 output_plugs[2].computed_value = 0 output_plugs[3].computed_value = 0 return value = input_plugs[0].input.computed_value try: test = iter(value) is_iterable = True except TypeError: is_iterable = False if is_iterable and len(value) == 4: output_plugs[0].computed_value = value[0] output_plugs[1].computed_value = value[1] output_plugs[2].computed_value = value[2] output_plugs[3].computed_value = value[3] else: output_plugs[0].computed_value = output_plugs[0].default_value output_plugs[1].computed_value = output_plugs[1].default_value output_plugs[2].computed_value = output_plugs[2].default_value output_plugs[3].computed_value = output_plugs[3].default_value def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='input_rgba', display_name='RGBA', value_type=Plug.VALUE_TYPE_VECTOR4) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='red', display_name='Red', value_type=Plug.VALUE_TYPE_FLOAT, editable=False ) plug.value = 0 return plug if index == 1: plug = Plug.Create( parent=parent, name='green', display_name='Green', value_type=Plug.VALUE_TYPE_FLOAT, editable=False ) plug.value = 0 return plug if index == 2: plug = Plug.Create( parent=parent, name='blue', display_name='Blue', value_type=Plug.VALUE_TYPE_FLOAT, editable=False ) plug.value = 0 return plug if index == 3: plug = Plug.Create( parent=parent, name='alpha', display_name='Alpha', value_type=Plug.VALUE_TYPE_FLOAT, editable=False ) plug.value = 0 return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantRGB()) fake.outputs[0].value = (0.1, 0.2, 0.3, 0.4) input_plugs[0].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == 0.1: raise Exception('Test failed.') if not output_plugs[1].computed_value == 0.2: raise Exception('Test failed.') if not output_plugs[2].computed_value == 0.3: raise Exception('Test failed.') if not output_plugs[3].computed_value == 0.4: raise Exception('Test failed.') class MergeRGBA(Operator): def __init__(self): super(MergeRGBA, self).__init__( id='92e57f3d-8514-4786-a4ed-2767139a15eb', name='Merge RGBA', required_inputs=4, min_inputs=4, max_inputs=4, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): rgba = [0.0, 0.0, 0.0, 0.0] for i in range(4): if input_plugs[i].input is not None: assumed_value_type = input_plugs[i].input.value_type if util.to_plug_value_type(value=input_plugs[i].input.computed_value, assumed_value_type=assumed_value_type) == Plug.VALUE_TYPE_FLOAT: rgba[i] = input_plugs[i].input.computed_value output_plugs[0].computed_value = tuple(rgba) def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='input_r', display_name='R', value_type=Plug.VALUE_TYPE_FLOAT) if index == 1: return Plug.Create(parent=parent, name='input_g', display_name='G', value_type=Plug.VALUE_TYPE_FLOAT) if index == 2: return Plug.Create(parent=parent, name='input_b', display_name='B', value_type=Plug.VALUE_TYPE_FLOAT) if index == 3: return Plug.Create(parent=parent, name='input_a', display_name='A', value_type=Plug.VALUE_TYPE_FLOAT) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='rgba', display_name='RGBA', value_type=Plug.VALUE_TYPE_VECTOR3, editable=False ) plug.value = (0, 0, 0, 0) return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.1 input_plugs[0].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.2 input_plugs[1].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.3 input_plugs[2].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.4 input_plugs[3].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == (0.1, 0.2, 0.3, 0.4): raise Exception('Test failed.') class LessThan(Operator): def __init__(self): super(LessThan, self).__init__( id='996df9bd-08d5-451b-a67c-80d0de7fba32', name='Less Than', required_inputs=2, min_inputs=2, max_inputs=2, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if input_plugs[0].input is None or input_plugs[1].input is None: for output in output_plugs: output.computed_value = False return value = input_plugs[0].input.computed_value compare = input_plugs[1].input.computed_value result = False try: result = value < compare except Exception as error: print('WARNING: Universal Material Map: ' 'unable to compare if "{0}" is less than "{1}". ' 'Setting output to "{2}".'.format( value, compare, result )) output_plugs[0].computed_value = result def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='value', display_name='Value', value_type=Plug.VALUE_TYPE_FLOAT) if index == 1: return Plug.Create(parent=parent, name='comparison', display_name='Comparison', value_type=Plug.VALUE_TYPE_FLOAT) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='output', display_name='Is Less Than', value_type=Plug.VALUE_TYPE_BOOLEAN) raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.1 input_plugs[0].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.2 input_plugs[1].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value: raise Exception('Test failed.') class GreaterThan(Operator): def __init__(self): super(GreaterThan, self).__init__( id='1e751c3a-f6cd-43a2-aa72-22cb9d82ad19', name='Greater Than', required_inputs=2, min_inputs=2, max_inputs=2, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if input_plugs[0].input is None or input_plugs[1].input is None: output_plugs[0].computed_value = False return value = input_plugs[0].input.computed_value compare = input_plugs[1].input.computed_value result = False try: result = value > compare except Exception as error: print('WARNING: Universal Material Map: ' 'unable to compare if "{0}" is greater than "{1}". ' 'Setting output to "{2}".'.format( value, compare, result )) output_plugs[0].computed_value = result def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='value', display_name='Value', value_type=Plug.VALUE_TYPE_FLOAT) if index == 1: return Plug.Create(parent=parent, name='comparison', display_name='Comparison', value_type=Plug.VALUE_TYPE_FLOAT) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='output', display_name='Is Greater Than', value_type=Plug.VALUE_TYPE_BOOLEAN) raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.1 input_plugs[0].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantFloat()) fake.outputs[0].value = 0.2 input_plugs[1].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if output_plugs[0].computed_value: raise Exception('Test failed.') class Or(Operator): def __init__(self): super(Or, self).__init__( id='d0288faf-cb2e-4765-8923-1a368b45f62c', name='Or', required_inputs=2, min_inputs=2, max_inputs=2, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if input_plugs[0].input is None and input_plugs[1].input is None: output_plugs[0].computed_value = False return value_1 = input_plugs[0].input.computed_value if input_plugs[0].input else False value_2 = input_plugs[1].input.computed_value if input_plugs[1].input else False if value_1 is None and value_2 is None: output_plugs[0].computed_value = False return if value_1 is None: output_plugs[0].computed_value = True if value_2 else False return if value_2 is None: output_plugs[0].computed_value = True if value_1 else False return output_plugs[0].computed_value = value_1 or value_2 def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='value_1', display_name='Value 1', value_type=Plug.VALUE_TYPE_ANY) if index == 1: return Plug.Create(parent=parent, name='value_2', display_name='Value 2', value_type=Plug.VALUE_TYPE_ANY) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='output', display_name='Is True', value_type=Plug.VALUE_TYPE_BOOLEAN) raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantBoolean()) fake.outputs[0].value = True input_plugs[0].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantBoolean()) fake.outputs[0].value = False input_plugs[1].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value: raise Exception('Test failed.') class And(Operator): def __init__(self): super(And, self).__init__( id='9c5e4fb9-9948-4075-a7d6-ae9bc04e25b5', name='And', required_inputs=2, min_inputs=2, max_inputs=2, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if input_plugs[0].input is None and input_plugs[1].input is None: output_plugs[0].computed_value = False return value_1 = input_plugs[0].input.computed_value if input_plugs[0].input else False value_2 = input_plugs[1].input.computed_value if input_plugs[1].input else False if value_1 is None and value_2 is None: output_plugs[0].computed_value = False return if value_1 is None: output_plugs[0].computed_value = True if value_2 else False return if value_2 is None: output_plugs[0].computed_value = True if value_1 else False return output_plugs[0].computed_value = value_1 and value_2 def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='value_1', display_name='Value 1', value_type=Plug.VALUE_TYPE_ANY) if index == 1: return Plug.Create(parent=parent, name='value_2', display_name='Value 2', value_type=Plug.VALUE_TYPE_ANY) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='output', display_name='Is True', value_type=Plug.VALUE_TYPE_BOOLEAN) raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantBoolean()) fake.outputs[0].value = True input_plugs[0].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantBoolean()) fake.outputs[0].value = True input_plugs[1].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value: raise Exception('Test failed.') class Equal(Operator): def __init__(self): super(Equal, self).__init__( id='fb353972-aebd-4d32-8231-f644f75d322c', name='Equal', required_inputs=2, min_inputs=2, max_inputs=2, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if input_plugs[0].input is None and input_plugs[1].input is None: output_plugs[0].computed_value = True return if input_plugs[0].input is None or input_plugs[1].input is None: output_plugs[0].computed_value = False return value_1 = input_plugs[0].input.computed_value value_2 = input_plugs[1].input.computed_value if value_1 is None and value_2 is None: output_plugs[0].computed_value = True return if value_1 is None or value_2 is None: output_plugs[0].computed_value = False return result = False try: result = value_1 == value_2 except Exception as error: print('WARNING: Universal Material Map: ' 'unable to compare if "{0}" is equal to "{1}". ' 'Setting output to "{2}".'.format( value_1, value_2, result )) output_plugs[0].computed_value = result def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='value_1', display_name='Value 1', value_type=Plug.VALUE_TYPE_ANY) if index == 1: return Plug.Create(parent=parent, name='value_1', display_name='Value 2', value_type=Plug.VALUE_TYPE_ANY) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='output', display_name='Are Equal', value_type=Plug.VALUE_TYPE_BOOLEAN) raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantString()) fake.outputs[0].value = self.id input_plugs[0].input = fake.outputs[0] fake = OperatorInstance.FromOperator(operator=ConstantString()) fake.outputs[0].value = self.id input_plugs[1].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value: raise Exception('Test failed.') class Not(Operator): def __init__(self): super(Not, self).__init__( id='7b8b67df-ce2e-445c-98b7-36ea695c77e3', name='Not', required_inputs=1, min_inputs=1, max_inputs=1, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if input_plugs[0].input is None: output_plugs[0].computed_value = False return value_1 = input_plugs[0].input.computed_value if value_1 is None: output_plugs[0].computed_value = False return output_plugs[0].computed_value = not value_1 def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='value', display_name='Boolean', value_type=Plug.VALUE_TYPE_BOOLEAN) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='output', display_name='Boolean', value_type=Plug.VALUE_TYPE_BOOLEAN) raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantBoolean()) fake.outputs[0].value = False input_plugs[0].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value: raise Exception('Test failed.') class ValueTest(Operator): def __init__(self): super(ValueTest, self).__init__( id='2899f66b-2e8d-467b-98d1-5f590cf98e7a', name='Value Test', required_inputs=1, min_inputs=1, max_inputs=1, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if input_plugs[0].input is None: output_plugs[0].computed_value = None return output_plugs[0].computed_value = input_plugs[0].input.computed_value def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='input', display_name='Input', value_type=Plug.VALUE_TYPE_ANY) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='output', display_name='Output', value_type=Plug.VALUE_TYPE_ANY) raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantInteger()) fake.outputs[0].value = 10 input_plugs[0].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == 10: raise Exception('Test failed.') class ValueResolver(Operator): def __init__(self): super(ValueResolver, self).__init__( id='74306cd0-b668-4a92-9e15-7b23486bd89a', name='Value Resolver', required_inputs=8, min_inputs=8, max_inputs=8, num_outputs=7 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): assumed_value_type = input_plugs[0].input.value_type if input_plugs[0].input else input_plugs[0].value_type computed_value = input_plugs[0].input.computed_value if input_plugs[0].input else False value_type = util.to_plug_value_type(value=computed_value, assumed_value_type=assumed_value_type) if value_type == Plug.VALUE_TYPE_BOOLEAN: output_plugs[0].computed_value = computed_value else: output_plugs[0].computed_value = input_plugs[1].computed_value if value_type == Plug.VALUE_TYPE_VECTOR3: output_plugs[1].computed_value = computed_value else: output_plugs[1].computed_value = input_plugs[2].computed_value if value_type == Plug.VALUE_TYPE_FLOAT: output_plugs[2].computed_value = computed_value else: output_plugs[2].computed_value = input_plugs[3].computed_value if value_type == Plug.VALUE_TYPE_INTEGER: output_plugs[3].computed_value = computed_value else: output_plugs[3].computed_value = input_plugs[4].computed_value if value_type == Plug.VALUE_TYPE_STRING: output_plugs[4].computed_value = computed_value else: output_plugs[4].computed_value = input_plugs[5].computed_value if value_type == Plug.VALUE_TYPE_VECTOR4: output_plugs[5].computed_value = computed_value else: output_plugs[5].computed_value = input_plugs[6].computed_value if value_type == Plug.VALUE_TYPE_LIST: output_plugs[6].computed_value = computed_value else: output_plugs[6].computed_value = input_plugs[7].computed_value for index, input_plug in enumerate(input_plugs): if index == 0: continue input_plug.is_editable = not input_plug.input for output_plug in output_plugs: output_plug.is_editable = False def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='input', display_name='Input', value_type=Plug.VALUE_TYPE_ANY) if index == 1: plug = Plug.Create( parent=parent, name='boolean', display_name='Boolean', value_type=Plug.VALUE_TYPE_BOOLEAN, editable=True, ) plug.value = False return plug if index == 2: plug = Plug.Create( parent=parent, name='color', display_name='Color', value_type=Plug.VALUE_TYPE_VECTOR3, editable=True, ) plug.value = (0, 0, 0) return plug if index == 3: plug = Plug.Create( parent=parent, name='float', display_name='Float', value_type=Plug.VALUE_TYPE_FLOAT, editable=True, ) plug.value = 0 return plug if index == 4: plug = Plug.Create( parent=parent, name='integer', display_name='Integer', value_type=Plug.VALUE_TYPE_INTEGER, editable=True, ) plug.value = 0 return plug if index == 5: plug = Plug.Create( parent=parent, name='string', display_name='String', value_type=Plug.VALUE_TYPE_STRING, editable=True, ) plug.value = '' return plug if index == 6: plug = Plug.Create( parent=parent, name='rgba', display_name='RGBA', value_type=Plug.VALUE_TYPE_VECTOR4, editable=True, ) plug.value = (0, 0, 0, 1) return plug if index == 7: plug = Plug.Create( parent=parent, name='list', display_name='List', value_type=Plug.VALUE_TYPE_LIST, editable=False, ) plug.value = [] return plug raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='boolean', display_name='Boolean', value_type=Plug.VALUE_TYPE_BOOLEAN, editable=False, ) plug.value = False return plug if index == 1: plug = Plug.Create( parent=parent, name='color', display_name='Color', value_type=Plug.VALUE_TYPE_VECTOR3, editable=False, ) plug.value = (0, 0, 0) return plug if index == 2: plug = Plug.Create( parent=parent, name='float', display_name='Float', value_type=Plug.VALUE_TYPE_FLOAT, editable=False, ) plug.value = 0 return plug if index == 3: plug = Plug.Create( parent=parent, name='integer', display_name='Integer', value_type=Plug.VALUE_TYPE_INTEGER, editable=False, ) plug.value = 0 return plug if index == 4: plug = Plug.Create( parent=parent, name='string', display_name='String', value_type=Plug.VALUE_TYPE_STRING, editable=False, ) plug.value = '' return plug if index == 5: plug = Plug.Create( parent=parent, name='rgba', display_name='RGBA', value_type=Plug.VALUE_TYPE_VECTOR4, editable=False, ) plug.value = (0, 0, 0, 1) return plug if index == 6: plug = Plug.Create( parent=parent, name='list', display_name='List', value_type=Plug.VALUE_TYPE_LIST, editable=False, ) plug.value = [] return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantInteger()) fake.outputs[0].value = 10 input_plugs[0].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[3].computed_value == 10: raise Exception('Test failed.') class MayaTransparencyResolver(Operator): """ Specialty operator based on Maya transparency attribute. If the input is of type string - and is not an empty string - then the output will be TRUE. If the input is a tripple float - and any value is greater than zero - then the output will also be TRUE. In all other cases the output will be FALSE. """ def __init__(self): super(MayaTransparencyResolver, self).__init__( id='2b523832-ac84-4051-9064-6046121dcd48', name='Maya Transparency Resolver', required_inputs=1, min_inputs=1, max_inputs=1, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): is_transparent = False assumed_value_type = input_plugs[0].input.value_type if input_plugs[0].input else input_plugs[0].value_type computed_value = input_plugs[0].input.computed_value if input_plugs[0].input else False value_type = util.to_plug_value_type(value=computed_value, assumed_value_type=assumed_value_type) if value_type == Plug.VALUE_TYPE_STRING: is_transparent = not computed_value == '' elif value_type == Plug.VALUE_TYPE_VECTOR3: for value in computed_value: if value > 0: is_transparent = True break elif value_type == Plug.VALUE_TYPE_FLOAT: is_transparent = computed_value > 0 output_plugs[0].computed_value = is_transparent def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='input', display_name='Input', value_type=Plug.VALUE_TYPE_ANY) raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='is_transparent', display_name='Is Transparent', value_type=Plug.VALUE_TYPE_BOOLEAN, ) plug.value = False return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): fake = OperatorInstance.FromOperator(operator=ConstantRGB()) fake.outputs[0].value = (0.5, 0.5, 0.5) input_plugs[0].input = fake.outputs[0] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value: raise Exception('Test failed.') class ListGenerator(Operator): def __init__(self): super(ListGenerator, self).__init__( id='a410f7a0-280a-451f-a26c-faf9a8e302b4', name='List Generator', required_inputs=0, min_inputs=0, max_inputs=-1, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output = [] for input_plug in input_plugs: output.append(input_plug.computed_value) output_plugs[0].computed_value = output def generate_input(self, parent: DagNode, index: int) -> Plug: return Plug.Create( parent=parent, name='[{0}]'.format(index), display_name='[{0}]'.format(index), value_type=Plug.VALUE_TYPE_ANY, editable=False, is_removable=True, ) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='list', display_name='list', value_type=Plug.VALUE_TYPE_LIST) raise Exception('Output index "{0}" not supported.'.format(index)) def remove_plug(self, operator_instance: 'OperatorInstance', plug: 'Plug') -> None: super(ListGenerator, self).remove_plug(operator_instance=operator_instance, plug=plug) for index, plug in enumerate(operator_instance.inputs): plug.name = '[{0}]'.format(index) plug.display_name = '[{0}]'.format(index) for plug in operator_instance.outputs: plug.invalidate() def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): pass def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): pass class ListIndex(Operator): def __init__(self): super(ListIndex, self).__init__( id='e4a81506-fb6b-4729-8273-f68e97f5bc6b', name='List Index', required_inputs=2, min_inputs=2, max_inputs=2, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): try: test = iter(input_plugs[0].computed_value) index = input_plugs[1].computed_value if 0 <= index < len(input_plugs[0].computed_value): output_plugs[0].computed_value = input_plugs[0].computed_value[index] else: output_plugs[0].computed_value = None except TypeError: output_plugs[0].computed_value = None def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='list', display_name='List', value_type=Plug.VALUE_TYPE_LIST) if index == 1: plug = Plug.Create( parent=parent, name='index', display_name='Index', value_type=Plug.VALUE_TYPE_INTEGER, editable=True ) plug.computed_value = 0 return plug raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='output', display_name='Output', value_type=Plug.VALUE_TYPE_ANY) raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): input_plugs[0].value = ['hello', 'world'] input_plugs[1].value = 1 def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == 'world': raise Exception('Test failed.') class MDLColorSpace(Operator): def __init__(self): super(MDLColorSpace, self).__init__( id='cf0b97c8-fb55-4cf3-8afc-23ebd4a0a6c7', name='MDL Color Space', required_inputs=0, min_inputs=0, max_inputs=0, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].computed_value = output_plugs[0].value if output_plugs[0].value else 'auto' def generate_input(self, parent: DagNode, index: int) -> Plug: raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='color_space', display_name='Color Space', value_type=Plug.VALUE_TYPE_ENUM, editable=True ) plug.enum_values = ['auto', 'raw', 'sRGB'] plug.default_value = 'auto' plug.value = 'auto' return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output_plugs[0].value = output_plugs[0].enum_values[2] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == output_plugs[0].enum_values[2]: raise Exception('Test failed.') class MDLTextureResolver(Operator): def __init__(self): super(MDLTextureResolver, self).__init__( id='af766adb-cf54-4a8b-a598-44b04fbcf630', name='MDL Texture Resolver', required_inputs=2, min_inputs=2, max_inputs=2, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): filepath = input_plugs[0].input.computed_value if input_plugs[0].input else '' value_type = util.to_plug_value_type(value=filepath, assumed_value_type=Plug.VALUE_TYPE_STRING) filepath = filepath if value_type == Plug.VALUE_TYPE_STRING else '' colorspace = input_plugs[1].computed_value output_plugs[0].computed_value = [filepath, colorspace] def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='input', display_name='Input', value_type=Plug.VALUE_TYPE_STRING) if index == 1: plug = Plug.Create( parent=parent, name='color_space', display_name='Color Space', value_type=Plug.VALUE_TYPE_ENUM, editable=True ) plug.enum_values = ['auto', 'raw', 'sRGB'] plug.default_value = 'auto' plug.value = 'auto' return plug raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='list', display_name='List', value_type=Plug.VALUE_TYPE_LIST, editable=False, ) plug.default_value = ['', 'auto'] plug.value = ['', 'auto'] return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): input_plugs[0].value = 'c:/folder/color.png' input_plugs[1].value = 'raw' def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[3].computed_value == ['c:/folder/color.png', 'raw']: raise Exception('Test failed.') class SplitTextureData(Operator): def __init__(self): super(SplitTextureData, self).__init__( id='6a411798-434c-4ad4-b464-0bd2e78cdcec', name='Split Texture Data', required_inputs=1, min_inputs=1, max_inputs=1, num_outputs=2 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): is_valid_input = False try: value = input_plugs[0].computed_value test = iter(value) if len(value) == 2: if sys.version_info.major < 3: if isinstance(value[0], basestring) and isinstance(value[1], basestring): is_valid_input = True else: if isinstance(value[0], str) and isinstance(value[1], str): is_valid_input = True except TypeError: pass if is_valid_input: output_plugs[0].computed_value = value[0] output_plugs[1].computed_value = value[1] else: output_plugs[0].computed_value = '' output_plugs[1].computed_value = 'auto' def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create(parent=parent, name='list', display_name='List', value_type=Plug.VALUE_TYPE_LIST) plug.default_value = ['', 'auto'] plug.computed_value = ['', 'auto'] return plug raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create(parent=parent, name='texture_path', display_name='Texture Path', value_type=Plug.VALUE_TYPE_STRING) plug.default_value = '' plug.computed_value = '' return plug if index == 1: plug = Plug.Create(parent=parent, name='color_space', display_name='Color Space', value_type=Plug.VALUE_TYPE_STRING) plug.default_value = 'auto' plug.computed_value = 'auto' return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): input_plugs[0].computed_value = ['hello.png', 'world'] def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == 'hello.png': raise Exception('Test failed.') if not output_plugs[1].computed_value == 'world': raise Exception('Test failed.') class Multiply(Operator): def __init__(self): super(Multiply, self).__init__( id='0f5c9828-f582-48aa-b055-c12b91e692a7', name='Multiply', required_inputs=0, min_inputs=2, max_inputs=-1, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): values = [] for input_plug in input_plugs: if isinstance(input_plug.computed_value, int): values.append(input_plug.computed_value) continue if isinstance(input_plug.computed_value, float): values.append(input_plug.computed_value) if len(values) < 2: output_plugs[0].computed_value = 0 else: product = 1.0 for o in values: product *= o output_plugs[0].computed_value = product for input_plug in input_plugs: input_plug.is_editable = not input_plug.input def generate_input(self, parent: DagNode, index: int) -> Plug: plug = Plug.Create( parent=parent, name='[{0}]'.format(index), display_name='[{0}]'.format(index), value_type=Plug.VALUE_TYPE_FLOAT, editable=True, is_removable=index > 1, ) plug.default_value = 1.0 plug.value = 1.0 plug.computed_value = 1.0 return plug def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='product', display_name='product', value_type=Plug.VALUE_TYPE_FLOAT) raise Exception('Output index "{0}" not supported.'.format(index)) def remove_plug(self, operator_instance: 'OperatorInstance', plug: 'Plug') -> None: super(Multiply, self).remove_plug(operator_instance=operator_instance, plug=plug) for index, plug in enumerate(operator_instance.inputs): plug.name = '[{0}]'.format(index) plug.display_name = '[{0}]'.format(index) for plug in operator_instance.outputs: plug.invalidate() def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): input_plugs[0].computed_value = 2 input_plugs[1].computed_value = 2 def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == 4: raise Exception('Test failed.') class ColorSpaceResolver(Operator): MAPPING = { 'MDL|auto|Blender': 'sRGB', 'MDL|srgb|Blender': 'sRGB', 'MDL|raw|Blender': 'Raw', 'Blender|filmic log|MDL': 'raw', 'Blender|linear|MDL': 'raw', 'Blender|linear aces|MDL': 'raw', 'Blender|non-color|MDL': 'raw', 'Blender|raw|MDL': 'raw', 'Blender|srgb|MDL': 'sRGB', 'Blender|xyz|MDL': 'raw', } DEFAULT = { 'Blender': 'Linear', 'MDL': 'auto', } def __init__(self): super(ColorSpaceResolver, self).__init__( id='c159df8f-a0a2-4300-b897-e8eaa689a901', name='Color Space Resolver', required_inputs=3, min_inputs=3, max_inputs=3, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): color_space = input_plugs[0].computed_value.lower() from_color_space = input_plugs[1].computed_value to_color_space = input_plugs[2].computed_value key = '{0}|{1}|{2}'.format( from_color_space, color_space, to_color_space ) if key in ColorSpaceResolver.MAPPING: output_plugs[0].computed_value = ColorSpaceResolver.MAPPING[key] else: output_plugs[0].computed_value = ColorSpaceResolver.DEFAULT[to_color_space] def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='color_space', display_name='Color Space', value_type=Plug.VALUE_TYPE_STRING, editable=False, is_removable=False, ) plug.default_value = '' plug.computed_value = '' return plug if index == 1: plug = Plug.Create( parent=parent, name='from_color_space', display_name='From', value_type=Plug.VALUE_TYPE_ENUM, editable=True ) plug.enum_values = ['MDL', 'Blender'] plug.default_value = 'MDL' plug.computed_value = 'MDL' return plug if index == 2: plug = Plug.Create( parent=parent, name='to_color_space', display_name='To', value_type=Plug.VALUE_TYPE_ENUM, editable=True ) plug.enum_values = ['Blender', 'MDL'] plug.default_value = 'Blender' plug.computed_value = 'Blender' return plug raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create( parent=parent, name='color_space', display_name='Color Space', value_type=Plug.VALUE_TYPE_STRING, editable=False ) plug.default_value = '' plug.computed_value = '' return plug raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): raise NotImplementedError() def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == output_plugs[0].enum_values[2]: raise Exception('Test failed.') class Add(Operator): def __init__(self): super(Add, self).__init__( id='f2818669-5454-4599-8792-2cb09f055bf9', name='Add', required_inputs=0, min_inputs=2, max_inputs=-1, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output = 0 for input_plug in input_plugs: try: output += input_plug.computed_value except: pass output_plugs[0].computed_value = output def generate_input(self, parent: DagNode, index: int) -> Plug: plug = Plug.Create( parent=parent, name='[{0}]'.format(index), display_name='[{0}]'.format(index), value_type=Plug.VALUE_TYPE_FLOAT, editable=True, is_removable=True, ) plug.default_value = 0.0 plug.computed_value = 0.0 return plug def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='sum', display_name='sum', value_type=Plug.VALUE_TYPE_FLOAT) raise Exception('Output index "{0}" not supported.'.format(index)) def remove_plug(self, operator_instance: 'OperatorInstance', plug: 'Plug') -> None: super(Add, self).remove_plug(operator_instance=operator_instance, plug=plug) for index, plug in enumerate(operator_instance.inputs): plug.name = '[{0}]'.format(index) plug.display_name = '[{0}]'.format(index) for plug in operator_instance.outputs: plug.invalidate() def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): pass def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): pass class Subtract(Operator): def __init__(self): super(Subtract, self).__init__( id='15f523f3-4e94-43a5-8306-92d07cbfa48c', name='Subtract', required_inputs=0, min_inputs=2, max_inputs=-1, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): output = None for input_plug in input_plugs: try: if output is None: output = input_plug.computed_value else: output -= input_plug.computed_value except: pass output_plugs[0].computed_value = output def generate_input(self, parent: DagNode, index: int) -> Plug: plug = Plug.Create( parent=parent, name='[{0}]'.format(index), display_name='[{0}]'.format(index), value_type=Plug.VALUE_TYPE_FLOAT, editable=True, is_removable=True, ) plug.default_value = 0.0 plug.computed_value = 0.0 return plug def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='difference', display_name='difference', value_type=Plug.VALUE_TYPE_FLOAT) raise Exception('Output index "{0}" not supported.'.format(index)) def remove_plug(self, operator_instance: 'OperatorInstance', plug: 'Plug') -> None: super(Subtract, self).remove_plug(operator_instance=operator_instance, plug=plug) for index, plug in enumerate(operator_instance.inputs): plug.name = '[{0}]'.format(index) plug.display_name = '[{0}]'.format(index) for plug in operator_instance.outputs: plug.invalidate() def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): pass def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): pass class Remap(Operator): def __init__(self): super(Remap, self).__init__( id='2405c02a-facc-47a6-80ef-d35d959b0cd4', name='Remap', required_inputs=5, min_inputs=5, max_inputs=5, num_outputs=1 ) def _compute_outputs(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): result = 0.0 old_value = input_plugs[0].computed_value try: test = iter(old_value) is_iterable = True except TypeError: is_iterable = False if not is_iterable: try: old_min = input_plugs[1].computed_value old_max = input_plugs[2].computed_value new_min = input_plugs[3].computed_value new_max = input_plugs[4].computed_value result = ((old_value - old_min) / (old_max - old_min)) * (new_max - new_min) + new_min except: pass else: result = [] for o in old_value: try: old_min = input_plugs[1].computed_value old_max = input_plugs[2].computed_value new_min = input_plugs[3].computed_value new_max = input_plugs[4].computed_value result.append(((o - old_min) / (old_max - old_min)) * (new_max - new_min) + new_min) except: pass output_plugs[0].computed_value = result def generate_input(self, parent: DagNode, index: int) -> Plug: if index == 0: plug = Plug.Create(parent=parent, name='value', display_name='Value', value_type=Plug.VALUE_TYPE_ANY) plug.default_value = 0 plug.computed_value = 0 return plug if index == 1: plug = Plug.Create(parent=parent, name='old_min', display_name='Old Min', value_type=Plug.VALUE_TYPE_FLOAT) plug.is_editable = True plug.default_value = 0 plug.computed_value = 0 return plug if index == 2: plug = Plug.Create(parent=parent, name='old_max', display_name='Old Max', value_type=Plug.VALUE_TYPE_FLOAT) plug.is_editable = True plug.default_value = 1 plug.computed_value = 1 return plug if index == 3: plug = Plug.Create(parent=parent, name='new_min', display_name='New Min', value_type=Plug.VALUE_TYPE_FLOAT) plug.is_editable = True plug.default_value = 0 plug.computed_value = 0 return plug if index == 4: plug = Plug.Create(parent=parent, name='new_max', display_name='New Max', value_type=Plug.VALUE_TYPE_FLOAT) plug.is_editable = True plug.default_value = 10 plug.computed_value = 10 return plug raise Exception('Input index "{0}" not supported.'.format(index)) def generate_output(self, parent: DagNode, index: int) -> Plug: if index == 0: return Plug.Create(parent=parent, name='remapped_value', display_name='Remapped Value', value_type=Plug.VALUE_TYPE_FLOAT) raise Exception('Output index "{0}" not supported.'.format(index)) def _prepare_plugs_for_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): input_plugs[0].computed_value = 0.5 input_plugs[1].computed_value = 0 input_plugs[2].computed_value = 1 input_plugs[3].computed_value = 1 input_plugs[4].computed_value = 0 def _assert_test(self, input_plugs: typing.List[Plug], output_plugs: typing.List[Plug]): if not output_plugs[0].computed_value == 0.5: raise Exception('Test failed.')
77,143
Python
37.765829
150
0.570421
NVIDIA-Omniverse/blender_omniverse_addons/omni/universalmaterialmap/core/singleton.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. def Singleton(class_): """A singleton decorator""" instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance
1,123
Python
34.124999
74
0.69902
NVIDIA-Omniverse/blender_omniverse_addons/omni/universalmaterialmap/core/generator/util.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import sys import typing from ..data import Library, Target from .core import IGenerator __generators: typing.List['IGenerator'] = [] def register(generator: IGenerator) -> typing.NoReturn: """ Registers the generator at the top of the internal list - overriding previously registered generators - for future queries and processes. """ generators = getattr(sys.modules[__name__], '__generators') if generator not in generators: generators.insert(0, generator) def un_register(generator: IGenerator) -> typing.NoReturn: """ Removes the generator from internal list of generators and will ignore it for future queries and processes. """ generators = getattr(sys.modules[__name__], '__generators') if generator in generators: generators.remove(generator) def can_generate_target(class_name: str) -> bool: """ """ generators = getattr(sys.modules[__name__], '__generators') for generator in generators: if generator.can_generate_target(class_name=class_name): return True return False def generate_target(class_name: str) -> typing.Tuple[Library, Target]: """ """ generators = getattr(sys.modules[__name__], '__generators') for generator in generators: if generator.can_generate_target(class_name=class_name): print('UMM using generator "{0}" for class_name "{1}".'.format(generator, class_name)) return generator.generate_target(class_name=class_name) raise Exception('Registered generators does not support action.') def generate_targets() -> typing.List[typing.Tuple[Library, Target]]: """ Generates targets from all registered workers that are able to. """ targets = [] generators = getattr(sys.modules[__name__], '__generators') for generator in generators: if generator.can_generate_targets(): print('UMM using generator "{0}" for generating targets.'.format(generator)) targets.extend(generator.generate_targets()) return targets def can_generate_target_from_instance(instance: object) -> bool: """ """ generators = getattr(sys.modules[__name__], '__generators') for generator in generators: if generator.can_generate_target_from_instance(instance=instance): return True return False def generate_target_from_instance(instance: object) -> typing.List[typing.Tuple[Library, Target]]: """ Generates targets from all registered workers that are able to. """ generators = getattr(sys.modules[__name__], '__generators') for generator in generators: if generator.can_generate_target_from_instance(instance=instance): print('UMM using generator "{0}" for instance "{1}".'.format(generator, instance)) return generator.generate_target_from_instance(instance=instance)
3,695
Python
40.066666
149
0.696076
NVIDIA-Omniverse/blender_omniverse_addons/omni/universalmaterialmap/core/generator/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
858
Python
44.210524
74
0.7331
NVIDIA-Omniverse/blender_omniverse_addons/omni/universalmaterialmap/core/generator/core.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. from abc import ABCMeta, abstractmethod import typing from ..data import Library, Target class IGenerator(metaclass=ABCMeta): """ """ @abstractmethod def __init__(self): super(IGenerator, self).__init__() @abstractmethod def can_generate_target(self, class_name: str) -> bool: """ """ pass @abstractmethod def generate_target(self, class_name: str) -> typing.Tuple[Library, Target]: """ """ pass @abstractmethod def can_generate_targets(self) -> bool: """ """ pass @abstractmethod def generate_targets(self) -> typing.List[typing.Tuple[Library, Target]]: """ """ pass @abstractmethod def can_generate_target_from_instance(self, instance: object) -> bool: """ """ pass @abstractmethod def generate_target_from_instance(self, instance: object) -> typing.Tuple[Library, Target]: """ """ pass
1,823
Python
27.952381
95
0.656061
NVIDIA-Omniverse/blender_omniverse_addons/omni/universalmaterialmap/core/converter/util.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. """ Convert Queries & Actions ######################### DCC Connectors and other conversion solutions will want to use this module. There are three different conversion strategies available: 1. Source *class* and *data*. The framework finds a suitable conversion template and returns data indicating a *target class* and data for setting its attributes. For example: .. code:: from omni.universalmaterialmap.core.converter import util if util.can_convert_data_to_data( class_name='lambert', render_context='MDL', source_data=[ ('color', 'color_texture.png'), ('normalCamera', 'normal_texture.png') ]): data = util.convert_data_to_data( class_name='lambert', render_context='MDL', source_data=[ ('color', 'color_texture.png'), ('normalCamera', 'normal_texture.png') ] ) ...could return: .. code:: [ ('umm_target_class', 'omnipbr'), ('diffuse_texture', 'color_texture.png'), ('normalmap_texture', 'normal_texture.png'), ] Note that the first value pair :code:`('umm_target_class', 'omnipbr')` indicates the object class that should be used for conversion. All other value pairs indicate attribute names and attribute values. Using this strategy puts very little responsibility on the conversion workers to understand assets. They merely have to apply the arguments to a conversion template, compute the internal graph, and spit out the results. It also means that the solution invoking the converter will have to gather the necessary arguments from some object or data source. 2. Source *instance* into conversion data. Here we use an object instance in order to get the same data as in strategy #1 above. For example: .. code:: from omni.universalmaterialmap.core.converter import util if util.can_convert_instance( instance=MyLambertPyNode, render_context='MDL'): data = util.convert_instance_to_data( instance=MyLambertPyNode, render_context='MDL' ) ...could return: .. code:: [ ('umm_target_class', 'omnipbr'), ('diffuse_texture', 'color_texture.png'), ('normalmap_texture', 'normal_texture.png'), ] Note that the first value pair :code:`('umm_target_class', 'omnipbr')` indicates the object class that should be used for conversion. All other value pairs indicate attribute names and attribute values. The advantage here is that the user of the framework can rely on a converter's understanding of objects and attributes. The downside is that there has to be an actual asset or dependency graph loaded. 3. Source *instance* into converted object. In this approach the converter will create a new object and set its properties/attributes based on a conversion template. For example: .. code:: from omni.universalmaterialmap.core.converter import util if util.can_convert_instance( instance=MyLambertPyNode, render_context='MDL'): node = util.convert_instance_to_instance( instance=MyLambertPyNode, render_context='MDL' ) ...could create and return an MDL material in the current Maya scene. Manifest Query ############## Module has methods for querying its conversion capabilities as indicated by library manifests. This could be useful when wanting to expose commands for converting assets within a DCC application scene. Note that this API does not require any data or object instance argument. It's a more *general* query. .. code:: from omni.universalmaterialmap.core.converter import util manifest = util.get_conversion_manifest() # Returns data indicating what source class can be converted to a render context. # # Example: # [ # ('lambert', 'MDL'), # ('blinn', 'MDL'), # ] if (my_class_name, 'MDL') in manifest: # Do something """ import sys import typing import traceback from .. import data from .core import ICoreConverter, IDataConverter, IObjectConverter _debug_mode = False __converters: typing.List['ICoreConverter'] = [] TARGET_CLASS_IDENTIFIER = 'umm_target_class' def register(converter: ICoreConverter) -> typing.NoReturn: """ Registers the converter at the top of the internal list - overriding previously registered converters - for future queries and processes. """ converters = getattr(sys.modules[__name__], '__converters') if converter not in converters: if _debug_mode: print('UMM: core.converter.util: Registering converter: "{0}"'.format(converter)) converters.insert(0, converter) elif _debug_mode: print('UMM: core.converter.util: Not registering converter because it is already registered: "{0}"'.format(converter)) def un_register(converter: ICoreConverter) -> typing.NoReturn: """ Removes the converter from internal list of converters and will ignore it for future queries and processes. """ converters = getattr(sys.modules[__name__], '__converters') if converter in converters: if _debug_mode: print('UMM: core.converter.util: un-registering converter: "{0}"'.format(converter)) converters.remove(converter) elif _debug_mode: print('UMM: core.converter.util: Not un-registering converter because it not registered to begin with: "{0}"'.format(converter)) def can_create_instance(class_name: str) -> bool: """ Resolves if a converter can create a node. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_create_instance(class_name=class_name): if _debug_mode: print('UMM: core.converter.util: converter can create instance: "{0}"'.format(converter)) return True if _debug_mode: print('UMM: core.converter.util: no converter can create instance.') return False def create_instance(class_name: str) -> object: """ Creates an asset using the first converter in the internal list that supports the class_name. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_create_instance(class_name=class_name): if _debug_mode: print('UMM: core.converter.util: converter creating instance: "{0}"'.format(converter)) return converter.create_instance(class_name=class_name) raise Exception('Registered converters does not support class "{0}".'.format(class_name)) def can_set_plug_value(instance: object, plug: data.Plug) -> bool: """ Resolves if a converter can set the plug's value given the instance and its attributes. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if _debug_mode: print('UMM: core.converter.util: converter can set plug value: "{0}"'.format(converter)) if converter.can_set_plug_value(instance=instance, plug=plug): return True if _debug_mode: print('UMM: core.converter.util: converter cannot set plug value given instance "{0}" and plug "{1}"'.format(instance, plug)) return False def set_plug_value(instance: object, plug: data.Plug) -> typing.NoReturn: """ Sets the plug's value given the value of the instance's attribute named the same as the plug. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_set_plug_value(instance=instance, plug=plug): if _debug_mode: print('UMM: core.converter.util: converter setting plug value: "{0}"'.format(converter)) return converter.set_plug_value(instance=instance, plug=plug) raise Exception('Registered converters does not support action.') def can_set_instance_attribute(instance: object, name: str) -> bool: """ Resolves if a converter can set an attribute by the given name on the instance. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if _debug_mode: print('UMM: core.converter.util: converter can set instance attribute: "{0}", "{1}", "{2}"'.format(converter, instance, name)) if converter.can_set_instance_attribute(instance=instance, name=name): return True if _debug_mode: print('UMM: core.converter.util: cannot set instance attribute: "{0}", "{1}"'.format(instance, name)) return False def set_instance_attribute(instance: object, name: str, value: typing.Any) -> typing.NoReturn: """ Sets the named attribute on the instance to the value. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_set_instance_attribute(instance=instance, name=name): if _debug_mode: print('UMM: core.converter.util: converter setting instance attribute: "{0}", "{1}", "{2}", "{3}"'.format(converter, instance, name, value)) return converter.set_instance_attribute(instance=instance, name=name, value=value) raise Exception('Registered converters does not support action.') def can_convert_instance(instance: object, render_context: str) -> bool: """ Resolves if a converter can convert the instance to another object given the render_context. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if _debug_mode: print('UMM: core.converter.util: converter can convert instance: "{0}", "{1}", "{2}"'.format(converter, instance, render_context)) if converter.can_convert_instance(instance=instance, render_context=render_context): return True return False def convert_instance_to_instance(instance: object, render_context: str) -> typing.Any: """ Interprets the instance and instantiates another object given the render_context. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_convert_instance(instance=instance, render_context=render_context): if _debug_mode: print('UMM: core.converter.util: converter converting instance: "{0}", "{1}", "{2}"'.format(converter, instance, render_context)) return converter.convert_instance_to_instance(instance=instance, render_context=render_context) raise Exception('Registered converters does not support action.') def can_convert_instance_to_data(instance: object, render_context: str) -> bool: """ Resolves if a converter can convert the instance to another object given the render_context. """ try: converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_convert_instance_to_data(instance=instance, render_context=render_context): return True except Exception as error: print('Warning: Universal Material Map: function "can_convert_instance_to_data": Unexpected error:') print('\targument "instance" = "{0}"'.format(instance)) print('\targument "render_context" = "{0}"'.format(render_context)) print('\terror: {0}'.format(error)) print('\tcallstack: {0}'.format(traceback.format_exc())) return False def convert_instance_to_data(instance: object, render_context: str) -> typing.List[typing.Tuple[str, typing.Any]]: """ Returns a list of key value pairs in tuples. The first pair is ("umm_target_class", "the_class_name") indicating the conversion target class. """ try: converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_convert_instance_to_data(instance=instance, render_context=render_context): result = converter.convert_instance_to_data(instance=instance, render_context=render_context) print('Universal Material Map: convert_instance_to_data({0}, "{1}") generated data:'.format(instance, render_context)) print('\t(') for o in result: print('\t\t{0}'.format(o)) print('\t)') return result except Exception as error: print('Warning: Universal Material Map: function "convert_instance_to_data": Unexpected error:') print('\targument "instance" = "{0}"'.format(instance)) print('\targument "render_context" = "{0}"'.format(render_context)) print('\terror: {0}'.format(error)) print('\tcallstack: {0}'.format(traceback.format_exc())) result = dict() result['umm_notification'] = 'unexpected_error' result['message'] = 'Not able to convert "{0}" for render context "{1}" because there was an unexpected error. Details: {2}'.format(instance, render_context, error) return result raise Exception('Registered converters does not support action.') def can_convert_attribute_values(instance: object, render_context: str, destination: object) -> bool: """ Resolves if the instance's attribute values can be converted and set on the destination object's attributes. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_convert_attribute_values(instance=instance, render_context=render_context, destination=destination): return True return False def convert_attribute_values(instance: object, render_context: str, destination: object) -> typing.NoReturn: """ Attribute values are converted and set on the destination object's attributes. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_convert_attribute_values(instance=instance, render_context=render_context, destination=destination): return converter.convert_attribute_values(instance=instance, render_context=render_context, destination=destination) raise Exception('Registered converters does not support action.') def can_convert_data_to_data(class_name: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]]) -> bool: """ Resolves if a converter can convert the given class and source_data to another class and target data. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IDataConverter): if converter.can_convert_data_to_data(class_name=class_name, render_context=render_context, source_data=source_data): return True return False def convert_data_to_data(class_name: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]]) -> typing.List[typing.Tuple[str, typing.Any]]: """ Returns a list of key value pairs in tuples. The first pair is ("umm_target_class", "the_class_name") indicating the conversion target class. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IDataConverter): if converter.can_convert_data_to_data(class_name=class_name, render_context=render_context, source_data=source_data): result = converter.convert_data_to_data(class_name=class_name, render_context=render_context, source_data=source_data) print('Universal Material Map: convert_data_to_data("{0}", "{1}") generated data:'.format(class_name, render_context)) print('\t(') for o in result: print('\t\t{0}'.format(o)) print('\t)') return result raise Exception('Registered converters does not support action.') def can_apply_data_to_instance(source_class_name: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]], instance: object) -> bool: """ Resolves if a converter can create one or more instances given the arguments. """ converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_apply_data_to_instance(source_class_name=source_class_name, render_context=render_context, source_data=source_data, instance=instance): return True return False def apply_data_to_instance(source_class_name: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]], instance: object) -> dict: """ Returns a list of created objects. """ try: converters = getattr(sys.modules[__name__], '__converters') for converter in converters: if isinstance(converter, IObjectConverter): if converter.can_apply_data_to_instance(source_class_name=source_class_name, render_context=render_context, source_data=source_data, instance=instance): converter.apply_data_to_instance(source_class_name=source_class_name, render_context=render_context, source_data=source_data, instance=instance) print('Universal Material Map: apply_data_to_instance("{0}", "{1}") completed.'.format(instance, render_context)) result = dict() result['umm_notification'] = 'success' result['message'] = 'Material conversion data applied to "{0}".'.format(instance) return result result = dict() result['umm_notification'] = 'incomplete_process' result['message'] = 'Not able to convert type "{0}" for render context "{1}" because there is no Conversion Graph for that scenario. No changes were applied to "{2}".'.format(source_class_name, render_context, instance) return result except Exception as error: print('UMM: Unexpected error: {0}'.format(traceback.format_exc())) result = dict() result['umm_notification'] = 'unexpected_error' result['message'] = 'Not able to convert type "{0}" for render context "{1}" because there was an unexpected error. Some changes may have been applied to "{2}". Details: {3}'.format(source_class_name, render_context, instance, error) return result def get_conversion_manifest() -> typing.List[typing.Tuple[str, str]]: """ Returns data indicating what source class can be converted to a render context. Example: [('lambert', 'MDL'), ('blinn', 'MDL'),] """ manifest: typing.List[typing.Tuple[str, str]] = [] converters = getattr(sys.modules[__name__], '__converters') for converter in converters: manifest.extend(converter.get_conversion_manifest()) return manifest
20,886
Python
47.687646
241
0.655559
NVIDIA-Omniverse/blender_omniverse_addons/omni/universalmaterialmap/core/converter/__init__.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
858
Python
44.210524
74
0.7331
NVIDIA-Omniverse/blender_omniverse_addons/omni/universalmaterialmap/core/converter/core.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. from abc import ABCMeta, abstractmethod import typing from ..data import Plug class ICoreConverter(metaclass=ABCMeta): """ """ @abstractmethod def __init__(self): super(ICoreConverter, self).__init__() @abstractmethod def get_conversion_manifest(self) -> typing.List[typing.Tuple[str, str]]: """ Returns data indicating what source class can be converted to a render context. Example: [('lambert', 'MDL'), ('blinn', 'MDL'),] """ raise NotImplementedError() class IObjectConverter(ICoreConverter): """ """ @abstractmethod def can_create_instance(self, class_name: str) -> bool: """ Returns true if worker can generate an object of the given class name. """ raise NotImplementedError() @abstractmethod def create_instance(self, class_name: str) -> object: """ Creates an object of the given class name. """ raise NotImplementedError() @abstractmethod def can_set_plug_value(self, instance: object, plug: Plug) -> bool: """ Returns true if worker can set the plug's value given the instance and its attributes. """ raise NotImplementedError() @abstractmethod def set_plug_value(self, instance: object, plug: Plug) -> typing.NoReturn: """ Sets the plug's value given the value of the instance's attribute named the same as the plug. """ raise NotImplementedError() @abstractmethod def can_set_instance_attribute(self, instance: object, name: str): """ Resolves if worker can set an attribute by the given name on the instance. """ return False @abstractmethod def set_instance_attribute(self, instance: object, name: str, value: typing.Any) -> typing.NoReturn: """ Sets the named attribute on the instance to the value. """ raise NotImplementedError() @abstractmethod def can_convert_instance(self, instance: object, render_context: str) -> bool: """ Resolves if worker can convert the instance to another object given the render_context. """ return False @abstractmethod def convert_instance_to_instance(self, instance: object, render_context: str) -> typing.Any: """ Converts the instance to another object given the render_context. """ raise NotImplementedError() @abstractmethod def can_convert_instance_to_data(self, instance: object, render_context: str) -> bool: """ Resolves if worker can convert the instance to another object given the render_context. """ return False @abstractmethod def convert_instance_to_data(self, instance: object, render_context: str) -> typing.List[typing.Tuple[str, typing.Any]]: """ Returns a list of key value pairs in tuples. The first pair is ("umm_target_class", "the_class_name") indicating the conversion target class. """ raise NotImplementedError() @abstractmethod def can_convert_attribute_values(self, instance: object, render_context: str, destination: object) -> bool: """ Resolves if the instance's attribute values can be converted and set on the destination object's attributes. """ raise NotImplementedError() @abstractmethod def convert_attribute_values(self, instance: object, render_context: str, destination: object) -> typing.NoReturn: """ Attribute values are converted and set on the destination object's attributes. """ raise NotImplementedError() @abstractmethod def can_apply_data_to_instance(self, source_class_name: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]], instance: object) -> bool: """ Resolves if worker can convert the instance to another object given the render_context. """ return False @abstractmethod def apply_data_to_instance(self, source_class_name: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]], instance: object) -> dict: """ Returns a notification object Examples: { 'umm_notification': "success", 'message': "Material \"Material_A\" was successfully converted from \"OmniPBR\" data." } { 'umm_notification': "incomplete_process", 'message': "Not able to convert \"Material_B\" using \"CustomMDL\" since there is no Conversion Graph supporting that scenario." } { 'umm_notification': "unexpected_error", 'message': "Not able to convert \"Material_C\" using \"OmniGlass\" due to an unexpected error. Details: \"cannot set property to None\"." } """ raise NotImplementedError() class IDataConverter(ICoreConverter): """ """ @abstractmethod def can_convert_data_to_data(self, class_name: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]]) -> bool: """ Resolves if worker can convert the given class and source_data to another class and target data. """ return False @abstractmethod def convert_data_to_data(self, class_name: str, render_context: str, source_data: typing.List[typing.Tuple[str, typing.Any]]) -> typing.List[typing.Tuple[str, typing.Any]]: """ Returns a list of key value pairs in tuples. The first pair is ("umm_target_class", "the_class_name") indicating the conversion target class. """ raise NotImplementedError()
6,404
Python
40.590909
176
0.665209
NVIDIA-Omniverse/blender_omniverse_addons/omni/universalmaterialmap/core/service/store.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import typing import os import uuid import traceback from .. import data from .. import operator from ..feature import POLLING from ..singleton import Singleton from .core import ChangeEvent, IDelegate from .delegate import Filesystem, FilesystemManifest, FilesystemSettings from .resources import install COMMON_LIBRARY_ID = '327ef29b-8358-441b-b2f0-4a16a9afd349' libraries_directory = os.path.expanduser('~').replace('\\', '/') if not libraries_directory.endswith('/Documents'): # os.path.expanduser() has different behaviour between 2.7 and 3 libraries_directory = '{0}/Documents'.format(libraries_directory) libraries_directory = '{0}/Omniverse'.format(libraries_directory) common_library_directory = '{0}/ConnectorCommon/UMMLibrary'.format(libraries_directory) cache_directory = '{0}/Cache'.format(common_library_directory) COMMON_LIBRARY = data.Library.Create( library_id=COMMON_LIBRARY_ID, name='Common', manifest=FilesystemManifest(root_directory='{0}'.format(common_library_directory)), conversion_graph=Filesystem(root_directory='{0}/ConversionGraph'.format(common_library_directory)), target=Filesystem(root_directory='{0}/Target'.format(common_library_directory)), settings=FilesystemSettings(root_directory='{0}'.format(common_library_directory)), ) DEFAULT_LIBRARIES = [COMMON_LIBRARY] class _ItemProvider(object): """ Class provides IO interface for a single UMM Library item. """ def __init__(self, identifier: str, library_delegate: IDelegate = None, cache_delegate: IDelegate = None): super(_ItemProvider, self).__init__() self._library_delegate: typing.Union[IDelegate, typing.NoReturn] = library_delegate self._cache_delegate: typing.Union[IDelegate, typing.NoReturn] = cache_delegate self._identifier: str = identifier self._file_util: typing.Union[data.FileUtility, typing.NoReturn] = None self._content_cache: dict = dict() def revert(self) -> None: if self._file_util: self._file_util.content.deserialize(data=self._content_cache) def has_unsaved_changes(self) -> bool: if not self._file_util: return False return not self._file_util.content.serialize() == self._content_cache def read(self, update: bool = False) -> None: """ TODO: Check if path has changed since last read from disk. """ if not self._library_delegate and not self._cache_delegate: raise Exception('Not supported: No delegate available to read().') # update_cache() assumes that read() prioritizes reading with library delegate! delegate = self._library_delegate if self._library_delegate else self._cache_delegate if not self._file_util: contents = delegate.read(identifier=self._identifier) if contents is not None: self._file_util = data.FileUtility.FromData(data=contents) self._update_content_cache() elif update: contents = delegate.read(identifier=self._identifier) self._file_util.content.deserialize(data=contents) def create(self, instance: data.Serializable) -> None: self._file_util = data.FileUtility.FromInstance(instance=instance) self.write() def write(self, content: data.Serializable = None) -> None: if not self._library_delegate and not self._cache_delegate: raise Exception('Not supported: No delegate available to write().') if content: if not self._file_util: self._file_util = data.FileUtility.FromInstance(instance=content) else: self._file_util._content = content elif not self._file_util: raise Exception('Not supported: _ItemProvider not initialized properly prior to "write()"') contents = self._file_util.serialize() if self._library_delegate: self._library_delegate.write(identifier=self._identifier, contents=contents) if self._cache_delegate: self._cache_delegate.write(identifier=self._identifier, contents=contents) self._update_content_cache() def delete(self) -> None: if not self._library_delegate and not self._cache_delegate: raise Exception('Not supported: No delegate available to delete().') if self._library_delegate: self._library_delegate.delete(identifier=self._identifier) if self._cache_delegate: self._cache_delegate.delete(identifier=self._identifier) self._file_util = None self._content_cache = None def _update_content_cache(self) -> None: if not self._file_util: self._content_cache = dict() else: self._content_cache = self._file_util.content.serialize() def update_cache(self) -> bool: if not self._library_delegate or not self._cache_delegate: return False # Assumes that read() prioritizes reading with library delegate! try: self.read() except Exception as error: print('Warning: Universal Material Map error reading data with identifier "{0}". Cache will not be updated due to the read error.\n\tDetails: "{1}".\n\tCallstack: {2}'.format(self._identifier, error, traceback.format_exc())) return False self._cache_delegate.write(identifier=self._identifier, contents=self._file_util.serialize()) def on_shutdown(self): self._cache_delegate = None self._library_delegate = None self._identifier = None self._file_util = None self._content_cache = None @property def content(self) -> data.Serializable: return self._file_util.content class _LibraryProvider(object): """ Class provides IO interface for a single UMM Library. """ @staticmethod def _transfer_data(source: IDelegate, target: IDelegate) -> bool: """ Returns True if transfer was made. """ if not source or not target: return False for identifier in source.get_ids(): target.write(identifier=identifier, contents=source.read(identifier=identifier)) return True def __init__(self, library: data.Library): super(_LibraryProvider, self).__init__() self._library: data.Library = library if POLLING: self._manifest_subscription: uuid.uuid4 = None self._conversion_graph_subscription: uuid.uuid4 = None self._target_subscription: uuid.uuid4 = None self._manifest_cache: typing.Union[IDelegate, typing.NoReturn] = None self._conversion_graph_cache: typing.Union[IDelegate, typing.NoReturn] = None self._target_cache: typing.Union[IDelegate, typing.NoReturn] = None self._settings_cache: typing.Union[IDelegate, typing.NoReturn] = None self._manifest_providers: typing.Dict[str, _ItemProvider] = dict() self._conversion_graph_providers: typing.Dict[str, _ItemProvider] = dict() self._target_providers: typing.Dict[str, _ItemProvider] = dict() self._settings_providers: typing.Dict[str, _ItemProvider] = dict() self._initialize() def _initialize(self) -> None: cache: _ItemProvider for cache in self._manifest_providers.values(): cache.on_shutdown() for cache in self._conversion_graph_providers.values(): cache.on_shutdown() for cache in self._target_providers.values(): cache.on_shutdown() for cache in self._settings_providers.values(): cache.on_shutdown() self._manifest_providers = dict() self._conversion_graph_providers = dict() self._target_providers = dict() self._settings_providers = dict() if not self._library: return if not self._library.id == COMMON_LIBRARY_ID: self._manifest_cache = FilesystemManifest( root_directory='{0}/{1}'.format(cache_directory, self._library.id) ) self._conversion_graph_cache = Filesystem( root_directory='{0}/{1}/ConversionGraph'.format(cache_directory, self._library.id) ) self._target_cache = Filesystem( root_directory='{0}/{1}/Target'.format(cache_directory, self._library.id) ) self._settings_cache = FilesystemSettings( root_directory='{0}/{1}'.format(cache_directory, self._library.id) ) if not self._library.id == COMMON_LIBRARY_ID and not self._library.is_read_only: self._update_cache() def _update_cache(self) -> None: if self._library.is_read_only: return self._update_cache_table( source=self._library.manifest, target=self._manifest_cache, providers=self._manifest_providers, ) self._update_cache_table( source=self._library.conversion_graph, target=self._conversion_graph_cache, providers=self._conversion_graph_providers, ) self._update_cache_table( source=self._library.target, target=self._target_cache, providers=self._target_providers, ) self._update_cache_table( source=self._library.settings, target=self._settings_cache, providers=self._settings_providers, ) def _update_cache_table(self, source: IDelegate, target: IDelegate, providers: dict) -> None: if self._library.is_read_only: return if not source or not target: return for identifier in source.get_ids(): if identifier not in providers.keys(): provider = _ItemProvider( identifier=identifier, library_delegate=source, cache_delegate=target ) providers[identifier] = provider else: provider = providers[identifier] provider.update_cache() def get_settings(self) -> typing.List[data.Settings]: if not self._library.settings: return [] settings: typing.List[data.Settings] = [] for identifier in self._library.settings.get_ids(): if identifier not in self._settings_providers.keys(): cache = _ItemProvider( identifier=identifier, library_delegate=self._library.settings, cache_delegate=self._settings_cache ) self._settings_providers[identifier] = cache else: cache = self._settings_providers[identifier] cache.read() setting = typing.cast(data.Settings, cache.content) settings.append(setting) return settings def get_manifests(self) -> typing.List[data.ConversionManifest]: delegate = self._library.manifest if self._library.manifest else self._manifest_cache if not delegate: return [] manifests: typing.List[data.ConversionManifest] = [] conversion_graphs: typing.List[data.ConversionGraph] = None for identifier in delegate.get_ids(): if identifier not in self._manifest_providers.keys(): cache = _ItemProvider( identifier=identifier, library_delegate=self._library.manifest, cache_delegate=self._manifest_cache ) self._manifest_providers[identifier] = cache else: cache = self._manifest_providers[identifier] cache.read() manifest = typing.cast(data.ConversionManifest, cache.content) if not conversion_graphs: conversion_graphs = self.get_conversion_graphs() for item in manifest.conversion_maps: if not item._conversion_graph: for conversion_graph in conversion_graphs: if conversion_graph.id == item.conversion_graph_id: item._conversion_graph = conversion_graph break manifests.append(manifest) if POLLING: if self._library.manifest and not self._manifest_subscription: self._manifest_subscription = self._library.manifest.add_change_subscription(callback=self._on_store_manifest_changes) return manifests def get_conversion_graphs(self) -> typing.List[data.ConversionGraph]: delegate = self._library.conversion_graph if self._library.conversion_graph else self._conversion_graph_cache if not delegate: return [] conversion_graphs: typing.List[data.ConversionGraph] = [] for identifier in delegate.get_ids(): if identifier not in self._conversion_graph_providers.keys(): cache = _ItemProvider( identifier=identifier, library_delegate=self._library.conversion_graph, cache_delegate=self._conversion_graph_cache ) try: cache.read() except Exception as error: print('Warning: Universal Material Map error reading Conversion Graph data with identifier "{0}". Graph will not be available for use inside UMM.\n\tDetails: "{1}".\n\tCallstack: {2}'.format(identifier, error, traceback.format_exc())) continue self._conversion_graph_providers[identifier] = cache else: cache = self._conversion_graph_providers[identifier] try: cache.read() except Exception as error: print('Warning: Universal Material Map error reading Conversion Graph data with identifier "{0}". Graph will not be available for use inside UMM.\n\tDetails: "{1}".\n\tCallstack: {2}'.format(identifier, error, traceback.format_exc())) continue conversion_graph = typing.cast(data.ConversionGraph, cache.content) conversion_graph._library = self._library conversion_graph.filename = identifier conversion_graph._exists_on_disk = True conversion_graphs.append(conversion_graph) if POLLING: if self._library.conversion_graph and not self._conversion_graph_subscription: self._conversion_graph_subscription = self._library.conversion_graph.add_change_subscription(callback=self._on_store_conversion_graph_changes) return conversion_graphs def get_targets(self) -> typing.List[data.Target]: delegate = self._library.target if self._library.target else self._target_cache if not delegate: return [] targets: typing.List[data.Target] = [] for identifier in delegate.get_ids(): if identifier not in self._target_providers.keys(): cache = _ItemProvider( identifier=identifier, library_delegate=self._library.target, cache_delegate=self._target_cache ) self._target_providers[identifier] = cache else: cache = self._target_providers[identifier] cache.read() target = typing.cast(data.Target, cache.content) target.store_id = identifier targets.append(target) if POLLING: if self._library.target and not self._target_subscription: self._target_subscription = self._library.target.add_change_subscription(callback=self._on_store_target_changes) return targets def _on_store_manifest_changes(self, event: ChangeEvent) -> None: if not POLLING: raise NotImplementedError() print('_on_store_manifest_changes', event) def _on_store_conversion_graph_changes(self, event: ChangeEvent) -> None: if not POLLING: raise NotImplementedError() print('_on_store_conversion_graph_changes', event) def _on_store_target_changes(self, event: ChangeEvent) -> None: if not POLLING: raise NotImplementedError() print('_on_store_target_changes...', event, self) def revert(self, item: data.Serializable) -> bool: """ Returns True if the item existed in a data store and was successfully reverted. """ if isinstance(item, data.ConversionGraph): if item.filename not in self._conversion_graph_providers.keys(): return False filename = item.filename library = item.library cache = self._conversion_graph_providers[item.filename] cache.revert() item.filename = filename item._library = library item._exists_on_disk = True return True if isinstance(item, data.Target): if item.store_id not in self._target_providers.keys(): return False cache = self._target_providers[item.store_id] cache.revert() return True if isinstance(item, data.ConversionManifest): if item.store_id not in self._manifest_providers.keys(): return False cache = self._manifest_providers[item.store_id] cache.revert() return True if isinstance(item, data.Settings): if item.store_id not in self._settings_providers.keys(): return False cache = self._settings_providers[item.store_id] cache.revert() return True def write(self, item: data.Serializable, identifier: str = None, overwrite: bool = False) -> None: if isinstance(item, data.Settings): if not item.store_id: raise Exception('Not supported: Settings must have a valid store id in order to write the item.') if not self._library.settings: raise Exception('Library "{0}" with id="{1}" does not support a Settings store.'.format(self._library.name, self._library.id)) if item.store_id not in self._settings_providers.keys(): cache = _ItemProvider( identifier=item.store_id, library_delegate=self._library.settings, cache_delegate=self._settings_cache ) self._settings_providers[item.store_id] = cache else: if not overwrite: return cache = self._settings_providers[item.store_id] cache.write(content=item) return if isinstance(item, data.ConversionManifest): if not item.store_id: raise Exception('Not supported: Conversion Manifest must have a valid store id in order to write the item.') if item.store_id not in self._manifest_providers.keys(): cache = _ItemProvider( identifier=item.store_id, library_delegate=self._library.manifest, cache_delegate=self._manifest_cache ) self._manifest_providers[item.store_id] = cache else: if not overwrite: return cache = self._manifest_providers[item.store_id] cache.write(content=item) return if isinstance(item, data.ConversionGraph): if not item.filename and not identifier: raise Exception('Not supported: Conversion Manifest must have a valid store id in order to write the item.') key = identifier if identifier else item.filename if key not in self._conversion_graph_providers.keys(): cache = _ItemProvider( identifier=key, library_delegate=self._library.conversion_graph, cache_delegate=self._conversion_graph_cache ) self._conversion_graph_providers[key] = cache else: if not overwrite: return cache = self._conversion_graph_providers[key] item.revision += 1 cache.write(content=item) if identifier: item.filename = identifier item._exists_on_disk = True item._library = self._library return if isinstance(item, data.Target): if not item.store_id: raise Exception( 'Not supported: Conversion Manifest must have a valid store id in order to write the item.') if item.store_id not in self._target_providers.keys(): cache = _ItemProvider( identifier=item.store_id, library_delegate=self._library.target, cache_delegate=self._target_cache ) self._target_providers[item.store_id] = cache else: if not overwrite: return cache = self._target_providers[item.store_id] cache.write(content=item) return raise NotImplementedError() def delete(self, item: data.Serializable) -> None: if isinstance(item, data.Settings): if not item.store_id: raise Exception('Not supported: Settings must have a valid store id in order to write the item.') if not self._library.settings: raise Exception('Library "{0}" with id="{1}" does not support a Settings store.'.format(self._library.name, self._library.id)) if item.store_id not in self._settings_providers.keys(): return cache = self._settings_providers[item.store_id] cache.delete() cache.on_shutdown() del self._settings_providers[item.store_id] return if isinstance(item, data.ConversionManifest): if not item.store_id: raise Exception('Not supported: Conversion Manifest must have a valid store id in order to write the item.') if item.store_id not in self._manifest_providers.keys(): return cache = self._manifest_providers[item.store_id] cache.delete() cache.on_shutdown() del self._manifest_providers[item.store_id] return if isinstance(item, data.ConversionGraph): if not item.filename: raise Exception('Not supported: Conversion Manifest must have a valid store id in order to write the item.') if item.filename not in self._conversion_graph_providers.keys(): return cache = self._conversion_graph_providers[item.filename] cache.delete() cache.on_shutdown() del self._conversion_graph_providers[item.filename] return if isinstance(item, data.Target): if not item.store_id: raise Exception( 'Not supported: Conversion Manifest must have a valid store id in order to write the item.') if item.store_id not in self._target_providers.keys(): return cache = self._target_providers[item.store_id] cache.write(content=item) cache.on_shutdown() del self._target_providers[item.store_id] return raise NotImplementedError() def can_show_in_store(self, item: data.Serializable) -> bool: if isinstance(item, data.ConversionGraph): delegate = self._library.conversion_graph if self._library.conversion_graph else self._conversion_graph_cache if not delegate: return False return delegate.can_show_in_store(identifier=item.filename) if isinstance(item, data.Target): delegate = self._library.target if self._library.target else self._target_cache if not delegate: return False return delegate.can_show_in_store(identifier=item.store_id) return False def show_in_store(self, item: data.Serializable) -> None: if isinstance(item, data.ConversionGraph): delegate = self._library.conversion_graph if self._library.conversion_graph else self._conversion_graph_cache if not delegate: return return delegate.show_in_store(identifier=item.filename) if isinstance(item, data.Target): delegate = self._library.target if self._library.target else self._target_cache if not delegate: return return delegate.show_in_store(identifier=item.store_id) @property def library(self) -> data.Library: return self._library @library.setter def library(self, value: data.Library) -> None: if self._library == value: return if POLLING: if self._library: if self._manifest_subscription and self._library.manifest: self._library.manifest.remove_change_subscription(subscription_id=self._manifest_subscription) if self._conversion_graph_subscription and self._library.conversion_graph: self._library.conversion_graph.remove_change_subscription(subscription_id=self._conversion_graph_subscription) if self._target_subscription and self._library.target: self._library.target.remove_change_subscription(subscription_id=self._target_subscription) self._library = value self._initialize() @Singleton class __Manager: def __init__(self): install() self._library_caches: typing.Dict[str, _LibraryProvider] = dict() self._operators: typing.List[data.Operator] = [ operator.And(), operator.Add(), operator.BooleanSwitch(), operator.ColorSpaceResolver(), operator.ConstantBoolean(), operator.ConstantFloat(), operator.ConstantInteger(), operator.ConstantRGB(), operator.ConstantRGBA(), operator.ConstantString(), operator.Equal(), operator.GreaterThan(), operator.LessThan(), operator.ListGenerator(), operator.ListIndex(), operator.MayaTransparencyResolver(), operator.MergeRGB(), operator.MergeRGBA(), operator.MDLColorSpace(), operator.MDLTextureResolver(), operator.Multiply(), operator.Not(), operator.Or(), operator.Remap(), operator.SplitRGB(), operator.SplitRGBA(), operator.SplitTextureData(), operator.Subtract(), operator.ValueResolver(), operator.ValueTest(), ] for o in self._operators: if len([item for item in self._operators if item.id == o.id]) == 1: continue raise Exception('Operator id "{0}" is not unique.'.format(o.id)) provider = _LibraryProvider(library=COMMON_LIBRARY) self._library_caches[COMMON_LIBRARY_ID] = provider render_contexts = [ 'MDL', 'USDPreview', 'Blender', ] settings = provider.get_settings() if len(settings) == 0: self._settings: data.Settings = data.Settings() for render_context in render_contexts: self._settings.render_contexts.append(render_context) self._settings.render_contexts.append(render_context) self._save_settings() else: self._settings: data.Settings = settings[0] added_render_context = False for render_context in render_contexts: if render_context not in self._settings.render_contexts: self._settings.render_contexts.append(render_context) added_render_context = True if added_render_context: self._save_settings() for i in range(len(self._settings.libraries)): for library in DEFAULT_LIBRARIES: if self._settings.libraries[i].id == library.id: self._settings.libraries[i] = library break for library in DEFAULT_LIBRARIES: if len([o for o in self._settings.libraries if o.id == library.id]) == 0: self._settings.libraries.append(library) for library in self._settings.libraries: self.register_library(library=library) def _save_settings(self) -> None: if COMMON_LIBRARY_ID not in self._library_caches.keys(): raise Exception('Not supported: Common library not in cache. Unable to save settings.') cache = self._library_caches[COMMON_LIBRARY_ID] cache.write(item=self._settings, identifier=None, overwrite=True) def register_library(self, library: data.Library) -> None: preferences_changed = False to_remove = [] for item in self._settings.libraries: if item.id == library.id: if not item == library: to_remove.append(item) for item in to_remove: self._settings.libraries.remove(item) preferences_changed = True if library not in self._settings.libraries: self._settings.libraries.append(library) preferences_changed = True if preferences_changed: self._save_settings() if library.id not in self._library_caches.keys(): self._library_caches[library.id] = _LibraryProvider(library=library) else: cache = self._library_caches[library.id] cache.library = library def register_render_contexts(self, context: str) -> None: """Register a render context such as MDL or USD Preview.""" if context not in self._settings.render_contexts: self._settings.render_contexts.append(context) self._save_settings() def get_assembly(self, reference: data.TargetInstance) -> typing.Union[data.Target, None]: cache: _LibraryProvider for cache in self._library_caches.values(): for target in cache.get_targets(): if target.id == reference.target_id: return target return None def get_assemblies(self, library: data.Library = None) -> typing.List[data.Target]: if library: if library.id not in self._library_caches.keys(): return [] cache = self._library_caches[library.id] return cache.get_targets() targets: typing.List[data.Target] = [] cache: _LibraryProvider for cache in self._library_caches.values(): targets.extend(cache.get_targets()) return targets def get_documents(self, library: data.Library = None) -> typing.List[data.ConversionGraph]: conversion_graphs: typing.List[data.ConversionGraph] = [] if library: if library.id not in self._library_caches.keys(): return [] cache = self._library_caches[library.id] conversion_graphs = cache.get_conversion_graphs() else: cache: _LibraryProvider for cache in self._library_caches.values(): conversion_graphs.extend(cache.get_conversion_graphs()) for conversion_graph in conversion_graphs: self._completed_document_serialization(conversion_graph=conversion_graph) return conversion_graphs def get_document(self, library: data.Library, document_filename: str) -> typing.Union[data.ConversionGraph, typing.NoReturn]: if library.id not in self._library_caches.keys(): return None cache = self._library_caches[library.id] for conversion_graph in cache.get_conversion_graphs(): if conversion_graph.filename == document_filename: self._completed_document_serialization(conversion_graph=conversion_graph) return conversion_graph return None def can_show_in_filesystem(self, document: data.ConversionGraph) -> bool: if not document.library: return False if document.library.id not in self._library_caches.keys(): return False cache = self._library_caches[document.library.id] return cache.can_show_in_store(item=document) def show_in_filesystem(self, document: data.ConversionGraph) -> None: if not document.library: return if document.library.id not in self._library_caches.keys(): return cache = self._library_caches[document.library.id] cache.show_in_store(item=document) def get_document_by_id(self, library: data.Library, document_id: str) -> typing.Union[data.ConversionGraph, typing.NoReturn]: for conversion_graph in self.get_documents(library=library): if conversion_graph.id == document_id: return conversion_graph return None def create_new_document(self, library: data.Library) -> data.ConversionGraph: conversion_graph = data.ConversionGraph() conversion_graph._library = library conversion_graph.filename = '' self._completed_document_serialization(conversion_graph=conversion_graph) return conversion_graph def _completed_document_serialization(self, conversion_graph: data.ConversionGraph) -> None: build_dag = len(conversion_graph.target_instances) == 0 for reference in conversion_graph.target_instances: if reference.target and reference.target.id == reference.target_id: continue reference.target = self.get_assembly(reference=reference) build_dag = True if build_dag: conversion_graph.build_dag() def create_from_source(self, source: data.ConversionGraph) -> data.ConversionGraph: new_conversion_graph = data.ConversionGraph() new_id = new_conversion_graph.id new_conversion_graph.deserialize(data=source.serialize()) new_conversion_graph._id = new_id new_conversion_graph._library = source.library new_conversion_graph.filename = source.filename self._completed_document_serialization(conversion_graph=new_conversion_graph) return new_conversion_graph def revert(self, library: data.Library, instance: data.Serializable) -> bool: """ Returns True if the file existed on disk and was successfully reverted. """ if not library: return False if library.id not in self._library_caches.keys(): return False cache = self._library_caches[library.id] if cache.revert(item=instance): if isinstance(instance, data.ConversionGraph): self._completed_document_serialization(conversion_graph=instance) return True return False def find_documents(self, source_class: str, library: data.Library = None) -> typing.List[data.ConversionGraph]: conversion_graphs = [] for conversion_graph in self.get_documents(library=library): if not conversion_graph.source_node: continue for node in conversion_graph.source_node.target.nodes: if node.class_name == source_class: conversion_graphs.append(conversion_graph) return conversion_graphs def find_assembly(self, assembly_class: str, library: data.Library = None) -> typing.List[data.Target]: targets = [] for target in self.get_assemblies(library=library): for node in target.nodes: if node.class_name == assembly_class: targets.append(target) break return targets def _get_manifest_filepath(self, library: data.Library) -> str: return '{0}/ConversionManifest.json'.format(library.path) def get_conversion_manifest(self, library: data.Library) -> data.ConversionManifest: if library.id not in self._library_caches.keys(): return data.ConversionManifest() cache = self._library_caches[library.id] manifests = cache.get_manifests() if len(manifests): manifest = manifests[0] for conversion_map in manifest.conversion_maps: if conversion_map.conversion_graph is None: continue self._completed_document_serialization(conversion_graph=conversion_map.conversion_graph) return manifest return data.ConversionManifest() def save_conversion_manifest(self, library: data.Library, manifest: data.ConversionManifest) -> None: if library.id not in self._library_caches.keys(): return cache = self._library_caches[library.id] cache.write(item=manifest) def write(self, filename: str, instance: data.Serializable, library: data.Library, overwrite: bool = False) -> None: if not filename.strip(): raise Exception('Invalid filename: empty string.') if library.id not in self._library_caches.keys(): raise Exception('Cannot write to a library that is not registered') if not filename.lower().endswith('.json'): filename = '{0}.json'.format(filename) cache = self._library_caches[library.id] cache.write(item=instance, identifier=filename, overwrite=overwrite) def delete_document(self, document: data.ConversionGraph) -> bool: if not document.library: return False if document.library.id not in self._library_caches.keys(): return False cache = self._library_caches[document.library.id] cache.delete(item=document) return True def is_graph_entity_id(self, identifier: str) -> bool: for item in self.get_assemblies(): if item.id == identifier: return True return False def get_graph_entity(self, identifier: str) -> data.GraphEntity: for item in self.get_assemblies(): if item.id == identifier: return data.TargetInstance.FromAssembly(assembly=item) for item in self.get_operators(): if item.id == identifier: return data.OperatorInstance.FromOperator(operator=item) raise Exception('Graph Entity with id "{0}" cannot be found'.format(identifier)) def register_operator(self, operator: data.Operator): if operator not in self._operators: self._operators.append(operator) def get_operators(self) -> typing.List[data.Operator]: return self._operators def is_operator_id(self, identifier: str) -> bool: for item in self.get_operators(): if item.id == identifier: return True return False def on_shutdown(self): if len(self._library_caches.keys()): provider: _LibraryProvider for provider in self._library_caches.values(): provider.library = None self._library_caches = dict() @property def libraries(self) -> typing.List[data.Library]: return self._settings.libraries def register_library(library: data.Library) -> None: """ """ __Manager().register_library(library=library) def get_libraries() -> typing.List[data.Library]: """ """ return __Manager().libraries def get_library(library_id: str) -> data.Library: """ """ for library in __Manager().libraries: if library.id == library_id: return library raise Exception('Library with id "{0}" not found.'.format(library_id)) def get_assembly(reference: data.TargetInstance) -> data.Target: """ """ # TODO: Is this still needed? return __Manager().get_assembly(reference=reference) def write(filename: str, instance: data.Serializable, library: data.Library, overwrite: bool = False) -> None: """ """ __Manager().write(filename=filename, instance=instance, library=library, overwrite=overwrite) def get_assemblies(library: data.Library = None) -> typing.List[data.Target]: """ """ return __Manager().get_assemblies(library=library) def is_graph_entity_id(identifier: str) -> bool: """ """ return __Manager().is_graph_entity_id(identifier=identifier) def get_graph_entity(identifier: str) -> data.GraphEntity: """ """ return __Manager().get_graph_entity(identifier=identifier) def get_documents(library: data.Library = None) -> typing.List[data.ConversionGraph]: """ """ return __Manager().get_documents(library=library) def get_document(library: data.Library, document_filename: str) -> typing.Union[data.ConversionGraph, typing.NoReturn]: """ """ # TODO: Is this still needed? return __Manager().get_document(library=library, document_filename=document_filename) def create_new_document(library: data.Library) -> data.ConversionGraph: """ """ return __Manager().create_new_document(library=library) def create_from_source(source: data.ConversionGraph) -> data.ConversionGraph: """ """ return __Manager().create_from_source(source=source) def revert(library: data.Library, instance: data.Serializable) -> bool: """ Returns True if the file existed on disk and was successfully reverted. """ return __Manager().revert(library, instance) def find_documents(source_class: str, library: data.Library = None) -> typing.List[data.ConversionGraph]: """ """ # TODO: Is this still needed? return __Manager().find_documents(source_class=source_class, library=library) def find_assembly(assembly_class: str, library: data.Library = None) -> typing.List[data.Target]: """ """ # TODO: Is this still needed? return __Manager().find_assembly(assembly_class=assembly_class, library=library) def register_operator(operator: data.Operator): """ """ __Manager().register_operator(operator=operator) def get_operators() -> typing.List[data.Operator]: """ """ return __Manager().get_operators() def is_operator_id(identifier: str) -> bool: """ """ return __Manager().is_operator_id(identifier=identifier) def delete_document(document: data.ConversionGraph) -> bool: """ """ return __Manager().delete_document(document=document) def get_conversion_manifest(library: data.Library) -> data.ConversionManifest: """ """ return __Manager().get_conversion_manifest(library=library) def get_render_contexts() -> typing.List[str]: """Returns list of registered render contexts.""" return __Manager()._settings.render_contexts[:] def register_render_contexts(context: str) -> None: """Register a render context such as MDL or USD Preview.""" __Manager().register_render_contexts(context=context) def can_show_in_filesystem(document: data.ConversionGraph) -> bool: """Checks if the operating system can display where a document is saved on disk.""" return __Manager().can_show_in_filesystem(document=document) def show_in_filesystem(document: data.ConversionGraph) -> None: """Makes the operating system display where a document is saved on disk.""" return __Manager().show_in_filesystem(document=document) def on_shutdown() -> None: """Makes the operating system display where a document is saved on disk.""" return __Manager().on_shutdown()
44,912
Python
38.60582
254
0.614557
NVIDIA-Omniverse/blender_omniverse_addons/omni/universalmaterialmap/core/service/delegate.py
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. import typing import os import json import subprocess import threading import platform import uuid from ..feature import POLLING from .core import ChangeEvent, IDelegate class Filesystem(IDelegate): def __init__(self, root_directory: str): super(Filesystem, self).__init__() if POLLING: self.__is_polling: bool = False self.__poll_timer: threading.Timer = None self.__poll_data: typing.Dict[str, float] = dict() self.__poll_subscriptions: typing.Dict[uuid.uuid4, typing.Callable[[ChangeEvent], typing.NoReturn]] = dict() self.__pending_write_ids: typing.List[str] = [] self.__pending_delete_ids: typing.List[str] = [] self._root_directory: str = root_directory def __start_polling(self) -> None: if not POLLING: return if self.__is_polling: return self.__is_polling = True # Store current state in self.__poll_data so that __on_timer we only notify of changes since starting to poll self.__poll_data = dict() self.__pending_change_ids = [] identifiers = self.get_ids() for identifier in identifiers: filepath = '{0}/{1}'.format(self._root_directory, identifier) modified_time = os.path.getmtime(filepath) if platform.system() == 'Windows' else os.stat(filepath).st_mtime self.__poll_data[identifier] = modified_time self.__poll_timer = threading.Timer(5, self.__on_timer) self.__poll_timer.start() def __on_timer(self): print('UMM PING') if not POLLING: return if not self.__is_polling: return try: identifiers = self.get_ids() added = [o for o in identifiers if o not in self.__poll_data.keys() and o not in self.__pending_write_ids] removed = [o for o in self.__poll_data.keys() if o not in identifiers and o not in self.__pending_delete_ids] modified_maybe = [o for o in identifiers if o not in added and o not in removed and o not in self.__pending_write_ids] modified = [] for identifier in modified_maybe: filepath = '{0}/{1}'.format(self._root_directory, identifier) modified_time = os.path.getmtime(filepath) if platform.system() == 'Windows' else os.stat(filepath).st_mtime if self.__poll_data[identifier] == modified_time: continue modified.append(identifier) self.__poll_data[identifier] = modified_time for identifier in added: filepath = '{0}/{1}'.format(self._root_directory, identifier) self.__poll_data[identifier] = os.path.getmtime(filepath) if platform.system() == 'Windows' else os.stat(filepath).st_mtime for identifier in removed: del self.__poll_data[identifier] if len(added) + len(modified) + len(removed) > 0: event = ChangeEvent(added=tuple(added), modified=tuple(modified), removed=tuple(removed)) for callbacks in self.__poll_subscriptions.values(): callbacks(event) except Exception as error: print('WARNING: Universal Material Map failed to poll {0} for file changes.\nDetail: {1}'.format(self._root_directory, error)) self.__poll_timer.run() def __stop_polling(self) -> None: if not POLLING: return self.__is_polling = False try: self.__poll_timer.cancel() except: pass self.__poll_data = dict() def can_poll(self) -> bool: if not POLLING: return False return True def start_polling(self): if not POLLING: return self.__start_polling() def stop_polling(self): if not POLLING: return self.__stop_polling() def add_change_subscription(self, callback: typing.Callable[[ChangeEvent], typing.NoReturn]) -> uuid.uuid4: if not POLLING: raise NotImplementedError('Polling feature not enabled.') for key, value in self.__poll_subscriptions.items(): if value == callback: return key key = uuid.uuid4() self.__poll_subscriptions[key] = callback self.start_polling() return key def remove_change_subscription(self, subscription_id: uuid.uuid4) -> None: if not POLLING: raise NotImplementedError('Polling feature not enabled.') if subscription_id in self.__poll_subscriptions.keys(): del self.__poll_subscriptions[subscription_id] if len(self.__poll_subscriptions.keys()) == 0: self.stop_polling() def get_ids(self) -> typing.List[str]: identifiers: typing.List[str] = [] for directory, sub_directories, filenames in os.walk(self._root_directory): for filename in filenames: if not filename.lower().endswith('.json'): continue identifiers.append(filename) break return identifiers def read(self, identifier: str) -> typing.Union[typing.Dict, typing.NoReturn]: if not identifier.lower().endswith('.json'): raise Exception('Invalid identifier: "{0}" does not end with ".json".'.format(identifier)) filepath = '{0}/{1}'.format(self._root_directory, identifier) if os.path.exists(filepath): try: with open(filepath, 'r') as pointer: contents = json.load(pointer) if not isinstance(contents, dict): raise Exception('Not supported: Load of file "{0}" did not resolve to a dictionary. Could be due to reading same file twice too fast.'.format(filepath)) return contents except Exception as error: print('Failed to open file "{0}"'.format(filepath)) raise error return None def write(self, identifier: str, contents: typing.Dict) -> None: if not identifier.lower().endswith('.json'): raise Exception('Invalid identifier: "{0}" does not end with ".json".'.format(identifier)) if not isinstance(contents, dict): raise Exception('Not supported: Argument "contents" is not an instance of dict.') if not os.path.exists(self._root_directory): os.makedirs(self._root_directory) if POLLING: if identifier not in self.__pending_write_ids: self.__pending_write_ids.append(identifier) filepath = '{0}/{1}'.format(self._root_directory, identifier) with open(filepath, 'w') as pointer: json.dump(contents, pointer, indent=4) if POLLING: # Store the modified time so that we don't trigger a notification. We only want notifications when changes are caused by external modifiers. self.__poll_data[identifier] = os.path.getmtime(filepath) if platform.system() == 'Windows' else os.stat(filepath).st_mtime self.__pending_write_ids.remove(identifier) def delete(self, identifier: str) -> None: if not identifier.lower().endswith('.json'): raise Exception('Invalid identifier: "{0}" does not end with ".json".'.format(identifier)) if POLLING: if identifier not in self.__pending_delete_ids: self.__pending_delete_ids.append(identifier) filepath = '{0}/{1}'.format(self._root_directory, identifier) if os.path.exists(filepath): os.remove(filepath) if POLLING: # Remove the item from self.__poll_data so that we don't trigger a notification. We only want notifications when changes are caused by external modifiers. if identifier in self.__poll_data.keys(): del self.__poll_data[identifier] self.__pending_delete_ids.remove(identifier) def can_show_in_store(self, identifier: str) -> bool: filepath = '{0}/{1}'.format(self._root_directory, identifier) return os.path.exists(filepath) def show_in_store(self, identifier: str) -> None: filepath = '{0}/{1}'.format(self._root_directory, identifier) if os.path.exists(filepath): subprocess.Popen(r'explorer /select,"{0}"'.format(filepath.replace('/', '\\'))) class FilesystemManifest(Filesystem): def __init__(self, root_directory: str): super(FilesystemManifest, self).__init__(root_directory=root_directory) def get_ids(self) -> typing.List[str]: identifiers: typing.List[str] = [] for directory, sub_directories, filenames in os.walk(self._root_directory): for filename in filenames: if not filename.lower() == 'conversionmanifest.json': continue identifiers.append(filename) break return identifiers class FilesystemSettings(Filesystem): def __init__(self, root_directory: str): super(FilesystemSettings, self).__init__(root_directory=root_directory) def get_ids(self) -> typing.List[str]: identifiers: typing.List[str] = [] for directory, sub_directories, filenames in os.walk(self._root_directory): for filename in filenames: if not filename.lower() == 'settings.json': continue identifiers.append(filename) break return identifiers
10,456
Python
40.995984
176
0.608072