Transform your 3D texturing workflow with the power of generative AI, directly within Blender!
add plugin source code
sakalondaf4e2fd07121
diff --git a/stablegen/.gitignore b/stablegen/.gitignorenew file mode 100644index 0000000..2a400ea--- /dev/null+++ b/stablegen/.gitignore@@ -0,0 +1,118 @@+# Byte-compiled / optimized / DLL files+__pycache__/+*.py[cod]+*$py.class++# C extensions+*.so++# Distribution / packaging+.Python+build/+develop-eggs/+dist/+downloads/+eggs/+.eggs/+lib/+lib64/+parts/+sdist/+var/+wheels/+pip-wheel-metadata/+share/python-wheels/+*.egg-info/+.installed.cfg+*.egg+MANIFEST++# PyInstaller+# Usually these files are written by a python script from a template+# before PyInstaller builds the exe, so as to inject date/other infos into it.+*.manifest+*.spec++# Installer logs+pip-log.txt+pip-delete-this-directory.txt++# Unit test / coverage reports+htmlcov/+.tox/+.nox/+.coverage+.coverage.*+.cache+nosetests.xml+coverage.xml+*.cover+.hypothesis/+.pytest_cache/++# Translations+*.mo+*.pot++# Django stuff:+*.log+local_settings.py+db.sqlite3++# Flask stuff:+instance/+.webassets-cache++# Scrapy stuff:+.scrapy++# Sphinx documentation+docs/_build/++# PyBuilder+target/++# Jupyter Notebook+.ipynb_checkpoints++# IPython+profile_default/+ipython_config.py++# pyenv+.python-version++# celery beat schedule file+celerybeat-schedule++# SageMath parsed files+*.sage.py++# Environments+.env+.venv+env/+venv/+ENV/+env.bak/+venv.bak/++# Spyder project settings+.spyderproject+.spyproject++# Rope project settings+.ropeproject++# mkdocs documentation+/site++# mypy+.mypy_cache/+.dmypy.json+dmypy.json++# Pyre type checker+.pyre/+bugs.txt+raycast.osodiff --git a/stablegen/__init__.py b/stablegen/__init__.pynew file mode 100755index 0000000..6d13cf0--- /dev/null+++ b/stablegen/__init__.py@@ -0,0 +1,981 @@+""" This script registers the addon. """+import bpy # pylint: disable=import-error+from .stablegen import StableGenPanel, ApplyPreset, SavePreset, DeletePreset, get_preset_items, update_parameters+from .render_tools import BakeTextures, AddCameras, SwitchMaterial, ExportOrbitGIF, CollectCameraPrompts, CameraPromptItem+from .utils import AddHDRI, ApplyModifiers, CurvesToMesh+from .generator import ComfyUIGenerate+import os+from bpy.app.handlers import persistent++bl_info = {+ "name": "StableGen",+ "category": "Object",+ "author": "Ondrej Sakala",+ "version": (0, 0, 1),+ 'blender': (4, 2, 0)+}++class StableGenAddonPreferences(bpy.types.AddonPreferences):+ """+ Preferences for the StableGen addon.+ """+ bl_idname = __name__++ model_dir: bpy.props.StringProperty(+ name="Model Directory",+ description="Directory containing SD models",+ default="",+ subtype='DIR_PATH',+ update=update_parameters+ ) # type: ignore++ server_address: bpy.props.StringProperty(+ name="Server Address",+ description="Address of the ComfyUI server",+ default="127.0.0.1:8188",+ update=update_parameters+ ) # type: ignore++ output_dir: bpy.props.StringProperty(+ name="Output Directory",+ description="Directory to save generated outputs",+ default="",+ subtype='DIR_PATH',+ update=update_parameters+ ) # type: ignore++ controlnet_mapping: bpy.props.StringProperty(+ name="ControlNet Mapping",+ description="JSON mapping of controlnet type to model files. Example: {\"depth\": [\"controlnet_depth_sdxl.safetensors\", \"control_v11f1p_sd15_depth.pth\"], \"canny\": [\"sdxl_canny.safetensors\"]}\+ \nOnly following types are currently supported: depth, canny",+ default='{"depth": ["controlnet_depth_sdxl.safetensors", "sdxl_depth_alt.safetensors","sdxl_promax.safetensors", "controlnet_flux1_union_pro.safetensors"], "canny": ["sdxl_canny.safetensors", "sdxl_promax.safetensors", "controlnet_flux1_union_pro.safetensors"], "normal": ["sdxl_promax.safetensors"]}',+ update=update_parameters+ ) # type: ignore++ save_blend_file: bpy.props.BoolProperty(+ name="Save Blend File",+ description="Save the current Blender file with packed textures",+ default=False,+ update=update_parameters+ ) # type: ignore++ def draw(self, context):+ """+ Draws the preferences panel.+ :param context: Blender context.+ :return: None+ """+ layout = self.layout+ layout.prop(self, "model_dir")+ layout.prop(self, "server_address")+ layout.prop(self, "output_dir")+ layout.prop(self, "controlnet_mapping")+ layout.prop(self, "save_blend_file")++def update_model_list(self, context):+ """+ Updates the list of models in the model folder.+ :param self: Reference to the current instance.+ :param context: Blender context.+ :return: List of models.+ """+ addon_prefs = context.preferences.addons[__name__].preferences+ model_dir = addon_prefs.model_dir+ if os.path.isdir(model_dir):+ models = [f for f in os.listdir(model_dir) if f.endswith('.safetensors')]+ return [(model, model, "") for model in models]+ return []++def update_union(self, context):+ if "union" in self.model_name.lower() or "promax" in self.model_name.lower():+ self.is_union = True+ else:+ self.is_union = False++class ControlNetUnit(bpy.types.PropertyGroup):+ unit_type: bpy.props.StringProperty(+ name="Type",+ description="ControlNet type (e.g. 'depth', 'canny')",+ default="",+ update=update_parameters+ ) # type: ignore+ model_name: bpy.props.EnumProperty(+ name="Model",+ description="Select the ControlNet model",+ items=lambda self, context: get_controlnet_models(context, self.unit_type),+ update=lambda self, context: (update_parameters(self, context), update_union(self, context) ),+ ) # type: ignore+ strength: bpy.props.FloatProperty(+ name="Strength",+ description="Strength of the ControlNet effect",+ default=0.5,+ min=0.0,+ max=3.0,+ update=update_parameters+ ) # type: ignore+ start_percent: bpy.props.FloatProperty(+ name="Start",+ description="Start percentage (/100)",+ default=0.0,+ min=0.0,+ max=1.0,+ update=update_parameters+ ) # type: ignore+ end_percent: bpy.props.FloatProperty(+ name="End",+ description="End percentage (/100)",+ default=1.0,+ min=0.0,+ max=1.0,+ update=update_parameters+ ) # type: ignore+ is_union: bpy.props.BoolProperty(+ name="Is Union Type",+ description="Is this a union ControlNet?",+ default=False,+ update=update_parameters+ ) # type: ignore+ use_union_type: bpy.props.BoolProperty(+ name="Use Union Type",+ description="Use union type for ControlNet",+ default=True,+ update=update_parameters+ ) # type: ignore++def get_controlnet_models(context, unit_type):+ """+ Get available ControlNet models for a given type.+ """+ addon_prefs = context.preferences.addons[__name__].preferences+ try:+ import json+ mapping = json.loads(addon_prefs.controlnet_mapping)+ if unit_type in mapping:+ return [(model, model, "") for model in mapping[unit_type]]+ except json.JSONDecodeError:+ return []+ return []++class AddControlNetUnit(bpy.types.Operator):+ bl_idname = "stablegen.add_controlnet_unit"+ bl_label = "Add ControlNet Unit"+ bl_description = "Add a ControlNet Unit. Only one unit per type is allowed."++ unit_type: bpy.props.EnumProperty(+ name="Type",+ items=[('depth', 'Depth', ''), ('canny', 'Canny', ''), ('normal', 'Normal', '')],+ default='depth',+ update=update_parameters+ ) # type: ignore++ model_name: bpy.props.EnumProperty(+ name="Model",+ description="Select the ControlNet model",+ items=lambda self, context: get_controlnet_models(context, self.unit_type),+ update=update_parameters+ ) # type: ignore++ def invoke(self, context, event):+ # Always prompt for unit type and model selection+ return context.window_manager.invoke_props_dialog(self)++ def draw(self, context):+ layout = self.layout+ layout.prop(self, "unit_type")+ models = get_controlnet_models(context, self.unit_type)+ if len(models) > 1:+ layout.prop(self, "model_name")++ def execute(self, context):+ units = context.scene.controlnet_units+ # Only add if not already present+ for unit in units:+ if unit.unit_type == self.unit_type:+ self.report({'WARNING'}, f"Unit '{self.unit_type}' already exists.")+ return {'CANCELLED'}+ new_unit = units.add()+ new_unit.unit_type = self.unit_type+ new_unit.model_name = self.model_name+ new_unit.strength = 0.5+ new_unit.start_percent = 0.0+ new_unit.end_percent = 1.0+ if "union" in new_unit.model_name.lower() or "promax" in new_unit.model_name.lower():+ new_unit.is_union = True+ context.scene.controlnet_units_index = len(units) - 1+ # Force redraw of the UI+ for area in context.screen.areas:+ area.tag_redraw()+ return {'FINISHED'}++class RemoveControlNetUnit(bpy.types.Operator):+ bl_idname = "stablegen.remove_controlnet_unit"+ bl_label = "Remove ControlNet Unit"+ bl_description = "Remove the selected ControlNet Unit"++ unit_type: bpy.props.EnumProperty(+ name="Type",+ items=[('depth', 'Depth', ''), ('canny', 'Canny', ''), ('normal', 'Normal', '')],+ default='depth',+ update=update_parameters+ ) # type: ignore++ def invoke(self, context, event):+ units = context.scene.controlnet_units+ if len(units) == 1:+ self.unit_type = units[0].unit_type+ return self.execute(context)+ return context.window_manager.invoke_props_dialog(self)++ def draw(self, context):+ layout = self.layout+ layout.prop(self, "unit_type")++ def execute(self, context):+ units = context.scene.controlnet_units+ for index, unit in enumerate(units):+ if unit.unit_type == self.unit_type:+ units.remove(index)+ context.scene.controlnet_units_index = min(max(0, index - 1), len(units) - 1)+ # Force redraw of the UI+ update_parameters(self, context)+ for area in context.screen.areas:+ area.tag_redraw()+ return {'FINISHED'}+ self.report({'WARNING'}, f"No unit of type '{self.unit_type}' found.")+ return {'CANCELLED'}++# load handler to set default ControlNet unit+@persistent+def load_handler(dummy):+ scene = bpy.context.scene+ if not scene.controlnet_units:+ default_unit = scene.controlnet_units.add()+ default_unit.unit_type = 'depth'++def register():+ """+ Registers the addon.+ :return: None+ """+ bpy.utils.register_class(StableGenAddonPreferences)+ bpy.utils.register_class(StableGenPanel)+ bpy.utils.register_class(ComfyUIGenerate)+ bpy.utils.register_class(BakeTextures)+ bpy.utils.register_class(AddCameras)+ bpy.utils.register_class(SwitchMaterial)+ bpy.utils.register_class(AddHDRI)+ bpy.utils.register_class(ApplyModifiers)+ bpy.utils.register_class(CurvesToMesh)+ bpy.utils.register_class(ControlNetUnit)+ bpy.utils.register_class(CameraPromptItem)+ bpy.utils.register_class(CollectCameraPrompts)+ bpy.types.Scene.comfyui_prompt = bpy.props.StringProperty(+ name="ComfyUI Prompt",+ description="Enter the text prompt for ComfyUI generation",+ default="a monkey",+ update=update_parameters+ )+ bpy.types.Scene.comfyui_negative_prompt = bpy.props.StringProperty(+ name="ComfyUI Negative Prompt",+ description="Enter the negative text prompt for ComfyUI generation",+ default="",+ update=update_parameters+ )+ bpy.types.Scene.model_name = bpy.props.EnumProperty(+ name="Model Name",+ description="Select the SD model",+ items=update_model_list,+ update=update_parameters+ )+ bpy.types.Scene.seed = bpy.props.IntProperty(+ name="Seed",+ description="Seed for image generation",+ default=42,+ min=0,+ max=1000000,+ update=update_parameters+ )+ bpy.types.Scene.control_after_generate = bpy.props.EnumProperty(+ name="Control After Generate",+ description="Control behavior after generation",+ items=[+ ('fixed', 'Fixed', ''),+ ('increment', 'Increment', ''),+ ('decrement', 'Decrement', ''),+ ('randomize', 'Randomize', '')+ ],+ default='fixed',+ update=update_parameters+ )+ bpy.types.Scene.steps = bpy.props.IntProperty(+ name="Steps",+ description="Number of steps for generation",+ default=8,+ min=0,+ max=200,+ update=update_parameters+ )+ bpy.types.Scene.cfg = bpy.props.FloatProperty(+ name="CFG",+ description="Classifier-Free Guidance scale",+ default=1.5,+ min=0.0,+ max=100.0,+ update=update_parameters+ )+ bpy.types.Scene.sampler = bpy.props.EnumProperty(+ name="Sampler",+ description="Sampler for generation",+ items=[+ ('euler', 'Euler', ''),+ ('euler_ancestral', 'Euler A', ''),+ ('dpmpp_sde', 'DPM++ SDE', ''),+ ('dpmpp_2m', 'DPM++ 2M', ''),+ ('dpmpp_2s_ancestral', 'DPM++ 2S Ancestral', ''),+ ],+ default='dpmpp_2s_ancestral',+ update=update_parameters+ )+ bpy.types.Scene.scheduler = bpy.props.EnumProperty(+ name="Scheduler",+ description="Scheduler for generation",+ items=[+ ('sgm_uniform', 'SGM Uniform', ''),+ ('karras', 'Karras', ''),+ ('beta', 'Beta', ''),+ ],+ default='sgm_uniform',+ update=update_parameters+ )+ bpy.types.Scene.show_advanced_params = bpy.props.BoolProperty(+ name="Show Advanced Parameters",+ description="Show or hide advanced parameters",+ default=False,+ update=update_parameters+ )+ bpy.types.Scene.show_depthmap_testing = bpy.props.BoolProperty(+ name="Show Depthmap Testing",+ description="Show or hide depthmap testing section",+ default=True,+ update=update_parameters+ )+ bpy.types.Scene.show_generation_params = bpy.props.BoolProperty(+ name="Show Generation Parameters",+ description="Most important parameters",+ default=True,+ update=update_parameters+ )+ bpy.types.Scene.auto_rescale = bpy.props.BoolProperty(+ name="Auto Rescale Resolution",+ description="Automatically rescale resolution to appropriate size for the selected model",+ default=True,+ update=update_parameters+ )+ bpy.types.Scene.use_ipadapter = bpy.props.BoolProperty(+ name="Use IPAdapter",+ description="""Use IPAdapter for image generation. Requires an external reference image. Can improve consistency, can be useful for generating images with similar styles.\n\n - Has priority over mode specific IPAdapter.""",+ default=False,+ update=update_parameters+ )+ #IPAdapter image+ bpy.types.Scene.ipadapter_image = bpy.props.StringProperty(+ name="Reference Image",+ description="Path to the reference image",+ default="",+ subtype='FILE_PATH',+ update=update_parameters+ )+ bpy.types.Scene.ipadapter_strength = bpy.props.FloatProperty(+ name="IPAdapter Strength",+ description="Strength for IPAdapter",+ default=1.0,+ min=-1.0,+ max=3.0,+ update=update_parameters+ )+ bpy.types.Scene.ipadapter_start = bpy.props.FloatProperty(+ name="IPAdapter Start",+ description="Start percentage for IPAdapter (/100)",+ default=0.0,+ min=0.0,+ max=1.0,+ update=update_parameters+ )+ bpy.types.Scene.ipadapter_end = bpy.props.FloatProperty(+ name="IPAdapter End",+ description="End percentage for IPAdapter (/100)",+ default=1.0,+ min=0.0,+ max=1.0,+ update=update_parameters+ )+ bpy.types.Scene.ipadapter_weight_type = bpy.props.EnumProperty(+ name="IPAdapter Weight Type",+ description="Weight type for IPAdapter",+ items=[+ ('standard', 'Standard', ''),+ ('prompt', 'Prompt is more important', ''),+ ('style', 'Style transfer', ''),+ ],+ default='style',+ update=update_parameters+ )+ bpy.types.Scene.sequential_ipadapter = bpy.props.BoolProperty(+ name="Use IPAdapter",+ description="""Uses IPAdapter to improve consistency between images.\n\n - Applicable for Separate, Sequential and Refine modes.\n - Uses either the first generated image or the most recent one as a reference for the rest of the images.\n - If 'Regenerate IPAdapter' is enabled, the first viewpoint will be regenerated with IPAdapter to match the rest of the images.\n - If 'Use IPAdapter (External Image)' is enabled, this setting is effectively overriden.""",+ default=False,+ update=update_parameters+ )+ bpy.types.Scene.sequential_ipadapter_mode = bpy.props.EnumProperty(+ name="IPAdapter Mode",+ description="Mode for IPAdapter in sequential generation",+ items=[+ ('first', 'Use first generated image', ''),+ ('recent', 'Use most recent generated image', ''),+ ],+ default='first',+ update=update_parameters+ )+ bpy.types.Scene.sequential_ipadapter_regenerate = bpy.props.BoolProperty(+ name="Regenerate IPAdapter",+ description="IPAdapter generations may differ from the original image. This option regenerates the first viewpoint with IPAdapter to match the rest of the images.",+ default=True,+ update=update_parameters+ )+ bpy.types.Scene.sequential_ipadapter_regenerate_wo_controlnet = bpy.props.BoolProperty(+ name="Generate IPAdapter reference without ControlNet",+ description="Generate the first viewpoint with IPAdapter without ControlNet. This is useful for generating a reference image that is not affected by ControlNet. Can possibly generate higher quality reference.",+ default=False,+ update=update_parameters+ )+ bpy.types.Scene.generation_method = bpy.props.EnumProperty(+ name="Generation Mode",+ description="Choose the mode for generating images",+ items=[+ ('separate', 'Generate Separately', 'Generates images one by one for each viewpoint. Each image is generated independently using only its own control signals (e.g., depth map) without context from other views. All images are applied at the end.'),+ ('sequential', 'Generate Sequentially', 'Generates images viewpoint by viewpoint. After the first view, each subsequent view is generated using inpainting, guided by a visibility mask and an RGB render of the texture projected from previous viewpoints to maintain consistency.'),+ ('grid', 'Generate Using Grid', 'Combines control signals from all viewpoints into a single grid, generates a single image, then splits it back into individual viewpoint textures. Faster but lower resolution per view. Includes an optional second pass to refine each split image individually at full resolution for improved quality.'),+ ('refine', 'Refine/Restyle Texture (Img2Img)', 'Uses the current rendered texture appearance as input for an img2img generation pass.\n\nBehavior depends on "Preserve Original Textures" (Advanced Parameters -> Generation Mode Specifics):\n\nON: Layers new details over the existing texture (preserves uncovered areas).\n - Works only with StableGen generated textures.\n\nOFF: Replaces the previous material with the new result (good for restyling).\n - Works on any existing material setup.'),+ ('uv_inpaint', 'UV Inpaint Missing Areas', 'Identifies untextured areas on a standard UV map using a visibility calculation. Performs baking if not baked already. Performs diffusion inpainting directly on the UV texture map to fill only these missing regions, using the surrounding texture as context.'),+ ],+ default='sequential',+ update=update_parameters+ )+ bpy.types.Scene.refine_images = bpy.props.BoolProperty(+ name="Refine Images",+ description="Refine images after generation",+ default=False,+ update=update_parameters+ )+ bpy.types.Scene.refine_steps = bpy.props.IntProperty(+ name="Refine Steps",+ description="Number of steps for refining",+ default=8,+ min=0,+ max=200,+ update=update_parameters+ )+ bpy.types.Scene.refine_sampler = bpy.props.EnumProperty(+ name="Refine Sampler",+ description="Sampler for refining",+ items=[+ ('euler', 'Euler', ''),+ ('euler_ancestral', 'Euler A', ''),+ ('dpmpp_sde', 'DPM++ SDE', ''),+ ('dpmpp_2m', 'DPM++ 2M', ''),+ ('dpmpp_2s_ancestral', 'DPM++ 2S Ancestral', ''),+ ],+ default='dpmpp_2s_ancestral',+ update=update_parameters+ )+ bpy.types.Scene.refine_scheduler = bpy.props.EnumProperty(+ name="Refine Scheduler",+ description="Scheduler for refining",+ items=[+ ('sgm_uniform', 'SGM Uniform', ''),+ ('karras', 'Karras', ''),+ ('beta', 'Beta', ''),+ ],+ default='sgm_uniform',+ update=update_parameters+ )+ bpy.types.Scene.denoise = bpy.props.FloatProperty(+ name="Denoise",+ description="Denoise level for refining",+ default=1.0,+ min=0.0,+ max=1.0,+ update=update_parameters+ )+ bpy.types.Scene.refine_cfg = bpy.props.FloatProperty(+ name="Refine CFG",+ description="Classifier-Free Guidance scale for refining",+ default=1.5,+ min=0.0,+ max=100.0,+ update=update_parameters+ )+ bpy.types.Scene.refine_prompt = bpy.props.StringProperty(+ name="Refine Prompt",+ description="Prompt for refining (leave empty to use same prompt as generation)",+ default="",+ update=update_parameters+ )+ bpy.types.Scene.refine_upscale_method = bpy.props.EnumProperty(+ name="Refine Upscale Method",+ description="Upscale method for refining",+ items=[+ ('nearest-exact', 'Nearest Exact', ''),+ ('bilinear', 'Bilinear', ''),+ ('bicubic', 'Bicubic', ''),+ ('lanczos', 'Lanczos', ''),+ ],+ default='lanczos',+ update=update_parameters+ )+ bpy.types.Scene.generation_status = bpy.props.EnumProperty(+ name="Generation Status",+ description="Status of the generation process",+ items=[+ ('idle', 'Idle', ''),+ ('running', 'Running', ''),+ ('error', 'Error', '')+ ],+ default='idle',+ update=update_parameters+ )+ bpy.types.Scene.generation_progress = bpy.props.FloatProperty(+ name="Generation Progress",+ description="Current progress of image generation",+ default=0.0,+ min=0.0,+ max=100.0,+ update=update_parameters+ )+ bpy.types.Scene.overwrite_material = bpy.props.BoolProperty(+ name="Overwrite Material",+ description="Overwrite existing material",+ default=True,+ update=update_parameters+ )+ bpy.types.Scene.refine_preserve = bpy.props.BoolProperty(+ name="Preserve Original Texture",+ description="Preserve the original textures when refining in places where the new texture isn't available",+ default=False,+ update=update_parameters+ )+ bpy.types.Scene.discard_factor = bpy.props.FloatProperty(+ name="Discard Factor",+ description="If the texture is facing the camera at an angle greater than this value, it will be discarded. This is useful for preventing artifacts from the very edge of the generated texture appearing when keeping high discard factor (use ~65 for best results when generating textures around an object)",+ default=90.0,+ min=0.0,+ max=180.0,+ update=update_parameters+ )+ bpy.types.Scene.weight_exponent = bpy.props.FloatProperty(+ name="Weight Exponent",+ description="Controls the falloff curve for viewpoint weighting based on the angle to the surface normal (θ). "+ "Weight = |cos(θ)|^Exponent. Higher values prioritize straight-on views more strongly, creating sharper transitions. "+ "1.0 = standard |cos(θ)| weighting..",+ default=3.0,+ min=0.1,+ max=1000.0,+ update=update_parameters+ )+ bpy.types.Scene.bake_texture = bpy.props.BoolProperty(+ name="Bake Texture",+ description="Bake the texture to the model. This is forced if there are more than 8 cameras. Use this to prevent UV map slot limit errors.",+ default=False,+ update=update_parameters+ )+ bpy.types.Scene.bake_texture_size = bpy.props.IntProperty(+ name="Bake Texture Size",+ description="Size of the baked texture",+ default=2048,+ min=256,+ max=8192,+ update=update_parameters+ )+ bpy.types.Scene.bake_unwrap_method = bpy.props.EnumProperty(+ name="Bake Unwrap Method",+ description="Method for unwrapping the model for baking",+ items=[+ ('none', 'None', ''),+ ('smart', 'Smart UV Project', ''),+ ('basic', 'Unwrap', ''),+ ('lightmap', 'Lightmap Pack', ''),+ ('pack', 'Pack Islands', '')+ ],+ default='none',+ update=update_parameters+ )+ bpy.types.Scene.bake_unwrap_overlap_only = bpy.props.BoolProperty(+ name="Ony Unwrap Overlapping UVs",+ description="Only unwrap UVs that overlap",+ default=True,+ update=update_parameters+ )+ bpy.types.Scene.allow_modify_existing_textures = bpy.props.BoolProperty(+ name="Allow modifying existing textures",+ description="Disconnect compare node in export_visibility so that smooth output is not pure 1 areas",+ default=False,+ update=update_parameters+ )+ bpy.types.Scene.ask_object_prompts = bpy.props.BoolProperty(+ name="Ask for object prompts",+ description="Use object-specific prompts; if disabled, the normal prompt is used for all objects",+ default=True,+ update=update_parameters+ )+ bpy.types.Scene.fallback_color = bpy.props.FloatVectorProperty(+ name="Fallback Color",+ description="Color to use as fallback in texture generation",+ subtype='COLOR',+ default=(0.5, 0.5, 0.5), # Changed from 4 values to 3 values+ min=0.0, max=1.0,+ update=update_parameters+ )+ bpy.types.Scene.sequential_smooth = bpy.props.BoolProperty(+ name="Sequential Smooth",+ description="""Use smooth visibility map for sequential generation mode. Disabling this uses a binary visibility map and may need more mask blurring to reduce artifacts.++ - Visibility map is a mask that indicates which pixels have textures already projected from previous viewpoints.+ - Both methods are using weights which are calculated based on the angle between the surface normal and the camera view direction.+ - 'Smooth' uses these calculated weights directly (0.0-1.0 range, giving gradual transitions). The transition point can be further tuned by the 'Smooth Factor' parameters.+ - Disabling 'Smooth' thresholds these weights to create a hard-edged binary mask (0.0 or 1.0).""",+ default=True,+ update=update_parameters+ )+ bpy.types.Scene.weight_exponent_mask = bpy.props.BoolProperty(+ name="Weight Exponent Mask",+ description="Use weight exponent for visibility map generation. Uses 1.0 if disabled.",+ default=False,+ update=update_parameters+ )+ bpy.types.Scene.canny_threshold_low = bpy.props.IntProperty(+ name="Canny Threshold Low",+ description="Low threshold for Canny edge detection",+ default=0,+ min=0,+ max=255,+ update=update_parameters+ )+ bpy.types.Scene.canny_threshold_high = bpy.props.IntProperty(+ name="Canny Threshold High",+ description="High threshold for Canny edge detection",+ default=80,+ min=0,+ max=255,+ update=update_parameters+ )+ bpy.types.Scene.sequential_factor_smooth = bpy.props.FloatProperty(+ name="Smooth Visibility Black Point",+ description="Controls the black point (start) of the Color Ramp used for the smooth visibility mask in sequential mode. Defines the weight threshold below which areas are considered fully invisible/untextured from previous views. Higher values create a sharper transition start.",+ default=0.15,+ min=0.0,+ max=1.0,+ update=update_parameters+ )+ bpy.types.Scene.sequential_factor_smooth_2 = bpy.props.FloatProperty(+ name="Smooth Visibility White Point",+ description="Controls the white point (end) of the Color Ramp used for the smooth visibility mask in sequential mode. Defines the weight threshold above which areas are considered fully visible/textured from previous views. Lower values create a sharper transition end.",+ default=1.0,+ min=0.0,+ max=1.0,+ update=update_parameters+ )+ bpy.types.Scene.sequential_factor = bpy.props.FloatProperty(+ name="Binary Visibility Threshold",+ description="Threshold value used when 'Sequential Smooth' is OFF. Calculated visibility weights below this value are treated as 0 (invisible), and those above as 1 (visible), creating a hard-edged binary mask.",+ default=0.7,+ min=0.0,+ max=1.0,+ update=update_parameters+ )+ bpy.types.Scene.differential_noise = bpy.props.BoolProperty(+ name="Differential Noise",+ description="Adds latent noise mask to the image before inpainting. This must be used with low factor smooth mask or with a high blur mask radius. Disabling this effectively discrads the mask and only uses the inapaint conditioning.",+ default=True,+ update=update_parameters+ )+ bpy.types.Scene.grow_mask_by = bpy.props.IntProperty(+ name="Grow Mask By",+ description="Grow mask by this amount (ComfyUI)",+ default=3,+ min=0,+ update=update_parameters+ )+ bpy.types.Scene.mask_blocky = bpy.props.BoolProperty(+ name="Blocky Visibility Map",+ description="Uses a blocky visibility map. This will downscale the visibility map according to the 8x8 grid which Stable Diffusion uses in latent space. Highly experimental.",+ default=False,+ update=update_parameters+ )+ bpy.types.Scene.differential_diffusion = bpy.props.BoolProperty(+ name="Differential Diffusion",+ description="Replace standard inpainting with a differential diffusion based workflow\n\n - Generally works better and reduces artifacts.\n - Using a Smooth Visibilty Map is recommended for Sequential Mode.",+ default=True,+ update=update_parameters+ )+ bpy.types.Scene.blur_mask = bpy.props.BoolProperty(+ name="Blur Mask",+ description="Blur mask before inpainting (ComfyUI)",+ default=True,+ update=update_parameters+ )+ bpy.types.Scene.blur_mask_radius = bpy.props.IntProperty(+ name="Blur Mask Radius",+ description="Radius for mask blurring (ComfyUI)",+ default=1,+ min=1,+ max=31,+ update=update_parameters+ )+ bpy.types.Scene.blur_mask_sigma = bpy.props.FloatProperty(+ name="Blur Mask Sigma",+ description="Sigma for mask blurring (ComfyUI)",+ default=1.0,+ min=0.1,+ update=update_parameters+ )+ bpy.types.Scene.sequential_custom_camera_order = bpy.props.StringProperty(+ name="Custom Camera Order",+ description="""Custom camera order for Sequential Mode. Format: 'index1,index2,index3,...'++ - This will permanently change the order of the cameras in the scene.""",+ default="",+ update=update_parameters+ )+ bpy.types.Scene.clip_skip = bpy.props.IntProperty(+ name="CLIP Skip",+ description="CLIP skip value for generation",+ default=1,+ min=1,+ update=update_parameters+ )+ bpy.types.Scene.lora_type = bpy.props.EnumProperty(+ name="LoRA Type",+ description="Type of LoRA to use",+ items=[+ ('hyper_1step', 'Hyper (1 step)', ''),+ ('hyper_4step', 'Hyper (4 steps)', ''),+ ('hyper_8step', 'Hyper (8 steps)', ''),+ ('lightning_2step', 'Lightning (2 steps)', ''),+ ('lightning_4step', 'Lightning (4 steps)', ''),+ ('lightning_8step', 'Lightning (8 steps)', ''),+ ('none', 'None', '')+ ],+ default='lightning_8step',+ update=update_parameters+ )+ bpy.types.Scene.stablegen_preset = bpy.props.EnumProperty(+ name="Preset",+ description="Select a preset for easy mode",+ items=get_preset_items,+ default=0+ )++ bpy.types.Scene.active_preset = bpy.props.StringProperty(+ name="Active Preset",+ default="DEFAULT"+ )++ bpy.types.Scene.model_architecture = bpy.props.EnumProperty(+ name="Model Architecture",+ description="Select the model architecture to use for generation",+ items=[+ ('sdxl', 'SDXL', ''),+ ('flux1', 'Flux 1 (beta support)', '')+ ],+ default='sdxl',+ update=update_parameters+ )++ bpy.types.Scene.output_timestamp = bpy.props.StringProperty(+ name="Output Timestamp",+ description="Timestamp for generation output directory",+ default=""+ )++ bpy.types.Scene.camera_prompts = bpy.props.CollectionProperty(+ type=CameraPromptItem,+ name="Camera Prompts",+ description="Stores viewpoint descriptions for each camera"+ ) # type: ignore++ bpy.types.Scene.use_camera_prompts = bpy.props.BoolProperty(+ name="Use Camera Prompts",+ description="Use camera prompts for generating images",+ default=True,+ update=update_parameters+ )+ bpy.types.Scene.show_core_settings = bpy.props.BoolProperty(+ name="Core Generation Settings",+ description="Parameters used for the image generation process. Also includes LoRAs for faster generation.",+ default=False,+ update=update_parameters+ )++ bpy.types.Scene.show_scene_understanding_settings = bpy.props.BoolProperty(+ name="Viewpoint Blending Settings",+ description="Settings for how the addon blends different viewpoints together.",+ default=False,+ update=update_parameters+ )++ bpy.types.Scene.show_output_material_settings = bpy.props.BoolProperty(+ name="Output & Material Settings",+ description="Settings for output characteristics and material handling, including texture processing and final image resolution.",+ default=False,+ update=update_parameters+ )++ bpy.types.Scene.show_image_guidance_settings = bpy.props.BoolProperty(+ name="Image Guidance (IPAdapter & ControlNet)",+ description="Configuration for advanced image guidance techniques, allowing more precise control via reference images or structural inputs.",+ default=False,+ update=update_parameters+ )++ bpy.types.Scene.show_masking_inpainting_settings = bpy.props.BoolProperty(+ name="Inpainting Options",+ description="Parameters for inpainting and mask manipulation to refine specific image areas. (Visible for UV Inpaint & Sequential modes).",+ default=False,+ update=update_parameters+ )++ bpy.types.Scene.show_mode_specific_settings = bpy.props.BoolProperty(+ name="Generation Mode Specifics",+ description="Parameters exclusively available for the selected Generation Mode, allowing tailored control over mode-dependent behaviors.",+ default=False,+ update=update_parameters+ )++ bpy.types.Scene.apply_bsdf = bpy.props.BoolProperty(+ name ="Apply BSDF",+ description="""Apply the BSDF shader to the material+ - when set to FALSE, the material will be emissive and will not be affected by the scene lighting+ - when set to TRUE, the material will be affected by the scene lighting""",+ default=True,+ update=update_parameters+ )++++ # IPADAPTER parameters+++ bpy.types.Scene.controlnet_units = bpy.props.CollectionProperty(type=ControlNetUnit)+ bpy.utils.register_class(AddControlNetUnit)+ bpy.utils.register_class(RemoveControlNetUnit)+ bpy.types.Scene.controlnet_units_index = bpy.props.IntProperty(default=0)+ bpy.app.handlers.load_post.append(load_handler)+ bpy.utils.register_class(ApplyPreset)+ bpy.utils.register_class(SavePreset)+ bpy.utils.register_class(DeletePreset)+ bpy.utils.register_class(ExportOrbitGIF)+++def unregister():+ """+ Unregisters the addon.+ :return: None+ """+ del bpy.types.Scene.comfyui_prompt+ del bpy.types.Scene.comfyui_negative_prompt+ del bpy.types.Scene.model_name+ del bpy.types.Scene.seed+ del bpy.types.Scene.control_after_generate+ del bpy.types.Scene.steps+ del bpy.types.Scene.cfg+ del bpy.types.Scene.sampler+ del bpy.types.Scene.scheduler+ del bpy.types.Scene.show_advanced_params+ del bpy.types.Scene.show_depthmap_testing+ del bpy.types.Scene.show_generation_params+ del bpy.types.Scene.auto_rescale+ del bpy.types.Scene.generation_method+ del bpy.types.Scene.use_ipadapter+ del bpy.types.Scene.refine_images+ del bpy.types.Scene.refine_steps+ del bpy.types.Scene.refine_sampler+ del bpy.types.Scene.refine_scheduler+ del bpy.types.Scene.denoise+ del bpy.types.Scene.refine_cfg+ del bpy.types.Scene.refine_prompt+ del bpy.types.Scene.refine_upscale_method+ del bpy.types.Scene.generation_status+ del bpy.types.Scene.generation_progress+ del bpy.types.Scene.overwrite_material+ del bpy.types.Scene.refine_preserve+ del bpy.types.Scene.discard_factor+ del bpy.types.Scene.weight_exponent+ del bpy.types.Scene.bake_texture+ del bpy.types.Scene.bake_texture_size+ del bpy.types.Scene.bake_unwrap_method+ del bpy.types.Scene.bake_unwrap_overlap_only+ del bpy.types.Scene.allow_modify_existing_textures+ del bpy.types.Scene.ask_object_prompts+ del bpy.types.Scene.fallback_color+ del bpy.types.Scene.controlnet_units+ del bpy.types.Scene.controlnet_units_index+ del bpy.types.Scene.weight_exponent_mask+ del bpy.types.Scene.sequential_smooth+ del bpy.types.Scene.canny_threshold_low+ del bpy.types.Scene.canny_threshold_high+ del bpy.types.Scene.sequential_factor_smooth+ del bpy.types.Scene.sequential_factor_smooth_2+ del bpy.types.Scene.sequential_factor+ del bpy.types.Scene.grow_mask_by+ del bpy.types.Scene.mask_blocky+ del bpy.types.Scene.differential_diffusion+ del bpy.types.Scene.differential_noise+ del bpy.types.Scene.blur_mask+ del bpy.types.Scene.blur_mask_radius+ del bpy.types.Scene.blur_mask_sigma+ del bpy.types.Scene.sequential_custom_camera_order+ del bpy.types.Scene.ipadapter_strength+ del bpy.types.Scene.ipadapter_start+ del bpy.types.Scene.ipadapter_end+ del bpy.types.Scene.sequential_ipadapter+ del bpy.types.Scene.sequential_ipadapter_mode+ del bpy.types.Scene.sequential_ipadapter_regenerate+ del bpy.types.Scene.ipadapter_weight_type+ del bpy.types.Scene.clip_skip+ del bpy.types.Scene.lora_type+ del bpy.types.Scene.stablegen_preset+ del bpy.types.Scene.model_architecture+ del bpy.types.Scene.output_timestamp+ del bpy.types.Scene.camera_prompts+ del bpy.types.Scene.use_camera_prompts+ del bpy.types.Scene.show_core_settings+ del bpy.types.Scene.show_scene_understanding_settings+ del bpy.types.Scene.show_output_material_settings+ del bpy.types.Scene.show_image_guidance_settings+ del bpy.types.Scene.show_masking_inpainting_settings+ del bpy.types.Scene.show_mode_specific_settings+ bpy.utils.unregister_class(ApplyPreset)+ bpy.utils.unregister_class(DeletePreset)+ bpy.utils.unregister_class(SavePreset)+ bpy.utils.unregister_class(CurvesToMesh)+ bpy.utils.unregister_class(ApplyModifiers)+ bpy.utils.unregister_class(AddHDRI)+ bpy.utils.unregister_class(SwitchMaterial)+ bpy.utils.unregister_class(AddCameras)+ bpy.utils.unregister_class(BakeTextures)+ bpy.utils.unregister_class(ComfyUIGenerate)+ bpy.utils.unregister_class(StableGenPanel)+ bpy.utils.unregister_class(StableGenAddonPreferences)+ bpy.utils.unregister_class(ControlNetUnit)+ bpy.utils.unregister_class(AddControlNetUnit)+ bpy.utils.unregister_class(RemoveControlNetUnit)+ bpy.utils.unregister_class(ExportOrbitGIF)+ bpy.utils.unregister_class(CameraPromptItem)+ bpy.utils.unregister_class(CollectCameraPrompts)+ # Remove the load handler for default controlnet unit+ if load_handler in bpy.app.handlers.load_post:+ bpy.app.handlers.load_post.remove(load_handler)+++if __name__ == "__main__":+ register()diff --git a/stablegen/generator.py b/stablegen/generator.pynew file mode 100644index 0000000..b2f44c6--- /dev/null+++ b/stablegen/generator.py@@ -0,0 +1,1928 @@+import os+import bpy # pylint: disable=import-error+import numpy as np++import uuid+import json+import urllib.request+import urllib.parse+import threading+from datetime import datetime++import math+from PIL import Image++from .util.helpers import prompt_text, prompt_text_img2img # pylint: disable=relative-beyond-top-level+from .util import install_testing # pylint: disable=relative-beyond-top-level+from .render_tools import export_emit_image, export_visibility, export_canny, bake_texture, prepare_baking, unwrap # pylint: disable=relative-beyond-top-level+from .utils import get_last_material_index, get_generation_dirs, get_file_path, get_dir_path, remove_empty_dirs # pylint: disable=relative-beyond-top-level+from .project import project_image # pylint: disable=relative-beyond-top-level++try:+ import websocket+except ImportError:+ install_testing.install()+ import websocket++def redraw_ui(context):+ """Redraws the UI to reflect changes in the operator's progress and status."""+ for area in context.screen.areas:+ area.tag_redraw()++class ComfyUIGenerate(bpy.types.Operator):+ """Generate textures using ComfyUI (to all mesh objects using all cameras in the scene)++ - Multiple modes are available. Choose by setting Generation Mode in the UI.+ - This includes texture generation and projection to the mesh objects.+ - By default, the generated textures will only be visible in the Rendered viewport shading mode."""+ bl_idname = "object.test_stable"+ bl_label = "Generate using ComfyUI"+ bl_options = {'REGISTER', 'UNDO'}++ _timer = None+ _progress = 0+ _error = None+ _is_running = False+ _threads_left = 0+ _cameras = None+ _grid_width = 0+ _grid_height = 0+ _material_id = -1+ proceed_with_high_res: bpy.props.BoolProperty(default=False)++ # Add properties to track progress+ _progress = 0.0+ _stage = ""+ _current_image = 0+ _total_images = 0+ _wait_event = None++ # Add new properties at the top of the class+ _object_prompts: dict = {}+ show_prompt_dialog: bpy.props.BoolProperty(default=True)+ current_object_name: bpy.props.StringProperty()+ current_object_prompt: bpy.props.StringProperty(+ name="Object Prompt",+ description="Enter a specific prompt for this object",+ default=""+ ) # type: ignore+ # New properties for prompt collection+ _mesh_objects: list = []+ mesh_index: int = 0++ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ self._total_images = 0+ self._current_image = 0+ self._stage = ""+ self._progress = 0+ self._wait_event = threading.Event()++ @classmethod+ def poll(cls, context):+ """+ Polls whether the operator can be executed.+ :param context: Blender context.+ :return: True if the operator can be executed, False otherwise.+ """+ # Check for other modal operators+ operator = None+ for window in context.window_manager.windows:+ for op in window.modal_operators:+ if op.bl_idname == 'OBJECT_OT_add_cameras' or op.bl_idname == 'OBJECT_OT_bake_textures' or op.bl_idname == 'OBJECT_OT_collect_camera_prompts':+ operator = op+ break+ if operator:+ break+ if operator:+ return False+ # Check if output directory, model directory, and server address are set+ addon_prefs = context.preferences.addons[__package__].preferences+ if not os.path.exists(addon_prefs.output_dir):+ return False+ if not os.path.exists(addon_prefs.model_dir):+ return False+ if not addon_prefs.server_address:+ return False+ return True++ def execute(self, context):+ """+ Executes the operator.+ :param context: Blender context.+ :return: {'RUNNING_MODAL'}+ """+ if ComfyUIGenerate._is_running:+ self.cancel_generate(context)+ return {'FINISHED'}++ # Timestamp for output directory+ context.scene.output_timestamp = datetime.now().strftime("%Y-%m-%dT%H-%M-%S")++ # If UV inpainting and we're in prompt collection mode, collect prompts first.+ if context.scene.generation_method == 'uv_inpaint' and self.show_prompt_dialog:+ self._object_prompts[self.current_object_name] = self.current_object_prompt+ if self.mesh_index < len(self._mesh_objects) - 1:+ self.mesh_index += 1+ self.current_object_name = self._mesh_objects[self.mesh_index]+ self.current_object_prompt = ""+ return context.window_manager.invoke_props_dialog(self, width=400)+ else:+ self.show_prompt_dialog = False+++ context.scene.generation_status = 'running'+ ComfyUIGenerate._is_running = True++ print("Executing ComfyUI Generation")++ render = bpy.context.scene.render+ resolution_x = render.resolution_x+ resolution_y = render.resolution_y+ total_pixels = resolution_x * resolution_y++ if context.scene.auto_rescale and ((total_pixels > 1_200_000 or total_pixels < 800_000) or (resolution_x % 8 != 0 or resolution_y % 8 != 0)):+ scale_factor = (1_000_000 / total_pixels) ** 0.5+ render.resolution_x = int(resolution_x * scale_factor)+ render.resolution_y = int(resolution_y * scale_factor)+ # ComfyUI requires resolution to be divisible by 8+ render.resolution_x -= render.resolution_x % 8+ render.resolution_y -= render.resolution_y % 8+ self.report({'INFO'}, f"Resolution automatically rescaled to {render.resolution_x}x{render.resolution_y}.")+ self.proceed_with_high_res = True # Automatically proceed after rescale++ elif total_pixels > 1_200_000 and not self.proceed_with_high_res: # 1MP + 20%+ self.proceed_with_high_res = True # Set to true to avoid repeated pop-ups+ self.report({'WARNING'}, "High resolution detected. Resolutions above 1MP may reduce performance and quality. To proceed, run the operator again.")+ context.scene.generation_status = 'idle'+ ComfyUIGenerate._is_running = False+ return {'CANCELLED'}++ self._cameras = [obj for obj in bpy.context.scene.objects if obj.type == 'CAMERA']+ if not self._cameras:+ self.report({'ERROR'}, "No cameras found in the scene.")+ context.scene.generation_status = 'idle'+ ComfyUIGenerate._is_running = False+ return {'CANCELLED'}+ # Sort cameras by name+ self._cameras.sort(key=lambda x: x.name)++ # Check if there is at least one ControlNet unit+ controlnet_units = getattr(context.scene, "controlnet_units", [])+ if not controlnet_units:+ self.report({'ERROR'}, "At least one ControlNet unit is required to run the operator.")+ context.scene.generation_status = 'idle'+ ComfyUIGenerate._is_running = False+ return {'CANCELLED'}++ # If there are curves within the scene, warn the user+ if any(obj.type == 'CURVE' for obj in bpy.context.scene.objects):+ self.report({'WARNING'}, "Curves detected in the scene. This may cause issues with the generation process. Consider removing them before proceeding.")++ print(f"Generating images for {len(self._cameras)} cameras")++ uv_slots_needed = len(self._cameras)++ # Find all mesh objects, check their material ids and store the highest one+ for obj in bpy.context.scene.objects:+ if obj.type == 'MESH':+ for slot in obj.material_slots:+ material_id = get_last_material_index(obj)+ if (material_id > self._material_id):+ self._material_id = material_id+ # Check if there are enough UV map slots+ if not context.scene.bake_texture and context.scene.generation_method != 'uv_inpaint':+ if not context.scene.overwrite_material or (context.scene.generation_method == 'refine' and context.scene.refine_preserve):+ if 8 - len(obj.data.uv_layers) < uv_slots_needed:+ self.report({'ERROR'}, "Not enough UV map slots for all cameras.")+ context.scene.generation_status = 'idle'+ ComfyUIGenerate._is_running = False+ return {'CANCELLED'}+ else:+ # Make a set to count unique uv maps+ uv_maps = set()+ mesh = obj.data+ uv_maps = [uv_layer.name for uv_layer in mesh.uv_layers]+ if len(uv_maps) == 1:+ # Probably a baked texture, check if there is enough uv slots+ if 8 - len(obj.data.uv_layers) - 1 < uv_slots_needed:+ self.report({'ERROR'}, "Not enough UV map slots for all cameras.")+ context.scene.generation_status = 'idle'+ ComfyUIGenerate._is_running = False+ return {'CANCELLED'}+ elif 8 - len(obj.data.uv_layers) + len(uv_maps) < uv_slots_needed:+ print(f"8 - {len(obj.data.uv_layers)} + {len(uv_maps)} < {uv_slots_needed}")+ self.report({'ERROR'}, "Not enough UV map slots for all cameras.")+ context.scene.generation_status = 'idle'+ ComfyUIGenerate._is_running = False+ return {'CANCELLED'}++ else:+ if 8 - len(obj.data.uv_layers) < 1:+ self.report({'ERROR'}, "Not enough UV map slots for baking. At least 1 slot is required.")++ if not context.scene.overwrite_material or self._material_id == -1 or (context.scene.generation_method == 'refine' and context.scene.refine_preserve):+ self._material_id += 1++ if context.scene.generation_method == 'sequential' and context.scene.sequential_custom_camera_order != "":+ # The format is: index1,index2,index3,...,indexN+ camera_order = context.scene.sequential_custom_camera_order.split(',')+ # Check if there is index for each camera+ if len(camera_order) != len(self._cameras):+ self.report({'ERROR'}, "The number of indices in the custom camera order must match the number of cameras.")+ context.scene.generation_status = 'idle'+ ComfyUIGenerate._is_running = False+ return {'CANCELLED'}+ # Make a backup of all cameras, remove and then add them in the custom order+ cameras = self._cameras.copy()+ cameras_backup = [camera.copy() for camera in cameras]+ for camera in cameras:+ bpy.data.objects.remove(camera)+ self._cameras = []+ # Re-add the cameras in the custom order+ for i, index in enumerate(camera_order):+ camera = cameras_backup[int(index)]+ # Rename the camera to match the index+ camera.name = f"Camera_{i}"+ self._cameras.append(camera)+ bpy.context.scene.collection.objects.link(camera)++ # If there is depth controlnet unit+ if any(unit["unit_type"] == "depth" for unit in controlnet_units):+ if context.scene.generation_method != 'uv_inpaint':+ # Export depth maps for each camera+ for i, camera in enumerate(self._cameras):+ bpy.context.scene.camera = camera+ self.export_depthmap(context, camera_id=i)+ if context.scene.generation_method == 'grid':+ self.combine_maps(context, self._cameras, type="depth")+ # If there is canny controlnet unit+ if any(unit["unit_type"] == "canny" for unit in controlnet_units):+ if context.scene.generation_method != 'uv_inpaint':+ # Export canny maps for each camera+ for i, camera in enumerate(self._cameras):+ bpy.context.scene.camera = camera+ export_canny(context, camera_id=i, low_threshold=context.scene.canny_threshold_low, high_threshold=context.scene.canny_threshold_high)+ if context.scene.generation_method == 'grid':+ self.combine_maps(context, self._cameras, type="canny")+ # If there is normal controlnet unit+ if any(unit["unit_type"] == "normal" for unit in controlnet_units):+ if context.scene.generation_method != 'uv_inpaint':+ # Export normal maps for each camera+ for i, camera in enumerate(self._cameras):+ bpy.context.scene.camera = camera+ self.export_normal(context, camera_id=i)+ if context.scene.generation_method == 'grid':+ self.combine_maps(context, self._cameras, type="normal")++ # Prepare for generating+ if context.scene.generation_method == 'grid':+ self._threads_left = 1+ if context.scene.generation_method == 'uv_inpaint':+ mesh_objects = [obj for obj in bpy.context.scene.objects if obj.type == 'MESH']+ self._threads_left = len(mesh_objects)+ else:+ self._threads_left = len(self._cameras)+++ # Refine mode preparation+ if context.scene.generation_method == 'refine':+ for i, camera in enumerate(self._cameras):+ bpy.context.scene.camera = camera+ export_emit_image(context, camera_id=i)++ # UV inpainting mode preparation+ if context.scene.generation_method == 'uv_inpaint':+ # Check if there are baked textures for all objects+ mesh_objects = [obj for obj in bpy.context.scene.objects if obj.type == 'MESH']++ if self.show_prompt_dialog:+ # Start the prompt collection process with the first object+ if not self._object_prompts: # Only if prompts haven't been collected+ self.current_object_name = mesh_objects[0].name+ return context.window_manager.invoke_props_dialog(self, width=400)++ # Continue with normal execution if all prompts are collected+ for obj in mesh_objects:+ # Use get_file_path to check for baked texture existence+ baked_texture_path = get_file_path(context, "baked", object_name=obj.name)+ if not os.path.exists(baked_texture_path):+ # Bake the texture if it doesn't exist+ prepare_baking(context)+ unwrap(obj, method='pack', overlap_only=True)+ bake_texture(context, obj, texture_resolution=2048, output_dir=get_dir_path(context, "baked"))++ # Export visibility masks for each object+ export_visibility(context, obj)++ self.prompt_text = context.scene.comfyui_prompt++ self._progress = 0.0+ self._stage = "Starting"+ redraw_ui(context)+ self._current_image = 0+ self._total_images = len(self._cameras)+ if context.scene.generation_method == 'grid':+ self._total_images = 1+ if context.scene.refine_images:+ self._total_images += len(self._cameras) # Add refinement steps+ elif context.scene.generation_method == 'uv_inpaint':+ self._total_images = len(mesh_objects)++ # Add modal timer+ context.window_manager.modal_handler_add(self)+ self._timer = context.window_manager.event_timer_add(0.5, window=context.window)+ print("Starting thread")+ if context.scene.generation_method == 'grid':+ self._thread = threading.Thread(target=self.async_generate, args=(context,))+ else:+ self._thread = threading.Thread(target=self.async_generate, args=(context, 0))++ self._thread.start()++ return {'RUNNING_MODAL'}+++ def modal(self, context, event):+ """+ Handles modal events.+ :param context: Blender context.+ :param event: Blender event.+ :return: {'PASS_THROUGH'}+ """+ if event.type == 'TIMER':+ redraw_ui(context)++ if not self._thread.is_alive():+ context.window_manager.event_timer_remove(self._timer)+ ComfyUIGenerate._is_running = False+ if self._error:+ if self._error == "'25'" or self._error == "'111'":+ # Probably canceled by user, quietly return+ context.scene.generation_status = 'idle'+ self.report({'WARNING'}, "Generation cancelled.")+ remove_empty_dirs(context)+ return {'CANCELLED'}+ self.report({'ERROR'}, self._error)+ remove_empty_dirs(context)+ context.scene.generation_status = 'idle'+ return {'CANCELLED'}+ self.report({'INFO'}, "Generation complete.")+ context.scene.display_settings.display_device = 'sRGB'+ context.scene.view_settings.view_transform = 'Standard'+ context.scene.generation_status = 'idle'+ # Clear output directories which are not needed anymore+ addon_prefs = context.preferences.addons[__package__].preferences+ # Save blend file in the output directory if enabled+ if addon_prefs.save_blend_file:+ blend_dir = get_dir_path(context, "revision")+ # Save the current blend file in the output directory+ scene_name = os.path.splitext(os.path.basename(bpy.data.filepath))[0]+ if not scene_name:+ scene_name = context.scene.name+ blend_file_path = os.path.join(blend_dir, f"{scene_name}_{context.scene.output_timestamp}.blend")+ # Clean-up unused data blocks+ bpy.ops.outliner.orphans_purge(do_recursive=True)+ # Pack resources and save the blend file+ bpy.ops.file.pack_all()+ bpy.ops.wm.save_as_mainfile(filepath=blend_file_path, copy=True)+ remove_empty_dirs(context)+ return {'FINISHED'}++ # Handle prompt collection for UV inpainting+ if context.scene.generation_method == 'uv_inpaint' and self.show_prompt_dialog:+ mesh_objects = [obj for obj in bpy.context.scene.objects if obj.type == 'MESH']+ current_index = next((i for i, obj in enumerate(mesh_objects)+ if obj.name == self.current_object_name), -1)++ # Store the current prompt+ self._object_prompts[self.current_object_name] = self.current_object_prompt++ # Move to next object or finish+ if current_index < len(mesh_objects) - 1:+ self.current_object_name = mesh_objects[current_index + 1].name+ self.current_object_prompt = ""+ return context.window_manager.invoke_props_dialog(self, width=400)+ else:+ self.show_prompt_dialog = False+ return self.execute(context)++ return {'PASS_THROUGH'}++ def cancel_generate(self, context):+ """+ Cancels the generation process using api.interupt().+ :param context: Blender context.+ :return: None+ """+ server_address = context.preferences.addons[__package__].preferences.server_address+ client_id = str(uuid.uuid4())+ data = json.dumps({"client_id": client_id}).encode('utf-8')+ req = urllib.request.Request("http://{}/interrupt".format(server_address), data=data)+ context.scene.generation_status = 'idle'+ ComfyUIGenerate._is_running = False+ urllib.request.urlopen(req)+ remove_empty_dirs(context)++ def async_generate(self, context, camera_id = None):+ """+ Asynchronously generates the image using ComfyUI.+ :param context: Blender context.+ :return: None+ """+ output_dir = context.preferences.addons[__package__].preferences.output_dir++ self._error = None+ try:+ mesh_objects = None+ if (context.scene.generation_method == 'uv_inpaint'):+ mesh_objects = [obj for obj in bpy.context.scene.objects if obj.type == 'MESH']++ depth_path = None+ canny_path = None+ normal_path = None+ mask_path = None+ render_path = None+ while self._threads_left > 0:+ if context.scene.steps != 0:+ # Generate image without ControlNet if needed+ if camera_id == 0 and (context.scene.generation_method == 'sequential' or context.scene.generation_method == 'separate' or context.scene.generation_method == 'refine')\+ and context.scene.sequential_ipadapter and context.scene.sequential_ipadapter_regenerate and not context.scene.use_ipadapter and context.scene.sequential_ipadapter_mode == 'first'\+ and context.scene.model_architecture == 'sdxl':+ self._stage = "Generating Reference Image"+ # Don't use ControlNet for the first image if sequential_ipadapter_regenerate_wo_controlnet is enabled+ if context.scene.sequential_ipadapter_regenerate_wo_controlnet:+ original_strengths = [unit.strength for unit in context.scene.controlnet_units]+ for unit in context.scene.controlnet_units:+ unit.strength = 0.0+ else:+ self._stage = "Generating Image"+ self._progress = 0+ # Prepare paths using new get_file_path function+ if context.scene.generation_method != 'uv_inpaint':+ # Get paths for controlnet images for the current camera or grid+ depth_path = get_file_path(context, "controlnet", subtype="depth", camera_id=camera_id) if camera_id is not None else get_file_path(context, "controlnet", subtype="depth")+ canny_path = get_file_path(context, "controlnet", subtype="canny", camera_id=camera_id) if camera_id is not None else get_file_path(context, "controlnet", subtype="canny")+ normal_path = get_file_path(context, "controlnet", subtype="normal", camera_id=camera_id) if camera_id is not None else get_file_path(context, "controlnet", subtype="normal")+ else:+ # Get paths for UV inpainting for the current object+ current_obj_name = mesh_objects[self._current_image].name+ mask_path = get_file_path(context, "uv_inpaint", subtype="visibility", object_name=current_obj_name)+ render_path = get_file_path(context, "baked", object_name=current_obj_name) # Use baked texture as input render++ # Generate the image+ if context.scene.generation_method == 'refine':+ render_path = get_file_path(context, "inpaint", subtype="render", camera_id=camera_id)+ if context.scene.model_architecture == 'flux1':+ image = self.refine_flux(context, depth_path=depth_path, canny_path=canny_path, normal_path=normal_path, render_path=render_path)+ else:+ image = self.refine(context, depth_path=depth_path, canny_path=canny_path, normal_path=normal_path, render_path=render_path)+ elif context.scene.generation_method == 'uv_inpaint':+ if context.scene.model_architecture == 'flux1':+ image = self.refine_flux(context, mask_path=mask_path, render_path=render_path)+ else:+ image = self.refine(context, mask_path=mask_path, render_path=render_path)+ elif context.scene.generation_method == 'sequential':+ if self._current_image == 0:+ if context.scene.model_architecture == 'flux1':+ image = self.generate_flux(context, depth_path=depth_path, canny_path=canny_path, normal_path=normal_path)+ else:+ image = self.generate(context, depth_path=depth_path, canny_path=canny_path, normal_path=normal_path)+ else:+ # Get paths for the previous render and mask+ render_path = get_file_path(context, "inpaint", subtype="render", camera_id=self._current_image)+ mask_path = get_file_path(context, "inpaint", subtype="visibility", camera_id=self._current_image)+ if context.scene.model_architecture == 'flux1':+ image = self.refine_flux(context, depth_path=depth_path, render_path=render_path, mask_path=mask_path, canny_path=canny_path, normal_path=normal_path)+ else:+ image = self.refine(context, depth_path=depth_path, render_path=render_path, mask_path=mask_path, canny_path=canny_path, normal_path=normal_path)+ else: # Grid or Separate+ if context.scene.model_architecture == 'flux1':+ image = self.generate_flux(context, depth_path=depth_path, canny_path=canny_path, normal_path=normal_path)+ else:+ image = self.generate(context, depth_path=depth_path, canny_path=canny_path, normal_path=normal_path)++ if image == {"error": "conn_refused"}:+ self._error = "Failed to connect to ComfyUI server."+ return++ # Save the generated image using new path structure+ if context.scene.generation_method == 'uv_inpaint':+ image_path = get_file_path(context, "generated_baked", object_name=mesh_objects[self._current_image].name, material_id=self._material_id)+ elif camera_id is not None:+ image_path = get_file_path(context, "generated", camera_id=camera_id, material_id=self._material_id)+ else: # Grid mode initial generation+ image_path = get_file_path(context, "generated", filename="generated_image_grid") # Save grid to a specific name++ with open(image_path, 'wb') as f:+ f.write(image)++ # Use hack to re-generate the image using IPAdapter to match IPAdapter style+ if camera_id == 0 and (context.scene.generation_method == 'sequential' or context.scene.generation_method == 'separate' or context.scene.generation_method == 'refine')\+ and context.scene.sequential_ipadapter and context.scene.sequential_ipadapter_regenerate and not context.scene.use_ipadapter and context.scene.sequential_ipadapter_mode == 'first'\+ and context.scene.model_architecture == 'sdxl':++ # Restore original strengths+ if context.scene.sequential_ipadapter_regenerate_wo_controlnet:+ for i, unit in enumerate(context.scene.controlnet_units):+ unit.strength = original_strengths[i]+ self._stage = "Generating Image"+ context.scene.use_ipadapter = True+ context.scene.ipadapter_image = image_path+ if context.scene.generation_method == "refine":+ image = self.refine(context, depth_path=depth_path, render_path=render_path, mask_path=mask_path, canny_path=canny_path, normal_path=normal_path)+ else:+ image = self.generate(context, depth_path=depth_path, canny_path=canny_path, normal_path=normal_path)+ context.scene.use_ipadapter = False+ image_path = image_path.replace(".png", "_ipadapter.png")+ with open(image_path, 'wb') as f:+ f.write(image)++ # Sequential mode callback+ if context.scene.generation_method == 'sequential':+ def image_project_callback():+ redraw_ui(context)+ project_image(context, self._material_id, stop_index=self._current_image)+ if self._current_image < len(self._cameras) - 1:+ next_camera_id = self._current_image + 1+ export_visibility(context, camera_visibility=self._cameras[self._current_image]) # Export mask for current view+ export_emit_image(context, camera_id=next_camera_id) # Export render for next view+ # Set the event to signal the end of the process+ self._wait_event.set()+ return None+ bpy.app.timers.register(image_project_callback)+ # Wait for the event to be set+ self._wait_event.wait()+ self._wait_event.clear()+ # Update paths for the next iteration (if any)+ if self._current_image < len(self._cameras) - 1:+ next_camera_id = self._current_image + 1+ render_path = get_file_path(context, "inpaint", subtype="render", camera_id=next_camera_id)+ mask_path = get_file_path(context, "inpaint", subtype="visibility", camera_id=next_camera_id)+ # Update controlnet paths for the next camera+ depth_path = get_file_path(context, "controlnet", subtype="depth", camera_id=next_camera_id)+ canny_path = get_file_path(context, "controlnet", subtype="canny", camera_id=next_camera_id)+ normal_path = get_file_path(context, "controlnet", subtype="normal", camera_id=next_camera_id)++ else: # steps == 0, skip generation+ pass # No image generation needed++ if context.scene.generation_method == 'separate' or context.scene.generation_method == 'refine' or context.scene.generation_method == 'sequential':+ self._current_image += 1+ self._threads_left -= 1+ if camera_id is not None: # Increment camera_id only if it was initially provided+ camera_id += 1++ elif context.scene.generation_method == 'uv_inpaint':+ self._current_image += 1+ self._threads_left -= 1++ elif context.scene.generation_method == 'grid':+ # Split the generated grid image back into multiple images+ self.split_generated_grid(context, self._cameras)+ if context.scene.refine_images:+ for i, _ in enumerate(self._cameras):+ self._stage = f"Refining Image {i+1}/{len(self._cameras)}"+ self._current_image = i + 1+ self._progress = 0+ # Refine the split images+ refine_depth_path = get_file_path(context, "controlnet", subtype="depth", camera_id=i)+ refine_canny_path = get_file_path(context, "controlnet", subtype="canny", camera_id=i)+ refine_normal_path = get_file_path(context, "controlnet", subtype="normal", camera_id=i)+ refine_render_path = get_file_path(context, "generated", camera_id=i, material_id=self._material_id) # Use the split image as render input++ if context.scene.model_architecture == 'flux1':+ image = self.refine_flux(context, depth_path=refine_depth_path, canny_path=refine_canny_path, normal_path=refine_normal_path, render_path=refine_render_path)+ else:+ image = self.refine(context, depth_path=refine_depth_path, canny_path=refine_canny_path, normal_path=refine_normal_path, render_path=refine_render_path)++ if image == {"error": "conn_refused"}:+ self._error = "Failed to connect to ComfyUI server."+ return+ # Overwrite the split image with the refined one+ image_path = get_file_path(context, "generated", camera_id=i, material_id=self._material_id)+ with open(image_path, 'wb') as f:+ f.write(image)+ self._threads_left = 0++ except Exception as e:+ self._error = str(e)+ return++ def image_project_callback():+ if context.scene.generation_method == 'sequential':+ return None+ self._stage = "Projecting Image"+ if context.scene.bake_texture:+ self._stage = "Baking Textures & Projecting"+ redraw_ui(context)+ if context.scene.generation_method != 'uv_inpaint':+ project_image(context, self._material_id)+ else:+ # Apply the UV inpainted textures to each mesh+ from .render_tools import apply_uv_inpaint_texture+ mesh_objects = [obj for obj in bpy.context.scene.objects if obj.type == 'MESH']+ for obj in mesh_objects:+ texture_path = get_file_path(+ context, "generated_baked", object_name=obj.name, material_id=self._material_id+ )+ apply_uv_inpaint_texture(context, obj, texture_path)+ return None++ bpy.app.timers.register(image_project_callback)++ # Update seed based on control parameter+ if context.scene.control_after_generate == 'increment':+ context.scene.seed += 1+ elif context.scene.control_after_generate == 'decrement':+ context.scene.seed -= 1+ elif context.scene.control_after_generate == 'randomize':+ context.scene.seed = np.random.randint(0, 1000000)++ def generate(self, context, depth_path=None, canny_path=None, normal_path=None):+ """+ Generates the image using ComfyUI.+ :param context: Blender context.+ :param depth_path: Path to the depth map image.+ :param canny_path: Path to the canny edge image.+ :param normal_path: Path to the normal map image.+ :return: Generated image binary data.+ """+ from .util.helpers import prompt_text++ # Setup connection parameters+ server_address = context.preferences.addons[__package__].preferences.server_address+ client_id = str(uuid.uuid4())+ # Get revision dir for debug file+ revision_dir = get_generation_dirs(context)["revision"]++ # Initialize the prompt template and get node mappings+ prompt, NODES = self._create_base_prompt(context)++ # Set model resolution+ self._configure_resolution(prompt, context, NODES)++ if context.scene.use_ipadapter or (context.scene.generation_method == 'separate' and context.scene.sequential_ipadapter and self._current_image > 0):+ # Configure IPAdapter settings+ self._configure_ipadapter(prompt, context, NODES)++ # Build controlnet chain+ prompt = self._build_controlnet_chain(prompt, context, depth_path, canny_path, normal_path, NODES)++ # Save prompt for debugging (in revision dir)+ self._save_prompt_to_file(prompt, revision_dir)++ # Execute generation and get results+ try:+ ws = self._connect_to_websocket(server_address, client_id)+ images = self._execute_prompt_and_get_images(ws, prompt, client_id, server_address, NODES)+ ws.close()+ except ConnectionRefusedError:+ return {"error": "conn_refused"}++ print(f"Image generated with prompt: {context.scene.comfyui_prompt}")++ # Return the generated image from the save_image node+ return images[NODES['save_image']][0]++ def _create_base_prompt(self, context):+ """Creates and configures the base prompt with user settings."""+ from .util.helpers import prompt_text++ # Load the base prompt template+ prompt = json.loads(prompt_text)++ # Node IDs organized by functional category+ NODES = {+ # Text Prompting+ 'pos_prompt': "9",+ 'neg_prompt': "10",+ 'clip_skip': "247",++ # Sampling Control+ 'sampler': "15",+ 'seed_control': "15", # Same as sampler node but for seed parameter++ # Model Loading+ 'checkpoint': "6",+ 'lora': "26",++ # Latent Space+ 'latent': "16",++ # Image Output+ 'save_image': "25",++ # IPAdapter+ 'ipadapter': "236",+ 'ipadapter_image': "237",+ }++ base_prompt_text = context.scene.comfyui_prompt+ # Camera Prompt Injection+ if context.scene.use_camera_prompts and context.scene.generation_method in ['separate', 'sequential', 'refine'] and self._cameras and self._current_image < len(self._cameras):+ current_camera_name = self._cameras[self._current_image].name+ # Find the prompt in the collection+ prompt_item = next((item for item in context.scene.camera_prompts if item.name == current_camera_name), None)+ if prompt_item and prompt_item.prompt:+ view_desc = prompt_item.prompt+ # Prepend the view description+ base_prompt_text = f"{view_desc}, {base_prompt_text}"++ # Set text prompts+ prompt[NODES['pos_prompt']]["inputs"]["text"] = base_prompt_text+ prompt[NODES['neg_prompt']]["inputs"]["text"] = context.scene.comfyui_negative_prompt++ # Set sampling parameters+ prompt[NODES['sampler']]["inputs"]["seed"] = context.scene.seed+ prompt[NODES['sampler']]["inputs"]["steps"] = context.scene.steps+ prompt[NODES['sampler']]["inputs"]["cfg"] = context.scene.cfg+ prompt[NODES['sampler']]["inputs"]["sampler_name"] = context.scene.sampler+ prompt[NODES['sampler']]["inputs"]["scheduler"] = context.scene.scheduler++ # Set clip skip+ prompt[NODES['clip_skip']]["stop_at_clip_layer"] = -context.scene.clip_skip++ # Set LoRA parameters+ self._configure_lora(prompt, context, NODES['lora'])++ # Set the model name+ prompt[NODES['checkpoint']]["inputs"]["ckpt_name"] = context.scene.model_name++ return prompt, NODES++ def _configure_lora(self, prompt, context, lora_node):+ """Configures the LoRA settings based on user selection."""+ lora_mapping = {+ 'hyper_8step': "Hyper-SDXL-8steps-lora.safetensors",+ 'lightning_8step': "sdxl_lightning_8step_lora.safetensors",+ 'hyper_4step': "Hyper-SDXL-4steps-lora.safetensors",+ 'lightning_4step': "sdxl_lightning_4step_lora.safetensors",+ 'hyper_1step': "Hyper-SDXL-1step-lora.safetensors",+ 'lightning_2step': "sdxl_lightning_2step_lora.safetensors"+ }++ if context.scene.lora_type in lora_mapping:+ prompt[lora_node]["inputs"]["lora_name"] = lora_mapping[context.scene.lora_type]+ else:+ # Disable LoRA if not selected+ prompt[lora_node]["inputs"]["strength_model"] = 0+ prompt[lora_node]["inputs"]["strength_clip"] = 0++ def _configure_resolution(self, prompt, context, NODES):+ """Sets the generation resolution based on mode."""+ if context.scene.generation_method == 'grid':+ # Use the resolution of the grid image+ prompt[NODES['latent']]["inputs"]["width"] = self._grid_width+ prompt[NODES['latent']]["inputs"]["height"] = self._grid_height+ else:+ # Use current render resolution+ prompt[NODES['latent']]["inputs"]["width"] = context.scene.render.resolution_x+ prompt[NODES['latent']]["inputs"]["height"] = context.scene.render.resolution_y++ def _configure_ipadapter(self, prompt, context, NODES):+ # Configure IPAdapter if enabled++ # Connect IPAdapter output to the appropriate node+ prompt[NODES['sampler']]["inputs"]["model"] = [NODES['ipadapter'], 0]++ # Set IPAdapter image source based on ipadapter_image+ if context.scene.use_ipadapter:+ image_path = bpy.path.abspath(context.scene.ipadapter_image)+ prompt[NODES['ipadapter_image']]["inputs"]["image"] = image_path+ elif context.scene.sequential_ipadapter:+ if context.scene.sequential_ipadapter_mode == 'first':+ prompt[NODES['ipadapter_image']]["inputs"]["image"] = get_file_path(context, "generated", camera_id=0, material_id=self._material_id)+ else:+ prompt[NODES['ipadapter_image']]["inputs"]["image"] = get_file_path(context, "generated", camera_id=self._current_image - 1, material_id=self._material_id)++ # Connect ipadapter image to the input+ prompt[NODES['ipadapter']]["inputs"]["image"] = [NODES['ipadapter_image'], 0]++ # Configure IPAdapter settings+ prompt[NODES['ipadapter']]["inputs"]["weight"] = context.scene.ipadapter_strength+ prompt[NODES['ipadapter']]["inputs"]["start_at"] = context.scene.ipadapter_start+ prompt[NODES['ipadapter']]["inputs"]["end_at"] = context.scene.ipadapter_end++ # Set weight type+ weight_type_mapping = {+ 'standard': "standard",+ 'prompt': "prompt is more important",+ 'style': "style transfer"+ }+ prompt[NODES['ipadapter']]["inputs"]["weight_type"] = weight_type_mapping.get(context.scene.ipadapter_weight_type, "standard")++ def _build_controlnet_chain(self, prompt, context, depth_path, canny_path, normal_path, NODES):+ """Builds the ControlNet processing chain."""+ # Build controlnet chain with guidance images+ prompt, final_node = build_controlnet_chain_extended(+ context, prompt, NODES['pos_prompt'], NODES['neg_prompt'], NODES['checkpoint'],+ {"depth": depth_path, "canny": canny_path, "normal": normal_path}+ )++ # Connect final node outputs to the KSampler+ prompt[NODES['sampler']]["inputs"]["positive"] = [final_node, 0]+ prompt[NODES['sampler']]["inputs"]["negative"] = [final_node, 1]++ return prompt++ def _save_prompt_to_file(self, prompt, output_dir):+ """Saves the prompt to a file for debugging."""+ try:+ with open(os.path.join(output_dir, "prompt.json"), 'w') as f:+ json.dump(prompt, f, indent=2) # Added indent for better readability+ except Exception as e:+ print(f"Failed to save prompt to file: {str(e)}")++ def _connect_to_websocket(self, server_address, client_id):+ """Establishes WebSocket connection to ComfyUI server."""+ try:+ ws = websocket.WebSocket()+ ws.connect(f"ws://{server_address}/ws?clientId={client_id}")+ return ws+ except Exception as e:+ print(f"WebSocket connection failed: {str(e)}")+ raise++ def _execute_prompt_and_get_images(self, ws, prompt, client_id, server_address, NODES):+ """Executes the prompt and collects generated images."""+ # Send the prompt to the queue+ prompt_id = self._queue_prompt(prompt, client_id, server_address)++ # Process the WebSocket messages and collect images+ output_images = {}+ current_node = ""++ while True:+ out = ws.recv()+ if isinstance(out, str):+ message = json.loads(out)++ if message['type'] == 'executing':+ data = message['data']+ if data['prompt_id'] == prompt_id:+ if data['node'] is None:+ break # Execution is complete+ else:+ current_node = data['node']+ print(f"Executing node: {current_node}")++ elif message['type'] == 'progress':+ progress = (message['data']['value'] / message['data']['max']) * 100+ if progress != 0:+ self._progress = progress # Update progress for UI+ print(f"Progress: {progress:.1f}%")+ else:+ # Binary data (image)+ if current_node == NODES['save_image']: # SaveImageWebsocket node+ print("Receiving generated image")+ images_output = output_images.get(current_node, [])+ images_output.append(out[8:]) # Skip the first 8 bytes (header)+ output_images[current_node] = images_output++ return output_images++ def _queue_prompt(self, prompt, client_id, server_address):+ """Queues the prompt for processing by ComfyUI."""+ try:+ data = json.dumps({+ "prompt": prompt,+ "client_id": client_id+ }).encode('utf-8')++ req = urllib.request.Request(f"http://{server_address}/prompt", data=data)+ response = json.loads(urllib.request.urlopen(req).read())++ return response['prompt_id']+ except Exception as e:+ print(f"Failed to queue prompt: {str(e)}")+ raise++ def refine(self, context, depth_path=None, canny_path=None, mask_path=None, render_path=None, normal_path=None):+ """+ Refines the image using ComfyUI.+ :param context: Blender context.+ :param depth_path: Path to the depth map image.+ :param canny_path: Path to the canny edge image.+ :param mask_path: Path to the mask image for inpainting.+ :param render_path: Path to the input render image.+ :param normal_path: Path to the normal map image.+ :return: Refined image.+ """+ # Setup connection parameters+ server_address = context.preferences.addons[__package__].preferences.server_address+ client_id = str(uuid.uuid4())+ output_dir = get_generation_dirs(context)["revision"]++ # Initialize the img2img prompt template and configure base settings+ prompt, NODES = self._create_img2img_base_prompt(context)++ # Configure based on generation method+ self._configure_refinement_mode(prompt, context, render_path, mask_path, NODES)++ if (context.scene.use_ipadapter or (context.scene.sequential_ipadapter and self._current_image > 0)) and context.scene.generation_method != 'uv_inpaint':+ # Configure IPAdapter settings+ self._configure_ipadapter_refine(prompt, context, NODES)++ # Set up image inputs for different controlnet types+ self._refine_configure_images(prompt, depth_path, canny_path, normal_path, render_path, NODES)++ # Build controlnet chain for refinement if needed+ if not context.scene.generation_method == 'uv_inpaint':+ prompt = self._refine_build_controlnet_chain(prompt, context, depth_path, canny_path, normal_path, NODES)+ else:+ if context.scene.differential_diffusion:+ prompt[NODES['sampler']]["inputs"]["positive"] = [NODES['inpaint_conditioning'], 0]+ prompt[NODES['sampler']]["inputs"]["negative"] = [NODES['inpaint_conditioning'], 1]+ else:+ prompt[NODES['sampler']]["inputs"]["positive"] = [NODES['pos_prompt'], 0]+ prompt[NODES['sampler']]["inputs"]["negative"] = [NODES['neg_prompt'], 0]++ # Save prompt for debugging+ with open(os.path.join(output_dir, "prompt.json"), 'w') as f:+ json.dump(prompt, f)++ # Execute generation and get results+ try:+ ws = websocket.WebSocket()+ ws.connect(f"ws://{server_address}/ws?clientId={client_id}")+ images = self._refine_get_images(ws, prompt, client_id, server_address, NODES)+ ws.close()+ except ConnectionRefusedError:+ return {"error": "conn_refused"}++ print(f"Image refined with prompt: {context.scene.refine_prompt if context.scene.refine_prompt else context.scene.comfyui_prompt}")++ # Return the refined image+ return images[NODES['save_image']][0]++ def _create_img2img_base_prompt(self, context):+ """Creates and configures the base prompt for img2img refinement."""+ from .util.helpers import prompt_text_img2img++ prompt = json.loads(prompt_text_img2img)++ # Node IDs organized by functional category+ NODES = {+ # Text Prompting+ 'pos_prompt': "102",+ 'neg_prompt': "103",+ 'clip_skip': "247",++ # Sampling Control+ 'sampler': "105",++ # Model Loading+ 'checkpoint': "38",+ 'lora': "37",++ # Image Processing+ 'upscale_grid': "118",+ 'upscale_uv': "23",+ 'vae_encode': "116",+ 'vae_encode_inpaint': "13",+ 'inpaint_conditioning': "228",++ # Input Images+ 'input_image': "1",+ 'mask_image': "12",+ 'render_image': "117",+ 'depth_image': "108",++ # Mask Processing+ 'grow_mask': "224",+ 'blur': "226",+ 'image_to_mask': "227",++ # Advanced Features+ 'differential_diffusion': "229",+ 'ipadapter': "236",+ 'ipadapter_image': "237",++ # Output+ 'save_image': "111"+ }++ base_prompt_text = context.scene.comfyui_prompt+ # Camera Prompt Injection+ if context.scene.use_camera_prompts and context.scene.generation_method in ['separate', 'sequential', 'refine', 'grid'] and self._cameras and self._current_image < len(self._cameras):+ current_camera_name = self._cameras[self._current_image].name+ # Find the prompt in the collection+ prompt_item = next((item for item in context.scene.camera_prompts if item.name == current_camera_name), None)+ if prompt_item and prompt_item.prompt:+ view_desc = prompt_item.prompt+ # Prepend the view description+ base_prompt_text = f"{view_desc}, {base_prompt_text}"++ # Set positive prompt based on generation method+ if context.scene.generation_method in ['refine', 'uv_inpaint', 'sequential']:+ prompt[NODES['pos_prompt']]["inputs"]["text"] = base_prompt_text+ else:+ prompt[NODES['pos_prompt']]["inputs"]["text"] = context.scene.refine_prompt if context.scene.refine_prompt != "" else context.scene.comfyui_prompt++ # Set negative prompt+ prompt[NODES['neg_prompt']]["inputs"]["text"] = context.scene.comfyui_negative_prompt++ # Set sampling parameters+ prompt[NODES['sampler']]["inputs"]["seed"] = context.scene.seed+ prompt[NODES['sampler']]["inputs"]["steps"] = context.scene.refine_steps if context.scene.generation_method == 'grid' else context.scene.steps+ prompt[NODES['sampler']]["inputs"]["cfg"] = context.scene.refine_cfg if context.scene.generation_method == 'grid' else context.scene.cfg+ prompt[NODES['sampler']]["inputs"]["sampler_name"] = context.scene.refine_sampler if context.scene.generation_method == 'grid' else context.scene.sampler+ prompt[NODES['sampler']]["inputs"]["scheduler"] = context.scene.refine_scheduler if context.scene.generation_method == 'grid' else context.scene.scheduler+ if context.scene.generation_method == 'grid' or context.scene.generation_method == 'refine':+ prompt[NODES['sampler']]["inputs"]["denoise"] = context.scene.denoise+ else:+ prompt[NODES['sampler']]["inputs"]["denoise"] = 1.0++ # Set clip skip+ prompt[NODES['clip_skip']]["stop_at_clip_layer"] = -context.scene.clip_skip++ # Set upscale method and dimensions+ prompt[NODES['upscale_grid']]["inputs"]["upscale_method"] = context.scene.refine_upscale_method+ prompt[NODES['upscale_grid']]["inputs"]["width"] = context.scene.render.resolution_x+ prompt[NODES['upscale_grid']]["inputs"]["height"] = context.scene.render.resolution_y+ prompt[NODES['upscale_uv']]["inputs"]["upscale_method"] = "nearest-exact"+ prompt[NODES['upscale_uv']]["inputs"]["width"] = 1024+ prompt[NODES['upscale_uv']]["inputs"]["height"] = 1024++ # Set the model name+ prompt[NODES['checkpoint']]["inputs"]["ckpt_name"] = context.scene.model_name++ # Configure LoRA+ self._configure_lora_for_refinement(prompt, context, NODES['lora'])++ return prompt, NODES++ def _configure_lora_for_refinement(self, prompt, context, lora_node):+ """Configures the LoRA settings for the refinement process."""+ lora_mapping = {+ 'hyper_8step': "Hyper-SDXL-8steps-lora.safetensors",+ 'lightning_8step': "sdxl_lightning_8step_lora.safetensors",+ 'hyper_4step': "Hyper-SDXL-4steps-lora.safetensors",+ 'lightning_4step': "sdxl_lightning_4step_lora.safetensors",+ 'hyper_1step': "Hyper-SDXL-1step-lora.safetensors",+ 'lightning_2step': "sdxl_lightning_2step_lora.safetensors"+ }++ if context.scene.lora_type in lora_mapping:+ prompt[lora_node]["inputs"]["lora_name"] = lora_mapping[context.scene.lora_type]+ else:+ # Disable LoRA if not selected+ prompt[lora_node]["inputs"]["strength_model"] = 0+ prompt[lora_node]["inputs"]["strength_clip"] = 0++ def _configure_refinement_mode(self, prompt, context, render_path, mask_path, NODES):+ """Configures the prompt based on the specific refinement mode."""+ # Configure based on generation method+ if context.scene.generation_method == 'refine':+ prompt[NODES['vae_encode']]["inputs"]["pixels"] = [NODES['render_image'], 0] # Use render directly++ elif context.scene.generation_method == 'uv_inpaint' or context.scene.generation_method == 'sequential':+ # Connect latent to KSampler+ prompt[NODES['sampler']]["inputs"]["latent_image"] = [NODES['vae_encode_inpaint'], 0] if not context.scene.differential_diffusion else [NODES['inpaint_conditioning'], 2]++ # Configure differential diffusion if enabled+ if context.scene.differential_diffusion:+ prompt[NODES['sampler']]["inputs"]["model"] = [NODES['differential_diffusion'], 0]++ # Configure mask settings+ prompt[NODES['mask_image']]["inputs"]["image"] = mask_path+ prompt[NODES['input_image']]["inputs"]["image"] = render_path++ # Configure mask blur settings+ if not context.scene.blur_mask:+ prompt[NODES['inpaint_conditioning']]["inputs"]["mask"] = [NODES['grow_mask'], 0] # Direct connection+ prompt[NODES['vae_encode_inpaint']]["inputs"]["mask"] = [NODES['grow_mask'], 0] # Direct connection++ # Set blur parameters+ prompt[NODES['blur']]["inputs"]["sigma"] = context.scene.blur_mask_sigma+ prompt[NODES['blur']]["inputs"]["blur_radius"] = context.scene.blur_mask_radius++ # Set grow mask parameter+ prompt[NODES['grow_mask']]["inputs"]["expand"] = context.scene.grow_mask_by++ if context.scene.generation_method == 'uv_inpaint':+ # Configure UV inpainting specific prompts+ self._configure_uv_inpainting_mode(prompt, context, render_path, NODES)+ else: # Sequential mode+ # Configure sequential mode settings+ self._configure_sequential_mode(prompt, context, render_path, NODES)++ def _configure_uv_inpainting_mode(self, prompt, context, render_path, NODES):+ """Configures the prompts for UV inpainting mode."""+ # Connect upscale to VAE / InpaintConditioning+ if not context.scene.differential_diffusion:+ prompt[NODES['vae_encode_inpaint']]["inputs"]["pixels"] = [NODES['upscale_uv'], 0]+ else:+ prompt[NODES['inpaint_conditioning']]["inputs"]["pixels"] = [NODES['upscale_uv'], 0]+ # Set the noise_mask flag according to context.scene.differential_noise+ prompt[NODES['inpaint_conditioning']]["inputs"]["noise_mask"] = context.scene.differential_noise++ # Create base UV prompt+ uv_prompt = f"seamless (UV-unwrapped texture) of {context.scene.comfyui_prompt}, consistent material continuity, no visible seams or stretching, PBR material properties"+ uv_prompt_neg = f"seam, stitch, visible edge, texture stretching, repeating pattern, {context.scene.comfyui_negative_prompt}"++ prompt[NODES['pos_prompt']]["inputs"]["text"] = uv_prompt+ prompt[NODES['neg_prompt']]["inputs"]["text"] = uv_prompt_neg++ # Get the current object name from the file path+ current_object_name = os.path.basename(render_path).split('.')[0]++ # Use the object-specific prompt if available+ object_prompt = self._object_prompts.get(current_object_name, context.scene.comfyui_prompt)+ if object_prompt:+ uv_prompt = f"(UV-unwrapped texture) of {object_prompt}, consistent material continuity, no visible seams or stretching, PBR material properties"+ uv_prompt_neg = f"seam, stitch, visible edge, texture stretching, repeating pattern, {context.scene.comfyui_negative_prompt}"+ prompt[NODES['pos_prompt']]["inputs"]["text"] = uv_prompt+ prompt[NODES['neg_prompt']]["inputs"]["text"] = uv_prompt_neg++ def _configure_ipadapter_refine(self, prompt, context, NODES):+ # Connect IPAdapter output to the appropriate node+ if context.scene.differential_diffusion and context.scene.generation_method != 'refine':+ prompt[NODES['differential_diffusion']]["inputs"]["model"] = [NODES['ipadapter'], 0]+ else:+ prompt[NODES['sampler']]["inputs"]["model"] = [NODES['ipadapter'], 0]++ if context.scene.use_ipadapter:+ # Set IPAdapter image source based on ipadapter_image+ image_path = bpy.path.abspath(context.scene.ipadapter_image)+ prompt[NODES['ipadapter_image']]["inputs"]["image"] = image_path+ else: # Mode-specific IPAdapter+ if context.scene.sequential_ipadapter_mode == 'first':+ prompt[NODES['ipadapter_image']]["inputs"]["image"] = get_file_path(context, "generated", camera_id=0, material_id=self._material_id)+ else:+ prompt[NODES['ipadapter_image']]["inputs"]["image"] = get_file_path(context, "generated", camera_id=self._current_image - 1, material_id=self._material_id)+++ # Connect ipadapter image to the input+ prompt[NODES['ipadapter']]["inputs"]["image"] = [NODES['ipadapter_image'], 0]++ # Configure IPAdapter settings+ prompt[NODES['ipadapter']]["inputs"]["weight"] = context.scene.ipadapter_strength+ prompt[NODES['ipadapter']]["inputs"]["start_at"] = context.scene.ipadapter_start+ prompt[NODES['ipadapter']]["inputs"]["end_at"] = context.scene.ipadapter_end++ # Set weight type+ weight_type_mapping = {+ 'standard': "standard",+ 'prompt': "prompt is more important",+ 'style': "style transfer"+ }+ prompt[NODES['ipadapter']]["inputs"]["weight_type"] = weight_type_mapping.get(context.scene.ipadapter_weight_type, "standard")++ def _configure_sequential_mode(self, prompt, context, render_path, NODES):+ """Configures the prompt for sequential generation mode."""+ # Connect image directly to VAE+ prompt[NODES['vae_encode_inpaint']]["inputs"]["pixels"] = [NODES['input_image'], 0]+ if context.scene.differential_diffusion:+ # Set the noise_mask flag according to context.scene.differential_noise+ prompt[NODES['inpaint_conditioning']]["inputs"]["noise_mask"] = context.scene.differential_noise++ def _refine_configure_images(self, prompt, depth_path, canny_path, normal_path, render_path, NODES):+ """Configures the input images for the refinement process."""+ # Set depth map+ if depth_path:+ prompt[NODES['depth_image']]["inputs"]["image"] = depth_path++ # Set render image+ if render_path:+ prompt[NODES['render_image']]["inputs"]["image"] = render_path++ def _refine_build_controlnet_chain(self, prompt, context, depth_path, canny_path, normal_path, NODES):+ """Builds the ControlNet chain for refinement process."""+ # Determine inputs for ControlNet chain+ pos_input = NODES['pos_prompt'] if (not context.scene.differential_diffusion or+ context.scene.generation_method in ["grid", "refine"]) else NODES['inpaint_conditioning']+ neg_input = NODES['neg_prompt'] if (not context.scene.differential_diffusion or+ context.scene.generation_method in ["grid", "refine"]) else NODES['inpaint_conditioning']+ vae_input = NODES['checkpoint']++ # Build the ControlNet chain+ prompt, final = build_controlnet_chain_extended(+ context, prompt, pos_input, neg_input, vae_input,+ {"depth": depth_path, "canny": canny_path, "normal": normal_path}+ )++ # Connect final outputs to KSampler+ prompt[NODES['sampler']]["inputs"]["positive"] = [final, 0]+ prompt[NODES['sampler']]["inputs"]["negative"] = [final, 1]++ return prompt++ def _refine_get_images(self, ws, prompt, client_id, server_address, NODES):+ """Executes the refinement prompt and collects the results."""+ # Queue the prompt+ prompt_id = self._queue_prompt(prompt, client_id, server_address)++ # Process WebSocket messages+ output_images = {}+ current_node = ""++ while True:+ out = ws.recv()+ if isinstance(out, str):+ message = json.loads(out)++ if message['type'] == 'executing':+ data = message['data']+ if data['prompt_id'] == prompt_id:+ if data['node'] is None:+ break # Execution complete+ else:+ current_node = data['node']++ elif message['type'] == 'progress':+ progress = (message['data']['value'] / message['data']['max']) * 100+ if progress != 0:+ self._progress = progress # Update progress for UI+ else:+ # Binary data (image)+ if current_node == NODES['save_image']: # Save image node+ images_output = output_images.get(current_node, [])+ images_output.append(out[8:]) # Skip header bytes+ output_images[current_node] = images_output++ return output_images++ def export_depthmap(self, context, camera_id=None):+ """+ Exports the depth map of the scene.+ :param context: Blender context.+ :param camera_id: ID of the camera.+ :return: None+ """+ print("Exporting depth map")+ # Save original settings to restore later.+ original_engine = bpy.context.scene.render.engine+ original_view_transform = bpy.context.scene.view_settings.view_transform+ original_film_transparent = bpy.context.scene.render.film_transparent++ # Set animation frame to 1+ bpy.context.scene.frame_set(1)++ output_dir = get_dir_path(context, "controlnet")["depth"]+ output_file = f"depth_map{camera_id}" if camera_id is not None else "depth_map"++ # Ensure the directory exists+ if not os.path.exists(output_dir):+ os.makedirs(output_dir)++ # Get the active view layer+ view_layer = bpy.context.view_layer++ # Switch to WORKBENCH render engine+ bpy.context.scene.render.engine = 'BLENDER_WORKBENCH'++ bpy.context.scene.display_settings.display_device = 'sRGB'+ bpy.context.scene.view_settings.view_transform = 'Raw'++ # Enable depth pass in the render settings+ view_layer.use_pass_z = True++ # Use the compositor to save the depth pass+ bpy.context.scene.use_nodes = True+ nodes = bpy.context.scene.node_tree.nodes+ links = bpy.context.scene.node_tree.links++ # Ensure animation format is not selected+ bpy.context.scene.render.image_settings.file_format = 'PNG'++ # Clear default nodes+ for node in nodes:+ nodes.remove(node)++ # Add render layers node+ render_layers_node = nodes.new(type="CompositorNodeRLayers")+ render_layers_node.location = (0, 0)++ # Add a normalize node (to scale depth values between 0 and 1)+ normalize_node = nodes.new(type="CompositorNodeNormalize")+ normalize_node.location = (200, 0)+ links.new(render_layers_node.outputs["Depth"], normalize_node.inputs[0])++ # Add an invert node to flip the depth map values+ invert_node = nodes.new(type="CompositorNodeInvert")+ invert_node.location = (400, 0)+ links.new(normalize_node.outputs[0], invert_node.inputs[1])++ # Add an output file node+ output_node = nodes.new(type="CompositorNodeOutputFile")+ output_node.location = (600, 0)+ output_node.base_path = output_dir+ output_node.file_slots[0].path = output_file+ output_node.format.file_format = "PNG" # Save as PNG+ links.new(invert_node.outputs[0], output_node.inputs[0])++ # Render the scene+ bpy.ops.render.render(write_still=True)++ bpy.context.scene.view_settings.view_transform = 'Standard'++ print(f"Depth map saved to: {os.path.join(output_dir, output_file)}.png")++ # Restore original settings+ bpy.context.scene.render.engine = original_engine+ bpy.context.scene.view_settings.view_transform = original_view_transform+ bpy.context.scene.render.film_transparent = original_film_transparent++ def export_normal(self, context, camera_id=None):+ """+ Exports the normal map of the scene.+ Areas without geometry will show the neutral color (0.5, 0.5, 1.0).+ :param context: Blender context.+ :param camera_id: ID of the camera.+ :return: None+ """+ print("Exporting normal map")+ bpy.context.scene.frame_set(1)+ output_dir = get_dir_path(context, "controlnet")["normal"]+ output_file = f"normal_map{camera_id}" if camera_id is not None else "normal_map"++ if not os.path.exists(output_dir):+ os.makedirs(output_dir)++ view_layer = bpy.context.view_layer+ view_layer.use_pass_normal = True++ # Store original settings to restore later.+ original_engine = bpy.context.scene.render.engine+ original_view_transform = bpy.context.scene.view_settings.view_transform+ original_film_transparent = bpy.context.scene.render.film_transparent++ bpy.context.scene.render.engine = 'BLENDER_EEVEE_NEXT'+ bpy.context.scene.view_settings.view_transform = 'Raw'+ bpy.context.scene.render.film_transparent = True+ bpy.context.scene.use_nodes = True++ # Disable unnecessary passes.+ view_layer.use_pass_z = False+ view_layer.use_pass_uv = False+ view_layer.use_pass_combined = False+ view_layer.use_pass_emit = False+ view_layer.use_pass_environment = False+ view_layer.use_pass_mist = False++ # Clear existing nodes.+ nodes = bpy.context.scene.node_tree.nodes+ links = bpy.context.scene.node_tree.links+ for node in nodes:+ nodes.remove(node)++ # Create the Render Layers node (provides the baked normal pass).+ render_layers_node = nodes.new(type="CompositorNodeRLayers")+ render_layers_node.location = (0, 0)++ # Create an RGB node set to the neutral normal color (0.5, 0.5, 1.0, 1.0).+ bg_node = nodes.new(type="CompositorNodeRGB")+ bg_node.outputs[0].default_value = (0.5, 0.5, 1.0, 1.0)+ bg_node.location = (0, -200)++ alpha_over_node = nodes.new(type="CompositorNodeAlphaOver")+ alpha_over_node.location = (200, 0)+ # Link the normal pass to the top input.+ links.new(render_layers_node.outputs["Normal"], alpha_over_node.inputs[2])+ # Link the neutral background to the bottom input.+ links.new(bg_node.outputs[0], alpha_over_node.inputs[1])++ # Create the Output File node.+ output_node = nodes.new(type="CompositorNodeOutputFile")+ output_node.location = (400, 0)+ output_node.base_path = output_dir+ output_node.file_slots[0].path = output_file+ output_node.format.file_format = "PNG"+ links.new(alpha_over_node.outputs[0], output_node.inputs[0])+ links.new(render_layers_node.outputs["Alpha"], alpha_over_node.inputs[0])++ bpy.ops.render.render(write_still=True)++ # Restore original settings.+ bpy.context.scene.render.engine = original_engine+ bpy.context.scene.view_settings.view_transform = original_view_transform+ bpy.context.scene.render.film_transparent = original_film_transparent++ print(f"Normal map saved to: {os.path.join(output_dir, output_file)}.png")++ def combine_maps(self, context, cameras, type):+ """Combines depth maps into a grid."""+ if type == 'depth':+ grid_image_path = get_file_path(context, "controlnet", subtype="depth", camera_id=None, material_id=self._material_id)+ elif type == 'canny':+ grid_image_path = get_file_path(context, "controlnet", subtype="canny", camera_id=None, material_id=self._material_id)+ elif type == 'normal':+ grid_image_path = get_file_path(context, "controlnet", subtype="normal", camera_id=None, material_id=self._material_id)++ # Render depth maps for each camera and combine them into a grid+ depth_maps = []+ for i, camera in enumerate(cameras):+ bpy.context.scene.camera = camera+ if type == 'depth':+ depth_map_path = get_file_path(context, "controlnet", subtype="depth", camera_id=i, material_id=self._material_id)+ elif type == 'canny':+ depth_map_path = get_file_path(context, "controlnet", subtype="canny", camera_id=i, material_id=self._material_id)+ elif type == 'normal':+ depth_map_path = get_file_path(context, "controlnet", subtype="normal", camera_id=i, material_id=self._material_id)+ depth_maps.append(depth_map_path)++ # Combine depth maps into a grid+ grid_image = self.create_grid_image(depth_maps)+ grid_image = self.rescale_to_1mp(grid_image)+ grid_image.save(grid_image_path)+ print(f"Combined depth map grid saved to: {grid_image_path}")++ def create_grid_image(self, image_paths):+ """Creates a grid image from a list of image paths."""+ images = [Image.open(path) for path in image_paths]+ widths, heights = zip(*(i.size for i in images))++ # Calculate grid dimensions to make it as square as possible+ num_images = len(images)+ grid_width = math.ceil(math.sqrt(num_images))+ grid_height = math.ceil(num_images / grid_width)++ max_width = max(widths)+ max_height = max(heights)++ total_width = grid_width * max_width+ total_height = grid_height * max_height++ grid_image = Image.new('RGB', (total_width, total_height))++ x_offset = 0+ y_offset = 0+ for i, img in enumerate(images):+ grid_image.paste(img, (x_offset, y_offset))+ x_offset += max_width+ if (i + 1) % grid_width == 0:+ x_offset = 0+ y_offset += max_height++ return grid_image++ def rescale_to_1mp(self, image):+ """Rescales the image to approximately 1MP."""+ from PIL import Image++ width, height = image.size+ total_pixels = width * height+ scale_factor = (1_000_000 / total_pixels) ** 0.5++ new_width = int(width * scale_factor)+ new_height = int(height * scale_factor)++ # Ensure the new dimensions are divisible by 8 (ComfyUI requirement)+ new_width -= new_width % 8+ new_height -= new_height % 8++ self._grid_height = new_height+ self._grid_width = new_width++ return image.resize((new_width, new_height), Image.LANCZOS)++ def split_generated_grid(self, context, cameras):+ """Splits the generated grid image back into multiple images."""+ grid_image_path = get_file_path(context, "generated", camera_id=None, material_id=self._material_id)++ # Load the generated grid image+ from PIL import Image+ grid_image = Image.open(grid_image_path)++ # Calculate grid dimensions to make it as square as possible+ num_images = len(cameras)+ grid_width = math.ceil(math.sqrt(num_images))+ grid_height = math.ceil(num_images / grid_width)++ max_width = grid_image.width // grid_width+ max_height = grid_image.height // grid_height++ x_offset = 0+ y_offset = 0+ for i in range(num_images):+ bbox = (x_offset, y_offset, x_offset + max_width, y_offset + max_height)+ individual_image = grid_image.crop(bbox)+ individual_image_path = get_file_path(context, "generated", camera_id=i, material_id=self._material_id)+ individual_image.save(individual_image_path)+ print(f"Generated image for camera {i+1} saved to: {individual_image_path}")+ x_offset += max_width+ if (i + 1) % grid_width == 0:+ x_offset = 0+ y_offset += max_height++ def draw(self, context):+ layout = self.layout+ if context.scene.generation_method == 'uv_inpaint' and self.show_prompt_dialog:+ layout.label(text=f"Enter prompt for object: {self.current_object_name}")+ layout.prop(self, "current_object_prompt", text="")++ def invoke(self, context, event):+ if context.scene.generation_method == 'uv_inpaint':+ # Reset object prompts on every run+ self._object_prompts = {}+ self._mesh_objects = [obj.name for obj in bpy.context.scene.objects if obj.type == 'MESH']+ self.mesh_index = 0+ self.current_object_name = self._mesh_objects[0] if self._mesh_objects else ""+ # If "Ask for object prompts" is disabled, don’t prompt per object+ if not context.scene.ask_object_prompts:+ self.show_prompt_dialog = False+ return self.execute(context)+ return context.window_manager.invoke_props_dialog(self, width=400)+ return self.execute(context)++ def create_base_prompt_flux(self, context):+ """Creates and configures the base Flux prompt.+ Uses prompt_text_flux and does not include negative prompt or LoRA configuration.+ """+ from .util.helpers import prompt_text_flux+ prompt = json.loads(prompt_text_flux)+ # Define node IDs for Flux+ NODES = {+ 'pos_prompt': "6", # CLIPTextEncode for positive prompt+ 'vae_loader': "10", # VAELoader+ 'dual_clip': "11", # DualCLIPLoader+ 'unet_loader': "12", # UNETLoader+ 'sampler': "13", # SamplerCustomAdvanced+ 'ksampler': "16", # KSamplerSelect+ 'scheduler': "17", # BasicScheduler+ 'guider': "22", # BasicGuider+ 'noise': "25", # RandomNoise+ 'flux_guidance': "26", # FluxGuidance+ 'latent': "30", # EmptyLatentImage+ 'save_image': "32" # SaveImageWebsocket+ }++ base_prompt_text = context.scene.comfyui_prompt+ # Camera Prompt Injection+ if context.scene.use_camera_prompts and context.scene.generation_method in ['separate', 'sequential', 'refine'] and self._cameras and self._current_image < len(self._cameras):+ current_camera_name = self._cameras[self._current_image].name+ # Find the prompt in the collection+ prompt_item = next((item for item in context.scene.camera_prompts if item.name == current_camera_name), None)+ if prompt_item and prompt_item.prompt:+ view_desc = prompt_item.prompt+ # Prepend the view description+ base_prompt_text = f"{view_desc}, {base_prompt_text}"++ # Set positive prompt only (Flux doesn't use negative prompt)+ prompt[NODES['pos_prompt']]["inputs"]["text"] = base_prompt_text++ # Configure sampler parameters+ prompt[NODES['noise']]["inputs"]["noise_seed"] = context.scene.seed+ prompt[NODES['scheduler']]["inputs"]["steps"] = context.scene.steps+ prompt[NODES['scheduler']]["inputs"]["scheduler"] = context.scene.scheduler+ prompt[NODES['flux_guidance']]["inputs"]["guidance"] = context.scene.cfg+ prompt[NODES['ksampler']]["inputs"]["sampler_name"] = context.scene.sampler++ # Flux does not use negative prompt or LoRA.+ return prompt, NODES++ def generate_flux(self, context, depth_path=None, canny_path=None, normal_path=None):+ """Generates an image using Flux 1.+ Similar in structure to generate() but uses Flux nodes, skips negative prompt and LoRA.+ """+ from .util.helpers import prompt_text_flux+ server_address = context.preferences.addons[__package__].preferences.server_address+ client_id = str(uuid.uuid4())+ output_dir = context.preferences.addons[__package__].preferences.output_dir++ # Build Flux base prompt and node mapping.+ prompt, NODES = self.create_base_prompt_flux(context)++ self._configure_resolution(prompt, context, NODES)++ prompt, final_node = build_controlnet_chain_extended(+ context, prompt, NODES['pos_prompt'], NODES['pos_prompt'], NODES['vae_loader'],+ {"depth": depth_path, "canny": canny_path, "normal": normal_path}+ )+ # Connect final node to FluxGuidance+ prompt[NODES['flux_guidance']]["inputs"]["conditioning"] = [final_node, 0]+ # Note: No negative prompt is connected.+ # Save prompt for debugging.+ try:+ with open(os.path.join(output_dir, "prompt_flux.json"), 'w') as f:+ json.dump(prompt, f, indent=2)+ except Exception as e:+ print(f"Failed to save flux prompt: {e}")+ # Execute generation via websocket.+ try:+ ws = self._connect_to_websocket(server_address, client_id)+ images = self._execute_prompt_and_get_images(ws, prompt, client_id, server_address, NODES)+ ws.close()+ except ConnectionRefusedError:+ return {"error": "conn_refused"}+ print(f"Flux image generated with prompt: {context.scene.comfyui_prompt}")+ return images[NODES['save_image']][0]++ def _create_img2img_base_prompt_flux(self, context):+ """Creates and configures the base Flux prompt for img2img refinement."""+ from .util.helpers import prompt_text_img2img_flux++ prompt = json.loads(prompt_text_img2img_flux)++ # Node IDs organized by functional category for Flux+ NODES = {+ # Text Prompting+ 'pos_prompt': "6", # CLIPTextEncode for positive prompt++ # Model Components+ 'vae_loader': "10", # VAELoader+ 'dual_clip': "11", # DualCLIPLoader+ 'unet_loader': "12", # UNETLoader++ # Sampling Control+ 'sampler': "13", # SamplerCustomAdvanced+ 'ksampler': "16", # KSamplerSelect+ 'scheduler': "17", # BasicScheduler+ 'guider': "22", # BasicGuider+ 'noise': "25", # RandomNoise+ 'flux_guidance': "26", # FluxGuidance++ # Image Processing+ 'vae_decode': "8", # VAEDecode+ 'vae_encode': "116", # VAEEncode+ 'vae_encode_inpaint': "44", # VAEEncodeForInpaint+ 'upscale': "118", # ImageScale for upscaling+ 'upscale_uv': "43", # ImageScale for UV maps++ # Input Images+ 'input_image': "1", # LoadImage for input+ 'mask_image': "42", # LoadImage for mask+ 'render_image': "117", # LoadImage for render++ # Mask Processing+ 'grow_mask': "224", # GrowMask+ 'blur': "226", # ImageBlur+ 'image_to_mask': "227", # ImageToMask+ 'mask_to_image': "225", # MaskToImage++ # Advanced Features+ 'differential_diffusion': "50", # DifferentialDiffusion for Flux+ 'inpaint_conditioning': "51", # InpaintModelConditioning for Flux++ # Latent Space+ 'latent': "30", # EmptyLatentImage++ # Output+ 'save_image': "32" # SaveImageWebsocket+ }++ base_prompt_text = context.scene.comfyui_prompt+ # Camera Prompt Injection+ if context.scene.use_camera_prompts and context.scene.generation_method in ['separate', 'sequential', 'refine', 'grid'] and self._cameras and self._current_image < len(self._cameras):+ current_camera_name = self._cameras[self._current_image].name+ # Find the prompt in the collection+ prompt_item = next((item for item in context.scene.camera_prompts if item.name == current_camera_name), None)+ if prompt_item and prompt_item.prompt:+ view_desc = prompt_item.prompt+ # Prepend the view description+ base_prompt_text = f"{view_desc}, {base_prompt_text}"++ # Set positive prompt (Flux doesn't use negative prompt)+ prompt[NODES['pos_prompt']]["inputs"]["text"] = base_prompt_text++ # Configure sampler parameters+ prompt[NODES['noise']]["inputs"]["noise_seed"] = context.scene.seed+ prompt[NODES['scheduler']]["inputs"]["steps"] = context.scene.refine_steps if context.scene.generation_method == 'grid' else context.scene.steps+ prompt[NODES['scheduler']]["inputs"]["denoise"] = context.scene.denoise if context.scene.generation_method in ['grid', 'refine'] else 1.0+ prompt[NODES['flux_guidance']]["inputs"]["guidance"] = context.scene.refine_cfg if context.scene.generation_method == 'grid' else context.scene.cfg+ prompt[NODES['ksampler']]["inputs"]["sampler_name"] = context.scene.refine_sampler if context.scene.generation_method == 'grid' else context.scene.sampler+ prompt[NODES['scheduler']]["inputs"]["scheduler"] = context.scene.refine_scheduler if context.scene.generation_method == 'grid' else context.scene.scheduler++ # Configure upscale settings+ prompt[NODES['upscale']]["inputs"]["upscale_method"] = context.scene.refine_upscale_method+ prompt[NODES['upscale']]["inputs"]["width"] = context.scene.render.resolution_x+ prompt[NODES['upscale']]["inputs"]["height"] = context.scene.render.resolution_y++ # Configure UV upscale settings+ prompt[NODES['upscale_uv']]["inputs"]["upscale_method"] = "nearest-exact"+ prompt[NODES['upscale_uv']]["inputs"]["width"] = 1024+ prompt[NODES['upscale_uv']]["inputs"]["height"] = 1024++ # Configure mask settings+ prompt[NODES['grow_mask']]["inputs"]["expand"] = context.scene.grow_mask_by+ prompt[NODES['blur']]["inputs"]["blur_radius"] = context.scene.blur_mask_radius+ prompt[NODES['blur']]["inputs"]["sigma"] = context.scene.blur_mask_sigma++ return prompt, NODES++ def refine_flux(self, context, depth_path=None, canny_path=None, mask_path=None, render_path=None, normal_path=None):+ """+ Refines the image using Flux 1 in ComfyUI.+ :param context: Blender context.+ :param depth_path: Path to the depth map image.+ :param canny_path: Path to the canny edge image.+ :param mask_path: Path to the mask image for inpainting.+ :param render_path: Path to the input render image.+ :param normal_path: Path to the normal map image.+ :return: Refined image.+ """+ # Setup connection parameters+ server_address = context.preferences.addons[__package__].preferences.server_address+ client_id = str(uuid.uuid4())+ output_dir = context.preferences.addons[__package__].preferences.output_dir++ # Initialize the img2img prompt template for Flux+ prompt, NODES = self._create_img2img_base_prompt_flux(context)++ # Configure based on generation method+ self._configure_refinement_mode_flux(prompt, context, render_path, mask_path, NODES)++ # Set up image inputs for different controlnet types+ self._refine_configure_images_flux(prompt, depth_path, canny_path, normal_path, render_path, NODES)++ # Build controlnet chain for refinement if needed+ if not context.scene.generation_method == 'uv_inpaint':+ prompt = self._refine_build_controlnet_chain_flux(prompt, context, depth_path, canny_path, normal_path, NODES)++ # Save prompt for debugging+ with open(os.path.join(output_dir, "prompt_flux_img2img.json"), 'w') as f:+ json.dump(prompt, f)++ # Execute generation and get results+ try:+ ws = self._connect_to_websocket(server_address, client_id)+ images = self._execute_prompt_and_get_images(ws, prompt, client_id, server_address, NODES)+ ws.close()+ except ConnectionRefusedError:+ return {"error": "conn_refused"}++ print(f"Image refined with Flux using prompt: {context.scene.comfyui_prompt}")++ # Return the refined image+ return images[NODES['save_image']][0]++ def _configure_refinement_mode_flux(self, prompt, context, render_path, mask_path, NODES):+ """Configures the prompt based on the specific refinement mode for Flux."""+ # Configure based on generation method+ if context.scene.generation_method == 'refine':+ # Configure for refine mode - load render directly+ prompt[NODES['render_image']]["inputs"]["image"] = render_path+ prompt[NODES['vae_encode']]["inputs"]["pixels"] = [NODES['render_image'], 0]+ # Connect latent to sampler+ prompt[NODES['sampler']]["inputs"]["latent_image"] = [NODES['vae_encode'], 0]++ elif context.scene.generation_method in ['uv_inpaint', 'sequential']:+ # Configure for inpainting modes+ prompt[NODES['mask_image']]["inputs"]["image"] = mask_path+ prompt[NODES['input_image']]["inputs"]["image"] = render_path++ # Configure mask processing+ if not context.scene.blur_mask:+ prompt[NODES['vae_encode_inpaint']]["inputs"]["mask"] = [NODES['grow_mask'], 0]+ if context.scene.differential_diffusion:+ prompt[NODES['inpaint_conditioning']]["inputs"]["mask"] = [NODES['grow_mask'], 0]+ else:+ # Configure blur chain+ prompt[NODES['image_to_mask']]["inputs"]["image"] = [NODES['blur'], 0]+ prompt[NODES['vae_encode_inpaint']]["inputs"]["mask"] = [NODES['image_to_mask'], 0]++ # Different setups based on differential diffusion+ if context.scene.differential_diffusion:+ # Connect differential diffusion between model loader and other components+ prompt[NODES['guider']]["inputs"]["model"] = [NODES['differential_diffusion'], 0]+ prompt[NODES['scheduler']]["inputs"]["model"] = [NODES['differential_diffusion'], 0]++ # Connect inpaint conditioning to differential diffusion+ prompt[NODES['differential_diffusion']]["inputs"]["model"] = [NODES['unet_loader'], 0]++ # Configure inpaint conditioning with proper input image and mask+ prompt[NODES['inpaint_conditioning']]["inputs"]["pixels"] = [+ NODES['upscale_uv'], 0+ ] if context.scene.generation_method == 'uv_inpaint' else [NODES['input_image'], 0]++ # Connect latent to sampler from inpaint conditioning+ prompt[NODES['sampler']]["inputs"]["latent_image"] = [NODES['inpaint_conditioning'], 2]++ # Connect conditioning to flux_guidance+ prompt[NODES['flux_guidance']]["inputs"]["conditioning"] = [NODES['inpaint_conditioning'], 0]+ else:+ # Standard setup without differential diffusion+ prompt[NODES['sampler']]["inputs"]["latent_image"] = [NODES['vae_encode_inpaint'], 0]++ if context.scene.generation_method == 'uv_inpaint':+ self._configure_uv_inpainting_mode_flux(prompt, context, render_path, NODES)+ else: # Sequential mode+ self._configure_sequential_mode_flux(prompt, context, NODES)++ def _configure_uv_inpainting_mode_flux(self, prompt, context, render_path, NODES):+ """Configures the prompts for UV inpainting mode in Flux."""+ # UV inpainting specific configuration+ prompt[NODES['upscale_uv']]["inputs"]["image"] = [NODES['input_image'], 0]++ if not context.scene.differential_diffusion:+ prompt[NODES['vae_encode_inpaint']]["inputs"]["pixels"] = [NODES['upscale_uv'], 0]+ else:+ # Set the noise_mask flag according to context.scene.differential_noise+ prompt[NODES['inpaint_conditioning']]["inputs"]["noise_mask"] = context.scene.differential_noise++ # Create UV-specific prompt+ uv_prompt = f"seamless (UV-unwrapped texture) of {context.scene.comfyui_prompt}, consistent material continuity, no visible seams or stretching"+ prompt[NODES['pos_prompt']]["inputs"]["text"] = uv_prompt++ # Object-specific prompt if available+ current_object_name = os.path.basename(render_path).split('.')[0]+ object_prompt = self._object_prompts.get(current_object_name, context.scene.comfyui_prompt)+ if object_prompt:+ uv_prompt = f"(UV-unwrapped texture) of {object_prompt}, consistent material continuity, no visible seams or stretching"+ prompt[NODES['pos_prompt']]["inputs"]["text"] = uv_prompt++ def _configure_sequential_mode_flux(self, prompt, context, NODES):+ """Configures the prompt for sequential generation mode in Flux."""+ # Direct connection for sequential mode+ if not context.scene.differential_diffusion:+ prompt[NODES['vae_encode_inpaint']]["inputs"]["pixels"] = [NODES['input_image'], 0]+ else:+ # Set the noise_mask flag according to context.scene.differential_noise+ prompt[NODES['inpaint_conditioning']]["inputs"]["noise_mask"] = context.scene.differential_noise++ # Note: Flux doesn't support IPAdapter in the same way as SDXL++ def _refine_configure_images_flux(self, prompt, depth_path, canny_path, normal_path, render_path, NODES):+ """Configures the input images for the refinement process in Flux."""+ # Set render image if provided+ if render_path:+ prompt[NODES['render_image']]["inputs"]["image"] = render_path++ # Control images are handled by the controlnet chain builder++ def _refine_build_controlnet_chain_flux(self, prompt, context, depth_path, canny_path, normal_path, NODES):+ """Builds the ControlNet chain for refinement process with Flux."""+ input = NODES['pos_prompt'] if not context.scene.differential_diffusion else NODES['inpaint_conditioning']+ # For Flux, the controlnet chain connects to the guidance node+ prompt, final_node = build_controlnet_chain_extended(+ context, prompt, input, input, NODES['vae_loader'],+ {"depth": depth_path, "canny": canny_path, "normal": normal_path}+ )+ # Connect final node to FluxGuidance conditioning input+ prompt[NODES['flux_guidance']]["inputs"]["conditioning"] = [final_node, 0]+ return prompt++import json # ensure json is imported++def build_controlnet_chain_extended(context, base_prompt, pos_input, neg_input, vae_input, image_dict):+ addon_prefs = context.preferences.addons[__package__].preferences+ try:+ mapping = json.loads(addon_prefs.controlnet_mapping)+ except Exception:+ mapping = {}++ # Get the dynamic collection of ControlNet units+ controlnet_units = getattr(context.scene, "controlnet_units", [])+ current_pos = pos_input+ current_neg = neg_input+ for idx, unit in enumerate(controlnet_units):+ # Generate unique keys for nodes in this chain unit.+ load_key = str(200 + idx * 3) # LoadImage node+ loader_key = str(200 + idx * 3 + 1) # ControlNetLoader node+ apply_key = str(200 + idx * 3 + 2) # ControlNetApplyAdvanced node++ # Create the LoadImage node.+ base_prompt[load_key] = {+ "inputs": {+ "image": image_dict.get(unit.unit_type, ""),+ "upload": "image"+ },+ "class_type": "LoadImage",+ "_meta": {+ "title": f"Load Image ({unit.unit_type})"+ }+ }+ # Create the ControlNetLoader node.+ base_prompt[loader_key] = {+ "inputs": {+ "control_net_name": unit.model_name # updated to use selected property+ },+ "class_type": "ControlNetLoader",+ "_meta": {+ "title": f"Load ControlNet ({unit.unit_type})"+ }+ }+ # Create the ControlNetApplyAdvanced node.+ base_prompt[apply_key] = {+ "inputs": {+ "strength": unit.strength,+ "start_percent": unit.start_percent,+ "end_percent": unit.end_percent,+ "positive": [current_pos, 0],+ "negative": [current_neg, 1] if (idx > 0 or current_neg == "228" or current_neg == "51") else [current_neg, 0],+ "control_net": [loader_key, 0],+ "image": [load_key, 0],+ "vae": [vae_input, 2] if context.scene.model_architecture == "sdxl" else [vae_input, 0],+ },+ "class_type": "ControlNetApplyAdvanced",+ "_meta": {+ "title": f"Apply ControlNet ({unit.unit_type})"+ }+ }+ # Update chain inputs: the output of this apply node becomes the new input.+ current_pos = apply_key+ current_neg = apply_key+ # If the controlnet is of the union type, connect the ControlNetApplyAdvanced input into the SetUnionControlNetType node (239)+ if unit.is_union and unit.use_union_type:+ base_prompt[apply_key]["inputs"]["control_net"] = ["239", 0]+ base_prompt["239"]["inputs"]["control_net"] = [loader_key, 0]+ if unit.unit_type == "depth":+ base_prompt["239"]["inputs"]["type"] = "depth"+ elif unit.unit_type == "canny":+ base_prompt["239"]["inputs"]["type"] = "canny/lineart/anime_lineart/mlsd"+ elif unit.unit_type == "normal":+ base_prompt["239"]["inputs"]["type"] = "normal"++ return base_prompt, current_pos\ No newline at end of filediff --git a/stablegen/installer.py b/stablegen/installer.pynew file mode 100644index 0000000..be7bc09--- /dev/null+++ b/stablegen/installer.py@@ -0,0 +1,379 @@+#!/usr/bin/env python3+import os+import sys+import argparse+import subprocess+import requests+import shutil+from pathlib import Path+from typing import Dict, List, Set, Any++try:+ from tqdm.auto import tqdm+ TQDM_AVAILABLE = True+except ImportError:+ TQDM_AVAILABLE = False++# --- Configuration: Dependencies Data ---+# Sizes are in MB.+DEPENDENCIES: Dict[str, Dict[str, Any]] = {+ # --- Custom Nodes ---+ "cn_ipadapter_plus": {+ "id": "cn_ipadapter_plus", "type": "node", "name": "ComfyUI IPAdapter Plus",+ "git_url": "https://github.com/cubiq/ComfyUI_IPAdapter_plus.git",+ "target_dir_relative": "custom_nodes",+ "repo_name": "ComfyUI_IPAdapter_plus",+ "license": "GPL-3.0", "packages": ["core"]+ },+ # --- Models ---+ # Core Models+ "model_ipadapter_plus_sdxl_vit_h": {+ "id": "model_ipadapter_plus_sdxl_vit_h", "type": "model", "name": "IPAdapter Plus SDXL ViT-H",+ "url": "https://huggingface.co/h94/IP-Adapter/resolve/main/sdxl_models/ip-adapter-plus_sdxl_vit-h.safetensors?download=true",+ "target_path_relative": "models/ipadapter", "filename": "ip-adapter-plus_sdxl_vit-h.safetensors",+ "license": "Apache 2.0", "size_mb": 850, "packages": ["core"]+ },+ "model_clip_vision_h": {+ "id": "model_clip_vision_h", "type": "model", "name": "IPAdapter CLIP Vision ViT-H",+ "url": "https://huggingface.co/h94/IP-Adapter/resolve/main/models/image_encoder/model.safetensors",+ "target_path_relative": "models/clip_vision", "filename": "CLIP-ViT-H-14-laion2B-s32B-b79K.safetensors",+ "rename_from": "model.safetensors", "license": "Apache 2.0", "size_mb": 2500, "packages": ["core"]+ },+ "model_clip_vision_g": {+ "id": "model_clip_vision_g", "type": "model", "name": "IPAdapter CLIP Vision ViT-G",+ "url": "https://huggingface.co/h94/IP-Adapter/resolve/main/sdxl_models/image_encoder/model.safetensors",+ "target_path_relative": "models/clip_vision", "filename": "CLIP-ViT-bigG-14-laion2B-39B-b160k.safetensors",+ "rename_from": "model.safetensors", "license": "Apache 2.0", "size_mb": 3500, "packages": ["core"]+ },+ "lora_sdxl_lightning_8step": {+ "id": "lora_sdxl_lightning_8step", "type": "model", "name": "SDXL Lightning 8-Step LoRA",+ "url": "https://huggingface.co/ByteDance/SDXL-Lightning/resolve/main/sdxl_lightning_8step_lora.safetensors?download=true",+ "target_path_relative": "models/loras", "filename": "sdxl_lightning_8step_lora.safetensors",+ "license": "OpenRAIL++", "size_mb": 400, "packages": ["core"]+ },+ # Preset Essentials+ "controlnet_depth_sdxl_preset": {+ "id": "controlnet_depth_sdxl_preset", "type": "model", "name": "ControlNet Depth SDXL (for presets)",+ "url": "https://huggingface.co/xinsir/controlnet-depth-sdxl-1.0/resolve/main/diffusion_pytorch_model.safetensors?download=true",+ "target_path_relative": "models/controlnet", "filename": "controlnet_depth_sdxl.safetensors",+ "rename_from": "diffusion_pytorch_model.safetensors", "license": "Apache 2.0", "size_mb": 2500, "packages": ["preset_essentials"]+ },+ # Extended SDXL Optional Models+ "lora_sdxl_lightning_4step": {+ "id": "lora_sdxl_lightning_4step", "type": "model", "name": "SDXL Lightning 4-Step LoRA",+ "url": "https://huggingface.co/ByteDance/SDXL-Lightning/resolve/main/sdxl_lightning_4step_lora.safetensors?download=true",+ "target_path_relative": "models/loras", "filename": "sdxl_lightning_4step_lora.safetensors",+ "license": "OpenRAIL++", "size_mb": 400, "packages": ["extended_optional"]+ },+ "lora_sdxl_lightning_2step": {+ "id": "lora_sdxl_lightning_2step", "type": "model", "name": "SDXL Lightning 2-Step LoRA",+ "url": "https://huggingface.co/ByteDance/SDXL-Lightning/resolve/main/sdxl_lightning_2step_lora.safetensors?download=true",+ "target_path_relative": "models/loras", "filename": "sdxl_lightning_2step_lora.safetensors",+ "license": "OpenRAIL++", "size_mb": 400, "packages": ["extended_optional"]+ },+ "lora_hyper_sdxl_8step": {+ "id": "lora_hyper_sdxl_8step", "type": "model", "name": "Hyper-SDXL 8-Steps LoRA",+ "url": "https://huggingface.co/ByteDance/Hyper-SD/resolve/main/Hyper-SDXL-8steps-lora.safetensors?download=true",+ "target_path_relative": "models/loras", "filename": "Hyper-SDXL-8steps-lora.safetensors",+ "license": "Unknown (User to verify)", "size_mb": 800, "packages": ["extended_optional"]+ },+ "lora_hyper_sdxl_4step": {+ "id": "lora_hyper_sdxl_4step", "type": "model", "name": "Hyper-SDXL 4-Steps LoRA",+ "url": "https://huggingface.co/ByteDance/Hyper-SD/resolve/main/Hyper-SDXL-4steps-lora.safetensors?download=true",+ "target_path_relative": "models/loras", "filename": "Hyper-SDXL-4steps-lora.safetensors",+ "license": "Unknown (User to verify)", "size_mb": 800, "packages": ["extended_optional"]+ },+ "lora_hyper_sdxl_1step": {+ "id": "lora_hyper_sdxl_1step", "type": "model", "name": "Hyper-SDXL 1-Step LoRA",+ "url": "https://huggingface.co/ByteDance/Hyper-SD/resolve/main/Hyper-SDXL-1step-lora.safetensors?download=true",+ "target_path_relative": "models/loras", "filename": "Hyper-SDXL-1step-lora.safetensors",+ "license": "Unknown (User to verify)", "size_mb": 800, "packages": ["extended_optional"]+ },+ "controlnet_depth_sdxl_fp16_alt": {+ "id": "controlnet_depth_sdxl_fp16_alt", "type": "model", "name": "ControlNet Depth SDXL fp16 (alternative)",+ "url": "https://huggingface.co/diffusers/controlnet-depth-sdxl-1.0/resolve/main/diffusion_pytorch_model.fp16.safetensors?download=true",+ "target_path_relative": "models/controlnet", "filename": "diffusion_pytorch_model.fp16.safetensors",+ "license": "OpenRAIL++", "size_mb": 2500, "packages": ["extended_optional"]+ },+ "controlnet_union_promax": {+ "id": "controlnet_union_promax", "type": "model", "name": "ControlNet Union SDXL ProMax",+ "url": "https://huggingface.co/brad-twinkl/controlnet-union-sdxl-1.0-promax/resolve/main/diffusion_pytorch_model.safetensors?download=true",+ "target_path_relative": "models/controlnet", "filename": "sdxl_promax.safetensors",+ "rename_from": "diffusion_pytorch_model.safetensors", "license": "Apache 2.0", "size_mb": 2500, "packages": ["extended_optional"]+ },+ # Checkpoints+ "checkpoint_realvis_v5": {+ "id": "checkpoint_realvis_v5", "type": "model", "name": "RealVisXL V5.0 fp16 Checkpoint",+ "url": "https://huggingface.co/SG161222/RealVisXL_V5.0/resolve/main/RealVisXL_V5.0_fp16.safetensors?download=true",+ "target_path_relative": "models/checkpoints", "filename": "RealVisXL_V5.0_fp16.safetensors",+ "license": "OpenRAIL++", "size_mb": 6500, "packages": ["checkpoint_realvis"]+ }+}++# Define what items each menu option entails by listing package tags+# The script will collect all unique items based on the selected package tags.+MENU_PACKAGES: Dict[str, Dict[str, Any]] = {+ '1': {"name": "[MINIMAL CORE] Basic Requirements",+ "tags": ["core"],+ "size_gb": 7.3,+ "description_suffix": "*You will still need to manually download your own SDXL checkpoint(s) and all ControlNet models for full functionality and preset usage.*"},+ '2': {"name": "[ESSENTIAL] Core + Preset Essentials",+ "tags": ["core", "preset_essentials"],+ "size_gb": 9.8,+ "description_suffix": "*All models for preset functionality. You will still need to manually download your own SDXL checkpoint(s).*"},+ '3': {"name": "[RECOMMENDED] Full SDXL Setup (No Checkpoints)",+ "tags": ["core", "preset_essentials", "extended_optional"],+ "size_gb": 16.0,+ "description_suffix": "*Downloads optional ControlNet and LoRA models. You will still need to manually download your own SDXL checkpoint(s).*"},+ '4': {"name": "[COMPLETE SDXL] Full SDXL Setup + RealVisXL V5.0 Checkpoint",+ "tags": ["core", "preset_essentials", "extended_optional", "checkpoint_realvis"],+ "size_gb": 23.0,+ "description_suffix": ""}+}++# --- Helper Functions ---+def print_header(title: str):+ print(f"\n{'='*10} {title} {'='*10}")++def print_separator(char='-', length=70):+ print(char * length)++def get_comfyui_path_from_args() -> Path:+ parser = argparse.ArgumentParser(description="StableGen Dependency Installer Script.")+ parser.add_argument("comfyuipath", nargs='?', default=None,+ help="Full path to your ComfyUI installation directory. If not provided, will be prompted.")+ args = parser.parse_args()++ comfyui_path_str = args.comfyuipath+ while not comfyui_path_str:+ comfyui_path_str = input("Please enter the full path to your ComfyUI installation directory: ").strip()++ comfyui_path = Path(comfyui_path_str).resolve() # Get absolute path++ if not comfyui_path.is_dir():+ print(f"Error: ComfyUI path '{comfyui_path}' not found or not a directory.")+ sys.exit(1)+ if not (comfyui_path / "models").is_dir() or not (comfyui_path / "custom_nodes").is_dir():+ print(f"Error: '{comfyui_path}' does not look like a valid ComfyUI directory (missing 'models' or 'custom_nodes' subfolder).")+ sys.exit(1)+ return comfyui_path++def create_dir_if_not_exists(path: Path):+ path.mkdir(parents=True, exist_ok=True)++def download_file(item_details: Dict[str, Any], comfyui_path: Path):+ url = item_details["url"]+ target_dir = comfyui_path / item_details["target_path_relative"]+ final_filename = item_details["filename"]+ final_filepath = target_dir / final_filename+ temp_filename = item_details.get("rename_from", final_filename)+ temp_filepath = target_dir / temp_filename++ if final_filepath.exists():+ print(f"INFO: File '{final_filename}' already exists at '{final_filepath}'. Skipping download.")+ print(f" Please ensure this is the correct file as specified (License: {item_details['license']}).")+ return++ if item_details.get("rename_from") and temp_filepath.exists():+ # This case covers if a previous download was interrupted after download but before rename+ # or if user manually placed the file with the original name.+ print(f"INFO: File '{temp_filename}' (to be renamed to '{final_filename}') already exists at '{temp_filepath}'.")+ print(f" Assuming it's the correct file. Renaming if necessary and skipping download.")+ print(f" Please ensure this is the correct file (License: {item_details['license']}).")+ if temp_filepath != final_filepath: # Needs rename+ try:+ shutil.move(str(temp_filepath), str(final_filepath))+ print(f" Successfully renamed '{temp_filename}' to '{final_filename}'.")+ except Exception as e:+ print(f" ERROR: Could not rename '{temp_filename}' to '{final_filename}': {e}")+ return++ create_dir_if_not_exists(target_dir)+ size_mb = item_details.get("size_mb", "N/A")+ print(f" Downloading: {item_details['name']} ({size_mb}MB) - License: {item_details['license']}")+ print(f" From: {url}")+ print(f" To: {final_filepath}")+ if item_details.get("rename_from"):+ print(f" (Will be downloaded as '{temp_filename}' and then renamed to '{final_filename}')")++ try:+ response = requests.get(url, stream=True, timeout=30) # Added timeout+ response.raise_for_status() # Raise an exception for HTTP errors+ total_size = int(response.headers.get('content-length', 0))++ # Use temp_filepath for download, then rename to final_filepath+ download_target = temp_filepath if item_details.get("rename_from") else final_filepath+ # Ensure no partial file from previous attempt if not renaming+ if not item_details.get("rename_from") and download_target.exists():+ print(f"WARNING: '{download_target}' exists but was not caught by pre-check. This might be a partial file. Overwriting.")+++ with open(download_target, 'wb') as f:+ if TQDM_AVAILABLE and total_size > 0:+ with tqdm(total=total_size, unit='B', unit_scale=True, unit_divisor=1024, desc=item_details['name'], ascii=True) as pbar:+ for chunk in response.iter_content(chunk_size=8192):+ f.write(chunk)+ pbar.update(len(chunk))+ else:+ print(f" Downloading {item_details['name']} (size: {total_size/1024/1024:.2f} MB)...")+ for chunk in response.iter_content(chunk_size=8192):+ f.write(chunk)+ print(f" Download complete: {download_target}")++ if item_details.get("rename_from") and temp_filepath != final_filepath:+ if final_filepath.exists():+ print(f"WARNING: Target renamed file '{final_filepath}' already exists. Overwriting.")+ final_filepath.unlink()+ shutil.move(str(temp_filepath), str(final_filepath))+ print(f" Successfully renamed to '{final_filename}'.")++ except requests.exceptions.RequestException as e:+ print(f" ERROR downloading {item_details['name']}: {e}")+ except Exception as e:+ print(f" An unexpected error occurred during download of {item_details['name']}: {e}")+++def clone_git_repo(item_details: Dict[str, Any], comfyui_path: Path):+ git_url = item_details["git_url"]+ target_parent_dir = comfyui_path / item_details["target_dir_relative"]+ repo_name = item_details["repo_name"]+ final_repo_path = target_parent_dir / repo_name++ if final_repo_path.is_dir():+ print(f"INFO: Custom node directory '{repo_name}' already exists at '{final_repo_path}'. Skipping clone.")+ print(f" Please ensure it's the correct repository and up-to-date if you encounter issues (License: {item_details['license']}).")+ return++ create_dir_if_not_exists(target_parent_dir)+ print(f" Cloning: {item_details['name']} - License: {item_details['license']}")+ print(f" From: {git_url}")+ print(f" To: {final_repo_path}")++ try:+ subprocess.run(['git', 'clone', git_url, str(final_repo_path)], check=True, cwd=str(target_parent_dir))+ print(f" Successfully cloned '{repo_name}'.")+ print(f" IMPORTANT: Restart ComfyUI if it was running to load this new custom node.")+ except subprocess.CalledProcessError as e:+ print(f" ERROR cloning {item_details['name']}: Git command failed with exit code {e.returncode}")+ if e.stderr:+ print(f" Git stderr: {e.stderr.decode(errors='ignore')}")+ if e.stdout:+ print(f" Git stdout: {e.stdout.decode(errors='ignore')}")++ except FileNotFoundError:+ print(" ERROR: Git command not found. Please ensure Git is installed and in your system's PATH.")+ except Exception as e:+ print(f" An unexpected error occurred during git clone of {item_details['name']}: {e}")+++def display_menu(comfyui_path: Path):+ print_header("StableGen Dependency Installer")+ print(f"Target ComfyUI Directory: {comfyui_path}")+ print_separator()+ print("This script helps download and set up essential and optional models for StableGen.")+ print("For FLUX.1 model setup (which requires manual download due to licensing),")+ print("please refer to the main README.md on our GitHub page: https://github.com/sakalond/stablegen")+ print_separator()+ print("Note: Download sizes are estimates. Actual sizes may vary slightly.")+ print()+ print("Upon entering a choice, the full list of components will be shown for approval before proceeding.")+ print_separator()+ print("Please choose an installation package:")+ print()++ for key, val in MENU_PACKAGES.items():+ print(f"\n{key}. {val['name']}")+ print_separator(char='.')+ # Dynamically list contents for clarity (optional, can make menu long)+ # items_in_package = get_items_for_package_tags(val['tags'])+ # for item_id in items_in_package:+ # print(f" - {DEPENDENCIES[item_id]['name']}")+ print(f" *Approximate total download size: ~{val['size_gb']:.1f} GB*")+ if val.get("description_suffix"):+ print(f" {val['description_suffix']}")+ print("\nq. Quit")+ print_separator()+++def get_unique_item_ids_for_tags(selected_tags: List[str]) -> Set[str]:+ item_ids: Set[str] = set()+ for item_id, details in DEPENDENCIES.items():+ # An item is included if any of its 'packages' tags are in selected_tags+ if any(tag in details["packages"] for tag in selected_tags):+ item_ids.add(item_id)+ return item_ids++# --- Main Script Logic ---+def main():+ comfyui_base_path = get_comfyui_path_from_args()++ processed_during_this_session: Set[str] = set() # To avoid re-processing in same session if menu is re-shown++ while True:+ display_menu(comfyui_base_path)+ choice = input("Enter your choice (1-4, or q to quit): ").strip().lower()++ if choice == 'q':+ print("Exiting installer.")+ break++ selected_option = MENU_PACKAGES.get(choice)+ if not selected_option:+ print("Invalid choice. Please try again.")+ continue++ print_separator()+ print(f"You selected: {selected_option['name']}")+ print(f"Estimated download for this package (if items not present): ~{selected_option['size_gb']:.1f} GB")++ current_selection_item_ids = get_unique_item_ids_for_tags(selected_option["tags"])+ items_to_process_this_round: List[Dict[str, Any]] = []++ print("This package will check/install the following components:")+ for item_id in sorted(list(current_selection_item_ids)): # Sort for consistent display+ if item_id not in processed_during_this_session and item_id in DEPENDENCIES:+ print(f" - {DEPENDENCIES[item_id]['name']}")+ items_to_process_this_round.append(DEPENDENCIES[item_id])++ if not items_to_process_this_round:+ print("All components for this selection appear to have been processed or are not defined. Nothing new to install for this choice.")+ print("If you expected installations, ensure the components are not already present from a previous run or selection.")+ print_separator()+ continue++ confirm_all = input("Proceed with checking/installing these components? (y/n, Enter for yes): ").strip().lower()+ if not (confirm_all == "" or confirm_all == 'y'):+ print("Installation of this package cancelled by user.")+ print_separator()+ continue++ print_separator(char='*')+ for item_details in items_to_process_this_round:+ if item_details["id"] in processed_during_this_session: # Should not happen if items_to_process_this_round is built correctly+ continue++ print_separator(char='.')+ print(f"Processing: {item_details['name']}")++ target_full_path: Path+ if item_details["type"] == "node":+ target_full_path = comfyui_base_path / item_details["target_dir_relative"] / item_details["repo_name"]+ clone_git_repo(item_details, comfyui_base_path)+ elif item_details["type"] == "model":+ target_full_path = comfyui_base_path / item_details["target_path_relative"] / item_details["filename"]+ download_file(item_details, comfyui_base_path)++ processed_during_this_session.add(item_details["id"])++ print_separator(char='*')+ print("Processing for selected package complete.")+ print("Please check messages above for status of each item.")+ if any(item["type"] == "node" for item in items_to_process_this_round):+ print("IMPORTANT: If any custom nodes were newly cloned, restart ComfyUI to load them.")+ print_separator()++if __name__ == "__main__":+ if not TQDM_AVAILABLE:+ print("NOTE: 'tqdm' library not found. Download progress will not be shown as a bar.")+ print(" You can install it with: pip install tqdm")+ main()\ No newline at end of filediff --git a/stablegen/project.py b/stablegen/project.pynew file mode 100644index 0000000..af84a1b--- /dev/null+++ b/stablegen/project.py@@ -0,0 +1,554 @@+import bpy+import os+from math import atan, tan++from .utils import get_last_material_index, get_file_path, get_dir_path+from .render_tools import prepare_baking, bake_texture, unwrap+from mathutils import Vector++def project_image(context, mat_id, stop_index=1000000):+ """+ Projects an image onto all mesh objects using UV Project Modifier.+ """+ def build_mix_tree(shaders, weight_nodes, nodes_collection, links, last_node=None, level=0, stop_index=1000000):+ """+ Recursively builds a binary tree of mix shader nodes.+ The mix factor between two shader nodes is computed dynamically using+ the outputs of weight_nodes assumed to come from OSL/maths nodes.++ For each pair, the total weight is created using an ADD node.+ Then a DIVIDE node computes:+ mix_factor = weight_A / (weight_A + weight_B)+ which is connected to the Mix Shader node's Fac input.++ Params:+ shaders: list of shader nodes (e.g., Principled BSDF nodes).+ weight_nodes: list of nodes whose outputs provide the dynamic weight values.+ (e.g. the less_than nodes outputs)+ nodes_collection: the node tree's nodes collection.+ links: the node tree's links collection.+ Returns:+ A tuple (final_shader, final_weight_node).+ """+ # Compute offsets based on recursion level+ if context.scene.refine_preserve:+ x_offset = 1000 + level * 600 + last_node.location[0] + 200+ else:+ x_offset = 1000 + level * 600+ y_offset = 0+ if len(shaders) == 1:+ # Base-case: Mix single color with fallback magenta+ final_mix = nodes_collection.new("ShaderNodeMixRGB")+ final_mix.location = (x_offset - 200, y_offset)+ # Convert fallback_color from 3 to 4 components by appending alpha 1.0+ final_mix.inputs["Color2"].default_value = (*context.scene.fallback_color, 1.0)+ # Connect the single color output to Color1+ links.new(shaders[0].outputs[0], final_mix.inputs["Color1"])+ if last_node:+ # Connect the final mix node to the last node+ links.new(last_node.outputs[0], final_mix.inputs["Color2"])+ # Create a compare node to drive the mix factor++ if context.scene.generation_method == 'refine' and context.scene.refine_preserve:+ compare_node = nodes_collection.new("ShaderNodeValToRGB")+ compare_node.location = (x_offset - 500, y_offset)+ compare_node.color_ramp.elements[0].position = 0.0+ compare_node.color_ramp.elements[0].color = (1, 1, 1, 1)+ compare_node.color_ramp.elements[1].position = 0.6+ compare_node.color_ramp.elements[1].color = (0, 0, 0, 1)+ compare_node.color_ramp.interpolation = 'LINEAR'+ else:+ compare_node = nodes_collection.new("ShaderNodeMath")+ compare_node.operation = 'COMPARE'+ # Value to compare against (Value 2)+ compare_node.inputs[1].default_value = 0.0+ # Epsilon for comparison+ compare_node.inputs[2].default_value = 0.0+ compare_node.location = (x_offset - 500, y_offset)+ # Connect final add node to compare node+ links.new(weight_nodes[0].outputs[0], compare_node.inputs[0])+ links.new(compare_node.outputs[0], final_mix.inputs["Fac"])++ if not context.scene.apply_bsdf:+ return final_mix, compare_node++ # Add a principle shader for the mixed color+ should_add_principled = True+ if context.scene.generation_method == 'refine' and context.scene.refine_preserve:+ # Final principled is at last_node's output if it is BSDF+ final_principled = last_node.outputs[0].links[0].to_node+ if final_principled.type == 'BSDF_PRINCIPLED':+ should_add_principled = False++ if should_add_principled:+ final_principled = nodes_collection.new("ShaderNodeBsdfPrincipled")+ final_principled.location = (x_offset, y_offset)+ final_principled.inputs["Roughness"].default_value = 1.0++ links.new(final_mix.outputs[0], final_principled.inputs[0])+ return final_principled, compare_node++ new_shaders = []+ new_weight_nodes = []+ i = 0+ while i < len(shaders):+ if i + 1 < len(shaders):+ # Sum the weights+ vert_offset = -200 * (i // 2)+ sum_node = nodes_collection.new("ShaderNodeMath")+ sum_node.operation = 'ADD'+ sum_node.location = (x_offset - 600, y_offset + vert_offset)+ links.new(weight_nodes[i].outputs[0], sum_node.inputs[0])+ links.new(weight_nodes[i+1].outputs[0], sum_node.inputs[1])++ # Compute mix factor: weight_A / (weight_A+weight_B)+ div_node = nodes_collection.new("ShaderNodeMath")+ div_node.operation = 'DIVIDE'+ div_node.location = (x_offset - 400, y_offset + vert_offset)+ links.new(weight_nodes[i+1].outputs[0], div_node.inputs[0])+ links.new(sum_node.outputs[0], div_node.inputs[1])++ # Create a MixRGB node for color blending of the two inputs+ mix_node = nodes_collection.new("ShaderNodeMixRGB")+ mix_node.location = (x_offset - 200, y_offset + vert_offset)+ # Connect first color to Color1 and second color to Color2+ links.new(shaders[i].outputs[0], mix_node.inputs["Color1"])+ links.new(shaders[i+1].outputs[0], mix_node.inputs["Color2"])+ # Use the computed mix factor+ links.new(div_node.outputs[0], mix_node.inputs["Fac"])++ new_shaders.append(mix_node)+ # The new effective weight is the sum (stored in sum_node)+ new_weight_nodes.append(sum_node)+ i += 2+ else:+ new_shaders.append(shaders[i])+ new_weight_nodes.append(weight_nodes[i])+ i += 1+ return build_mix_tree(new_shaders, new_weight_nodes, nodes_collection, links, last_node, level+1)++ cameras = [obj for obj in context.scene.objects if obj.type == 'CAMERA']+ cameras.sort(key=lambda x: x.name)++ # The image is saved as png binary in the image variable+ stage_ref = "Projecting images (this may take a while)..."+ if context.scene.generation_method == 'sequential' and stop_index > 0:+ stage_ref = f"Editing node tree..."+ # Force refresh of the UI+ for area in context.screen.areas:+ area.tag_redraw()++ # Apply projection to all mesh objects for each camera+ for i, camera in enumerate(cameras):+ object_Mesh = [obj for obj in context.scene.objects if obj.type == 'MESH']+ for x, obj in enumerate(object_Mesh):+ # We can skip the UV Projection step in sequential mode for i > 0+ if context.scene.generation_method != 'sequential' or stop_index == 0 or context.scene.bake_texture:+ # Deselect all objects+ bpy.ops.object.select_all(action='DESELECT')+ # Select object as active (needed for applying the modifier)+ context.view_layer.objects.active = obj+ obj.select_set(True)++ # Make object data single-user before applying modifier+ bpy.ops.object.make_single_user(object=True, obdata=True)++ # Add new UV map if not present (with same name)+ # Check if "ProjectionUV" UV map already exists+ uv_map = None++ if context.scene.overwrite_material and not context.scene.bake_texture:+ for uv in obj.data.uv_layers:+ if uv.name == f"ProjectionUV_{i}_{mat_id}":+ uv_map = uv+ break++ # If the objects has no UV map and we are baking textures, create a new one+ if not obj.data.uv_layers and context.scene.bake_texture:+ obj.data.uv_layers.new(name="BakeUV")++ if not uv_map:+ uv_map = obj.data.uv_layers.new(name=f"ProjectionUV_{i}_{mat_id}")++ # Add the UV Project Modifier if not present+ uv_project_mod = obj.modifiers.new(name="UVProject", type='UV_PROJECT')++ # Assign the active camera to the UV Project modifier+ if not camera:+ return False++ uv_project_mod.projectors[0].object = camera++ # Set the UV map for the modifier+ try:+ uv_project_mod.uv_layer = uv_map.name+ except:+ # Throw custom exception: Not enough UV map slots+ raise Exception("Not enough UV map slots. Please remove some UV maps.")++ # Calculate and set the aspect ratio+ render = context.scene.render+ aspect_ratio = render.resolution_x / render.resolution_y+ uv_project_mod.aspect_x = aspect_ratio if aspect_ratio > 1 else 1+ uv_project_mod.aspect_y = 1 / aspect_ratio if aspect_ratio < 1 else 1++ # Apply the modifier+ bpy.ops.object.modifier_apply(modifier=uv_project_mod.name)++ original_uv_map = obj.data.uv_layers[0]++ # If we are running in sequential mode, we already have baked textures for i < stop_index+ if context.scene.bake_texture:+ if (stop_index > 0 and context.scene.generation_method == 'sequential'):+ # Deselect all objects+ bpy.ops.object.select_all(action='DESELECT')+ # Select object as active (needed for applying the modifier)+ context.view_layer.objects.active = obj+ obj.select_set(True)+ if i <= stop_index and (not context.scene.generation_method == 'sequential' or i == stop_index):+ simple_project_bake(context, i, obj, mat_id)+ obj.data.uv_layers.remove(obj.data.uv_layers[-1]) # Remove the last UV map++ for obj in context.scene.objects:+ if obj.type != 'MESH':+ continue++ # Deselect all objects+ bpy.ops.object.select_all(action='DESELECT')+ context.view_layer.objects.active = obj+ obj.select_set(True)++ # Create the material+ to_switch = False+ if context.scene.generation_method == "refine" and context.scene.refine_preserve and not context.scene.overwrite_material:+ # Copy active material+ mat = obj.active_material.copy()+ obj.data.materials.append(mat)+ to_switch = True+ elif obj.active_material and (context.scene.overwrite_material or (context.scene.generation_method == "refine" and context.scene.refine_preserve) or (context.scene.generation_method == 'sequential' and stop_index > 0)):+ # Use active material+ mat = obj.active_material+ else:+ mat = bpy.data.materials.new(name="ProjectionMaterial")+ obj.data.materials.append(mat)+ # Mark as active material+ obj.active_material_index = obj.material_slots.find(mat.name)+ to_switch = True++ if to_switch:+ original_materials = obj.data.materials[:]+ # Clear existing materials+ obj.data.materials.clear()+ # Add the new material+ obj.data.materials.append(mat)+ # Add the rest of the original materials+ for original_mat in original_materials:+ if original_mat != mat:+ obj.data.materials.append(original_mat)++ # Enable use of nodes+ mat.use_nodes = True+ nodes = mat.node_tree.nodes+ links = mat.node_tree.links++ previous_node = None+ output = None++ original_uv_map = obj.data.uv_layers[0]+++ if context.scene.generation_method == 'sequential' and stop_index > 0:+ # We just need to remove the compare nodes which are connected to script node at stop_index+ script_node = None+ # First find all script nodes with label {stop_index}-{mat_id}+ for node in nodes:+ if node.type == 'SCRIPT' and node.label == f"{stop_index}-{mat_id}":+ script_node = node+ break+ compare_output_sockets = set()+ if script_node:+ # Find all compare nodes connected to the script node+ for link in script_node.outputs[0].links:+ if link.to_node.type == 'MATH' and link.to_node.operation == 'LESS_THAN':+ # Save all outputs (nodes connected to) of compare nodes+ for link2 in link.to_node.outputs[0].links:+ compare_output_sockets.add(link2.to_socket)+ # Remove the compare node+ nodes.remove(link.to_node)+ # Connect the script node to all outputs+ for output in compare_output_sockets:+ links.new(script_node.outputs[0], output)+ # We also need to set the generated image to the texture node with label {stop_index}-{mat_id}+ for node in nodes:+ if node.type == 'TEX_IMAGE' and node.label == f"{stop_index}-{mat_id}":+ output_dir = context.preferences.addons[__package__].preferences.output_dir+ if not context.scene.bake_texture:+ image = bpy.data.images.load(get_file_path(context, "generated", camera_id=stop_index, material_id=mat_id))+ if (context.scene.generation_method == 'sequential' or context.scene.generation_method == 'separate') and context.scene.sequential_ipadapter and context.scene.sequential_ipadapter_regenerate and not context.scene.use_ipadapter and stop_index == 0 and context.scene.sequential_ipadapter_mode == 'first':+ image = bpy.data.images.load(get_file_path(context, "generated", camera_id=stop_index, material_id=mat_id).replace(".png", "_ipadapter.png"))+ else:+ # Use baked texture+ image = bpy.data.images.load(get_file_path(context, "generated_baked", camera_id=stop_index, material_id=mat_id, object_name=obj.name))+ node.image = image+ break+ # Now we can continue to the next object+ continue++ elif not context.scene.refine_preserve or not context.scene.generation_method == 'refine':+ # Clear existing nodes+ for node in nodes:+ nodes.remove(node)+ else:+ # Find the node connected to the output node+ for node in nodes:+ if node.type == 'OUTPUT_MATERIAL':+ output = node+ break+ if output:+ # Save the node connected to the output node into a variable+ if output.inputs[0].links[0].from_node.type == 'BSDF_PRINCIPLED':+ previous_node = output.inputs[0].links[0].from_node.inputs[0].links[0].from_node+ else:+ previous_node = output.inputs[0].links[0].from_node++ if not (context.scene.generation_method == 'refine' and context.scene.refine_preserve):+ output = nodes.new("ShaderNodeOutputMaterial")+ output.location = (3000, 0)++ geometry = nodes.new("ShaderNodeNewGeometry")+ geometry.location = (-600, 0)++ tex_image_nodes = []+ uv_map_nodes = []+ subtract_nodes = []+ normalize_nodes = []+ script_nodes = []+ script_nodes_outputs = []+ add_camera_loc_nodes = []+ length_nodes = []+ camera_fov_nodes = []+ camera_aspect_ratio_nodes = []+ camera_direction_nodes = []+ camera_up_nodes = []++ for i, camera in enumerate(cameras):+ # Add image texture node+ tex_image = nodes.new("ShaderNodeTexImage")+ output_dir = context.preferences.addons[__package__].preferences.output_dir+ if i <= stop_index:+ if not context.scene.bake_texture:+ image = bpy.data.images.load(get_file_path(context, "generated", camera_id=i, material_id=mat_id))+ if (context.scene.generation_method == 'sequential' or context.scene.generation_method == 'separate') and context.scene.sequential_ipadapter and context.scene.sequential_ipadapter_regenerate and not context.scene.use_ipadapter and i == 0 and context.scene.sequential_ipadapter_mode == 'first':+ image = bpy.data.images.load(get_file_path(context, "generated", camera_id=i, material_id=mat_id).replace(".png", "_ipadapter.png"))+ else:+ # Use baked texture+ image = bpy.data.images.load(get_file_path(context, "generated_baked", camera_id=i, material_id=mat_id, object_name=obj.name))+ tex_image.image = image+ tex_image.location = (0, -200 * i)+ tex_image.extension = 'CLIP'+ tex_image.label = f"{i}-{mat_id}"+ tex_image_nodes.append(tex_image)++ # Add UV map node+ uv_map_node = nodes.new("ShaderNodeUVMap")+ if not context.scene.bake_texture:+ uv_map_node.uv_map = f"ProjectionUV_{i}_{mat_id}"+ else:+ # Use the original UV map+ uv_map_node.uv_map = original_uv_map.name+ uv_map_node.location = (-200, -200 * (i+1))+ uv_map_nodes.append(uv_map_node)++ # Compute the dot product of the direction vector and geometry normal++ subtract = nodes.new("ShaderNodeVectorMath")+ subtract.operation = 'SUBTRACT'+ subtract.location = (-400, -300 + (-800) * i)+ subtract.inputs[1].default_value = camera.location+ subtract_nodes.append(subtract)++ normalize = nodes.new("ShaderNodeVectorMath")+ normalize.operation = 'NORMALIZE'+ normalize.location = (-400, -500 + (-800) * (i))+ normalize_nodes.append(normalize)+++ # Switch to Cycles for OSL support+ context.scene.render.engine = 'CYCLES'+ context.scene.cycles.device = 'CPU'+ context.scene.cycles.shading_system = True++ # Add a script node+ script = nodes.new("ShaderNodeScript")+ script.location = (-400, (-800) * i)+ script.mode = 'EXTERNAL'+ script.filepath = os.path.join(os.path.dirname(__file__), "raycast.osl")+ script.inputs["AngleThreshold"].default_value = context.scene.discard_factor+ script.inputs["Power"].default_value = context.scene.weight_exponent+ script.label = f"{i}-{mat_id}"+ script_nodes.append(script)+ if i > stop_index:+ # Connect a temporary less than node to the script node+ less_than = nodes.new("ShaderNodeMath")+ less_than.operation = 'LESS_THAN'+ less_than.location = (-200, (-800) * i)+ less_than.inputs[1].default_value = -1+ links.new(script.outputs[0], less_than.inputs[0])+ script_nodes_outputs.append(less_than)+ else:+ script_nodes_outputs.append(script)++ # Add additional add node, which will contain camera's FOV in first default value, and camera's aspect ratio in second default value+ camera_fov = nodes.new("ShaderNodeValue")+ camera_fov.location = (-600, 200 + 300 * i)+ fov = camera.data.angle_x+ # Correct the FOV for vertical aspect ratio+ if context.scene.render.resolution_y > context.scene.render.resolution_x:+ fov = 2 * atan(tan(fov / 2) * context.scene.render.resolution_x / context.scene.render.resolution_y)+ camera_fov.outputs[0].default_value = fov+ camera_fov_nodes.append(camera_fov)+ camera_aspect_ratio = nodes.new("ShaderNodeValue")+ camera_aspect_ratio.location = (-600, 200 + 300 * i)++ # Add camera direction and up nodes (combine XYZ)+ camera_direction = nodes.new("ShaderNodeCombineXYZ")+ camera_direction.location = (-600, 200 + 300 * i)+ # Get the camera direction vector+ camera_direction.inputs[0].default_value = (camera.matrix_world.to_quaternion() @ Vector((0, 0, -1))).x+ camera_direction.inputs[1].default_value = (camera.matrix_world.to_quaternion() @ Vector((0, 0, -1))).y+ camera_direction.inputs[2].default_value = (camera.matrix_world.to_quaternion() @ Vector((0, 0, -1))).z+ camera_direction_nodes.append(camera_direction)+ camera_up = nodes.new("ShaderNodeCombineXYZ")+ camera_up.location = (-600, 200 + 300 * i)+ # Get the camera up vector+ camera_up.inputs[0].default_value = (camera.matrix_world.to_quaternion() @ Vector((0, 1, 0))).x+ camera_up.inputs[1].default_value = (camera.matrix_world.to_quaternion() @ Vector((0, 1, 0))).y+ camera_up.inputs[2].default_value = (camera.matrix_world.to_quaternion() @ Vector((0, 1, 0))).z+ camera_up_nodes.append(camera_up)++ camera_aspect_ratio.outputs[0].default_value = context.scene.render.resolution_x / context.scene.render.resolution_y+ camera_aspect_ratio_nodes.append(camera_aspect_ratio)++ # Add combine XYZ node+ add_camera_loc = nodes.new("ShaderNodeCombineXYZ")+ add_camera_loc.location = (-600, 200 + 300 * i)+ add_camera_loc.inputs[0].default_value = camera.location.x+ add_camera_loc.inputs[1].default_value = camera.location.y+ add_camera_loc.inputs[2].default_value = camera.location.z+ add_camera_loc_nodes.append(add_camera_loc)++ # Add length node+ length = nodes.new("ShaderNodeVectorMath")+ length.operation = 'LENGTH'+ length.location = (-400, 200 * (i+1))+ length_nodes.append(length)++ # Build mix shader tree+ mix_node, _ = build_mix_tree(tex_image_nodes, script_nodes_outputs, nodes, links, previous_node, stop_index=stop_index)+ links.new(mix_node.outputs[0], output.inputs["Surface"])++ # Move output node right to the mix_node+ output.location = (mix_node.location[0] + 400, mix_node.location[1])++ for i, camera in enumerate(cameras):+ tex_image = tex_image_nodes[i]+ uv_map_node = uv_map_nodes[i]+ subtract = subtract_nodes[i]+ normalize = normalize_nodes[i]+ script = script_nodes[i]+ add_camera_loc = add_camera_loc_nodes[i]+ length = length_nodes[i]+ camera_fov = camera_fov_nodes[i]+ camera_aspect_ratio = camera_aspect_ratio_nodes[i]+ camera_direction = camera_direction_nodes[i]+ camera_up = camera_up_nodes[i]++ # Connect common nodes+ links.new(uv_map_node.outputs["UV"], tex_image.inputs["Vector"])+ links.new(geometry.outputs["Position"], subtract.inputs[0])+ links.new(subtract.outputs["Vector"], normalize.inputs[0])+ links.new(normalize.outputs["Vector"], script.inputs["Direction"])+ links.new(add_camera_loc.outputs["Vector"], script.inputs["Origin"])+ links.new(length.outputs["Value"], script.inputs["threshold"])+ links.new(geometry.outputs["Normal"], script.inputs["SurfaceNormal"])+ links.new(camera_fov.outputs[0], script.inputs["CameraFOV"])+ links.new(camera_aspect_ratio.outputs[0], script.inputs["CameraAspect"])+ links.new(camera_direction.outputs[0], script.inputs["CameraDir"])+ links.new(camera_up.outputs[0], script.inputs["CameraUp"])+ links.new(subtract.outputs["Vector"], length.inputs[0])++ # Add material index node (subtract node)+ subtract_node = nodes.new("ShaderNodeMath")+ subtract_node.operation = 'SUBTRACT'+ subtract_node.inputs[0].default_value = mat_id+ subtract_node.location = (-1000, 0)+ return True++def simple_project_bake(context, camera_id, obj, mat_id):+ # Create a temporary material for the projection+ mat = bpy.data.materials.new(name="ProjectionMaterialTemp")+ obj.data.materials.append(mat)++ # Switch the active material to the new material (Switch to edit mode, select all, assign the material)+ obj.active_material_index = len(obj.material_slots) - 1+ bpy.context.view_layer.objects.active = obj+ bpy.ops.object.mode_set(mode='EDIT')+ bpy.ops.mesh.select_all(action='DESELECT')+ bpy.ops.mesh.select_all(action='SELECT')+ bpy.ops.object.material_slot_assign()+ bpy.ops.object.mode_set(mode='OBJECT')++ # Unwrap (only for the first camera)+ if camera_id == 0:+ unwrap(obj, context.scene.bake_unwrap_method, context.scene.bake_unwrap_overlap_only)++ # Enable use of nodes+ mat.use_nodes = True+ nodes = mat.node_tree.nodes+ links = mat.node_tree.links++ # Clear existing nodes+ for node in nodes:+ nodes.remove(node)++ # Add image texture node+ tex_image = nodes.new("ShaderNodeTexImage")++ file_path = get_file_path(context, "generated", camera_id=camera_id, material_id=mat_id)+ if (context.scene.generation_method == 'sequential' or context.scene.generation_method == 'separate') and context.scene.sequential_ipadapter and context.scene.sequential_ipadapter_regenerate and not context.scene.use_ipadapter and camera_id == 0 and context.scene.sequential_ipadapter_mode == 'first':+ file_path = get_file_path(context, "generated", camera_id=camera_id, material_id=mat_id).replace(".png", "_ipadapter.png")++ tex_image.image = bpy.data.images.load(file_path)++ # Add UV map node+ uv_map_node = nodes.new("ShaderNodeUVMap")+ uv_map_node.uv_map = f"ProjectionUV_{camera_id}_{mat_id}"++ # Add BSDF node+ bsdf = nodes.new("ShaderNodeBsdfPrincipled")+ bsdf.inputs["Roughness"].default_value = 1.0++ # Add output node+ output = nodes.new("ShaderNodeOutputMaterial")+ links.new(uv_map_node.outputs["UV"], tex_image.inputs["Vector"])+ # Connect the nodes+ if context.scene.apply_bsdf:+ links.new(tex_image.outputs["Color"], bsdf.inputs["Base Color"])+ links.new(bsdf.outputs["BSDF"], output.inputs["Surface"])+ else:+ links.new(tex_image.outputs["Color"], output.inputs["Surface"])++ # Bake texture using BakeTextures.bake_texture+ texture_size = context.scene.bake_texture_size+ original_engine = context.scene.render.engine+ prepare_baking(context)++ # If the object has no UV map, create one+ if not obj.data.uv_layers:+ obj.data.uv_layers.new(name="UVMap")++ bake_texture(context, obj, texture_size, suffix=f"{camera_id}-{mat_id}", output_dir=get_dir_path(context, "generated_baked"))+ context.scene.render.engine = original_engine++ # Remove the temporary material+ bpy.ops.object.material_slot_remove()diff --git a/stablegen/raycast.osl b/stablegen/raycast.oslnew file mode 100644index 0000000..4cfd278--- /dev/null+++ b/stablegen/raycast.osl@@ -0,0 +1,69 @@+shader raycast(+ vector Origin = P, // Camera position in world space+ vector Direction = N, // Ray direction in world space+ vector SurfaceNormal = N,+ float threshold = 1,+ float CameraAspect = 1.77778, // width/height ratio (e.g., 16:9)+ float CameraFOV = 1.0, // horizontal FOV in radians+ vector CameraDir = vector(0,0,-1), // Camera look direction in world space+ vector CameraUp = vector(0,1,0), // Camera up vector in world space+ float AngleThreshold = 90.0, // Maximum angle in degrees between ray and normal+ float Power = 4.0, // Exponent for weight falloff (higher = sharper)+ output float Result = 0+)+{+ // Normalize the world-space ray direction.+ vector d = normalize(Direction);++ // Build camera basis.+ vector forward = normalize(CameraDir);+ vector r = normalize(cross(forward, CameraUp));+ vector upVector = normalize(cross(r, forward));++ // Transform the ray direction into the camera's coordinate system.+ float cam_x = dot(d, r);+ float cam_y = dot(d, upVector);+ float cam_z = dot(d, -forward); // should be negative for rays in front of the camera++ // Only process rays that are in front of the camera.+ if (cam_z >= 0) {+ Result = 0;+ return;+ }++ // Compute film extents at a virtual film plane at z = -1.+ float filmw = tan(CameraFOV * 0.5);+ float filmh = filmw / CameraAspect;++ // Project the ray direction onto the film plane.+ float x_proj = cam_x / -cam_z;+ float y_proj = cam_y / -cam_z;++ // If the projected point falls outside the film bounds, exit.+ if (abs(x_proj) > filmw || abs(y_proj) > filmh) {+ Result = 0;+ return;+ }++ // Continue with the raycast.+ float Distance = 99999999.99;+ if (trace(Origin, d))+ {+ getmessage("trace", "hitdist", Distance);+ if ((Distance + 0.001) < threshold)+ Result = 0;+ else {+ float dot_val = dot(d, normalize(SurfaceNormal));+ float orthogonality = abs(clamp(dot_val, -1.0, 1.0));+ float angle = acos(orthogonality) * 180.0 / M_PI;+ if (angle > AngleThreshold) {+ Result = 0;+ } else {+ Result = pow(orthogonality, Power);+ }+ }+ }+ else {+ Result = 0;+ }+}diff --git a/stablegen/render_tools.py b/stablegen/render_tools.pynew file mode 100644index 0000000..c829ce4--- /dev/null+++ b/stablegen/render_tools.py@@ -0,0 +1,1982 @@+""" This file contains the operators and panels for the StableGen addon """+# disable import-error because pylint doesn't recognize the blenders internal modules+import os+import bpy, bmesh # pylint: disable=import-error+import numpy as np+import math+import time+import mathutils+from mathutils import Matrix+import blf+from .utils import get_file_path, get_dir_path, remove_empty_dirs+from .util import install_testing+import tempfile+import shutil+try:+ import cv2+ import imageio+ import imageio_ffmpeg+except ImportError or ModuleNotFoundError:+ install_testing.install()+ import imageio+ import imageio_ffmpeg+ import cv2+import urllib.parse+from PIL import Image+++def apply_uv_inpaint_texture(context, obj, baked_image_path):+ """+ Applies the UV inpainted texture to the active material by replacing+ the fallback color node in the node tree.+ """+ mat = obj.active_material+ if not mat or not mat.use_nodes:+ return+ nodes = mat.node_tree.nodes+ links = mat.node_tree.links++ # Locate the Output Material node+ output_node = None+ for node in nodes:+ if node.type == 'OUTPUT_MATERIAL':+ output_node = node+ break+ if not output_node or not output_node.inputs["Surface"].links:+ return++ # Traverse from the output input to find a MIX_RGB node with unlinked Color2+ mix_node = None+ current_node = output_node.inputs[0].links[0].from_node.inputs[0].links[0].from_node+ while current_node:+ # Base case: Found a MIX_RGB node with unlinked Color2 or linked to image texture+ if (current_node.type == 'MIX_RGB' and+ (not current_node.inputs["Color2"].is_linked or current_node.inputs["Color2"].links[0].from_node.type == 'TEX_IMAGE')):+ mix_node = current_node+ break+ # If possible, traverse one step back using the first input link+ if current_node.inputs["Color2"].links:+ current_node = current_node.inputs["Color2"].links[0].from_node+ else:+ current_node = None++ if not mix_node:+ return++ # Insert the texture node feeding into the mix node+ tex_node = nodes.new("ShaderNodeTexImage")+ try:+ img = bpy.data.images.load(baked_image_path)+ except Exception as e:+ print("Failed to load image", baked_image_path, e)+ return+ tex_node.image = img+ tex_node.location = (mix_node.location[0] - 300, mix_node.location[1])+ # Remove any existing links on Color2 and connect new texture output+ for link in mix_node.inputs["Color2"].links:+ links.remove(link)+ links.new(tex_node.outputs["Color"], mix_node.inputs["Color2"])+ # Add UV map node+ uv_map_node = nodes.new("ShaderNodeUVMap")+ # Find first UV map which doesn't start with "ProjectionUV"+ uv_map_name = None+ for uv_map in obj.data.uv_layers:+ if uv_map.name.startswith("ProjectionUV"):+ continue+ uv_map_name = uv_map.name+ break+ if uv_map_name:+ uv_map_node.uv_map = uv_map_name+ else:+ uv_map_node.uv_map = obj.data.uv_layers.active.name+ uv_map_node.location = (tex_node.location[0] - 300, tex_node.location[1] - 200)+ # Connect UV map node to texture node+ links.new(uv_map_node.outputs["UV"], tex_node.inputs["Vector"])++def export_emit_image(context, camera_id=None, bg_color=(0.5, 0.5, 0.5), view_transform='Standard'):+ """+ Exports a emit-only render of the scene from a camera's perspective.+ :param context: Blender context.+ :param camera_id: ID of the camera.+ :return: None+ """+ print("Exporting emit render")+ # Set animation frame to 1+ bpy.context.scene.frame_set(1)++ # Store original materials and create temporary ones+ original_materials = {}+ original_active_material = {}+ temporary_materials = {}++ use_emission = True++ # Check if there is BSDF applied++ # We need to temporarily disconnect BDSF nodes and connect their inputs directly to the output++ for obj in context.scene.objects:+ if obj.type == 'MESH':+ # Store original materials+ original_materials[obj] = list(obj.data.materials)+ original_active_material[obj] = obj.active_material++ # Copy active material and switch to it+ mat = obj.active_material+ if not mat:+ continue+ mat_copy = mat.copy()++ # Clear materials and assign temp material+ obj.data.materials.clear()+ obj.data.materials.append(mat_copy)++ # Store the temporary material for later deletion+ temporary_materials[obj] = mat_copy++ # Enable use of nodes+ mat_copy.use_nodes = True+ nodes = mat_copy.node_tree.nodes+ links = mat_copy.node_tree.links++ # Find the output node+ output = None+ for node in nodes:+ if node.type == 'OUTPUT_MATERIAL':+ output = node+ break++ # Check the type of the node which connects to output+ before_output = output.inputs[0].links[0].from_node+ if before_output.type == 'BSDF_PRINCIPLED':+ # Find the last color mix node+ color_mix = output.inputs[0].links[0].from_node.inputs[0].links[0].from_node+ else:+ # Already a color mix node+ color_mix = before_output+ continue++ # Find the last color mix node+ color_mix = output.inputs[0].links[0].from_node.inputs[0].links[0].from_node+ # Connect the color mix node directly to the output+ links.new(color_mix.outputs[0], output.inputs[0])++ output_dir = get_dir_path(context, "inpaint")["visibility"] if "visibility" in str(camera_id) else get_dir_path(context, "inpaint")["render"]+ output_file = f"render{camera_id}" if camera_id is not None else "render"++ # Store and set world settings+ world = context.scene.world+ if not world:+ world = bpy.data.worlds.new("World")+ context.scene.world = world++ # Store original settings+ original_engine = context.scene.render.engine+ original_film_transparent = context.scene.render.film_transparent+ original_use_nodes = world.use_nodes+ original_color = world.color.copy() if not world.use_nodes else None++ # Now setting the world color should work+ world.color = bg_color+ # Disable world nodes temporarily+ world.use_nodes = False+ # Switch to CYCLES render engine and configure settings+ context.scene.render.engine = 'CYCLES'+ # Enable OSL+ context.scene.cycles.use_osl = True+ context.scene.cycles.device = 'CPU'+ context.scene.render.film_transparent = False+ # Change color management to standard+ bpy.context.scene.display_settings.display_device = 'sRGB'+ bpy.context.scene.view_settings.view_transform = view_transform+ context.scene.cycles.samples = 1 # Minimum samples for speed+ # Configure view layer settings for diffuse-only+ view_layer = context.view_layer+ view_layer.use_pass_diffuse_color = False+ view_layer.use_pass_diffuse_direct = False+ view_layer.use_pass_diffuse_indirect = False++ # Disable all other passes+ view_layer.use_pass_ambient_occlusion = False+ view_layer.use_pass_shadow = False+ view_layer.use_pass_emit = True+ view_layer.use_pass_environment = True+++ # Set up nodes for diffuse-only output+ context.scene.use_nodes = True+ nodes = context.scene.node_tree.nodes+ links = context.scene.node_tree.links++ # Clear existing nodes+ nodes.clear()++ # Create nodes+ render_layers = nodes.new('CompositorNodeRLayers')+ mix_node = nodes.new('CompositorNodeMixRGB')+ mix_node.blend_type = 'ADD'+ mix_node.inputs[0].default_value = 1+ output_node = nodes.new('CompositorNodeOutputFile')+ output_node.base_path = output_dir+ output_node.file_slots[0].path = output_file++ # Connect emission to output+ links.new(render_layers.outputs['Emit'], mix_node.inputs[1])+ links.new(render_layers.outputs['Env'], mix_node.inputs[2])+ links.new(mix_node.outputs[0], output_node.inputs[0])++ # Render+ bpy.ops.render.render(write_still=True)++ if context.scene.mask_blocky:+ # If this is a visibility mask, expand it to blocks+ if "visibility" in str(camera_id):+ # Load the rendered image+ image_path = os.path.join(output_dir, f"{output_file}.png")+ image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)++ image_path = image_path.replace(".png", "0001.png")++ # Expand the mask to blocks+ expanded_mask = expand_mask_to_blocks(image_path, block_size=8)++ # Scale float32 to uint8 [0, 255]+ expanded_mask = (expanded_mask * 255).astype(np.uint8)++ cv2.imwrite(image_path, expanded_mask)++ # Restore original settings+ context.scene.render.engine = original_engine+ context.scene.render.film_transparent = original_film_transparent+ if original_use_nodes:+ world.use_nodes = True+ elif original_color:+ world.color = original_color+ bpy.context.scene.view_settings.view_transform = 'Standard'++ # Restore original materials+ for obj, materials in original_materials.items():+ obj.data.materials.clear()+ # First append the original active material+ if original_active_material[obj]:+ obj.data.materials.append(original_active_material[obj])+ for mat in materials:+ if mat != original_active_material[obj]:+ obj.data.materials.append(mat)++ # Clean up temporary materials+ for _, temp_mat in temporary_materials.items():+ if temp_mat and temp_mat.name in bpy.data.materials:+ bpy.data.materials.remove(temp_mat)++ print(f"Emmision render saved to: {os.path.join(output_dir, output_file)}.png")++def export_render(context, camera_id=None):+ """+ Renders the scene from a camera's perspective using Workbench.+ Creates temporary materials for consistent rendering.+ :param context: Blender context.+ :param camera_id: ID of the camera for the output filename.+ :return: None+ """+ print("Exporting render using Workbench")++ # Store original materials and create temporary ones+ original_materials = {}+ original_active_material = {}+ for obj in context.scene.objects:+ if obj.type == 'MESH':+ # Store original materials+ original_materials[obj] = list(obj.data.materials)+ original_active_material[obj] = obj.active_material++ # Create temporary material+ temp_mat = bpy.data.materials.new(name="TempRenderMaterial")+ temp_mat.use_nodes = True # Even Workbench uses nodes for basic color+ nodes = temp_mat.node_tree.nodes+ links = temp_mat.node_tree.links++ # Clear default nodes+ for node in nodes:+ nodes.remove(node)++ # Create basic material output and diffuse BSDF (Workbench respects Base Color)+ mat_output = nodes.new('ShaderNodeOutputMaterial')+ diffuse = nodes.new('ShaderNodeBsdfDiffuse') # Simple diffuse color+ diffuse.inputs['Color'].default_value = (0.8, 0.8, 0.8, 1.0) # Default grey+ diffuse.inputs['Roughness'].default_value = 0.5+ links.new(diffuse.outputs['BSDF'], mat_output.inputs['Surface'])++ # Clear materials and assign temp material+ obj.data.materials.clear()+ obj.data.materials.append(temp_mat)++ # Set animation frame to 1+ context.scene.frame_set(1)++ # Setup output path+ output_dir = get_dir_path(context, "misc")+ output_file = f"render{camera_id}" if camera_id is not None else "render"++ # Store original render settings+ original_engine = context.scene.render.engine+ original_workbench_settings = {+ 'lighting': context.scene.display.shading.light,+ 'color_type': context.scene.display.shading.color_type+ }++ # Switch to WORKBENCH render engine and configure settings+ context.scene.render.engine = 'BLENDER_WORKBENCH'+ # Configure Workbench for a flat, consistent look if needed+ context.scene.display.shading.light = 'STUDIO'+ context.scene.display.shading.color_type = 'SINGLE'++ # Set up output nodes (Compositor setup remains the same)+ context.scene.use_nodes = True+ nodes = context.scene.node_tree.nodes+ links = context.scene.node_tree.links+ nodes.clear()++ render_layers = nodes.new('CompositorNodeRLayers')+ output_node = nodes.new('CompositorNodeOutputFile')+ output_node.base_path = output_dir+ output_node.file_slots[0].path = output_file+ links.new(render_layers.outputs['Image'], output_node.inputs[0])++ # Render+ bpy.ops.render.render(write_still=True)++ # Restore original materials+ for obj, materials in original_materials.items():+ obj.data.materials.clear()+ # First append the original active material+ if original_active_material[obj]:+ obj.data.materials.append(original_active_material[obj])+ for mat in materials:+ if mat != original_active_material[obj]:+ obj.data.materials.append(mat)++ # Clean up temporary materials+ # Use a while loop to safely remove materials while iterating+ temp_mats = [m for m in bpy.data.materials if m.name.startswith("TempRenderMaterial")]+ for mat in temp_mats:+ bpy.data.materials.remove(mat)+++ # Restore original render settings+ context.scene.render.engine = original_engine+ context.scene.display.shading.light = original_workbench_settings['lighting']+ context.scene.display.shading.color_type = original_workbench_settings['color_type']+++ print(f"Render saved to: {os.path.join(output_dir, output_file)}0001.png") # Blender adds frame number++def export_canny(context, camera_id=None, low_threshold=0, high_threshold=80):+ """+ Uses export_render and openCV to generate a Canny edge detection image.+ :param context: Blender context.+ :param camera_id: ID of the camera for the output filename.+ :param low_threshold: Low threshold for edge detection.+ :param high_threshold: High threshold for edge detection.+ :return: None+ """+ # Render the scene+ export_render(context, camera_id)++ # Load the rendered image+ output_dir_render = get_dir_path(context, "misc")+ output_dir_canny = get_dir_path(context, "controlnet")["canny"]+ output_file = f"render{camera_id}0001" if camera_id is not None else "render"+ image_path = os.path.join(output_dir_render, f"{output_file}.png")+ image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)++ # Apply Canny edge detection+ edges = cv2.Canny(image, low_threshold, high_threshold)++ # Save the edge detection image+ output_file = f"canny{camera_id}0001" if camera_id is not None else "canny"+ cv2.imwrite(os.path.join(output_dir_canny, f"{output_file}.png"), edges)++ print(f"Canny edge detection saved to: {os.path.join(output_dir_canny, output_file)}.png")+++def expand_mask_to_blocks(mask_file_path, block_size=8):+ """+ Loads a mask image from a file path and processes it so that any+ block_size x block_size grid cell containing any non-black pixel (value > 0)+ becomes fully white (1.0).++ Args:+ mask_file_path (str): The path to the mask image file.+ block_size (int): The size of the grid blocks (default: 8).++ Returns:+ np.ndarray | None: The processed mask as a NumPy array (float32, normalized [0, 1]).+ Returns None if the file cannot be loaded or processed.+ """+ if not isinstance(mask_file_path, str):+ print(f"Error: mask_file_path must be a string. Got: {type(mask_file_path)}")+ return None+ if not os.path.exists(mask_file_path):+ print(f"Error: Mask file not found at {mask_file_path}")+ return None+ if not os.path.isfile(mask_file_path):+ print(f"Error: Path provided is not a file: {mask_file_path}")+ return None++ try:+ # Load the image using Pillow+ with Image.open(mask_file_path) as img:+ # Convert to grayscale ('L') which typically represents intensity+ mask_pil = img.convert("L")+ # Convert PIL Image to numpy array+ mask_array = np.array(mask_pil)++ # --- Normalize mask to float32 [0, 1] ---+ # Ensures comparison with 0.0 is reliable regardless of original bit depth+ if mask_array.dtype == np.uint8:+ mask_array = mask_array.astype(np.float32) / 255.0+ elif np.issubdtype(mask_array.dtype, np.integer):+ max_val = np.iinfo(mask_array.dtype).max+ mask_array = mask_array.astype(np.float32) / max_val if max_val > 0 else mask_array.astype(np.float32)+ elif not np.issubdtype(mask_array.dtype, np.floating):+ print(f"Warning: Unsupported mask dtype {mask_array.dtype} after loading. Trying to convert.")+ mask_array = mask_array.astype(np.float32) # Attempt conversion+ # Ensure it's precisely within [0, 1] after potential float conversion+ mask_array = np.clip(mask_array, 0.0, 1.0)+ # --- End normalization ---++ max_value = 1.0 # Output will be normalized float [0, 1]++ height, width = mask_array.shape+ # Create output mask initialized to zeros (black), ensure float32 type+ output_mask = np.zeros_like(mask_array, dtype=np.float32)++ # --- Core block processing logic ---+ for y in range(0, height, block_size):+ for x in range(0, width, block_size):+ # Define block boundaries, handle image edges+ y_start = y+ y_end = min(y + block_size, height)+ x_start = x+ x_end = min(x + block_size, width)++ # Extract the current block+ block = mask_array[y_start:y_end, x_start:x_end]++ # Check if *any* pixel value in the block is greater than 0.0+ if np.any(block > 0.0):+ # If yes, set the corresponding block in the output mask to 1.0 (white)+ output_mask[y_start:y_end, x_start:x_end] = max_value+ # --- End of core logic ---++ return output_mask++ except FileNotFoundError:+ print(f"Error: Mask file not found at {mask_file_path}")+ return None+ except Exception as e:+ print(f"Error loading or processing mask file {mask_file_path}: {e}")+ return None+++def export_visibility(context, obj=None, camera_visibility=None):+ """+ Exports the visibility of the mesh by temporarily altering the shading nodes.+ :param context: Blender context.+ :param filepath: Path to the output file.+ :param obj: Blender object.+ :param camera_visibility: Camera object for visibility calculation.+ :return: None+ """+ # Store original materials and create temporary ones+ original_materials = {}+ original_active_material = {}+ temporary_materials = {}++ def prepare_material(obj):+ mat = obj.active_material+ if not mat:+ return False++ # Store original materials+ original_materials[obj] = list(obj.data.materials)+ original_active_material[obj] = obj.active_material # Store original active material++ # Store original active mat++ # Copy active material and switch to it+ mat = obj.active_material+ if not mat:+ return False+ mat_copy = mat.copy()++ # Clear materials and assign temp material+ obj.data.materials.clear()+ obj.data.materials.append(mat_copy)++ # Store temporary material for later deletion+ temporary_materials[obj] = mat_copy++ # Enable use of nodes+ mat_copy.use_nodes = True+ nodes = mat_copy.node_tree.nodes+ links = mat_copy.node_tree.links++ # Find the output node+ output = None+ for node in nodes:+ if node.type == 'OUTPUT_MATERIAL':+ output = node+ break++ if not output:+ return False++ # Determine which input to used based on existence of BSDF node before the output+ if output.inputs[0].links and output.inputs[0].links[0].from_node.type == 'BSDF_PRINCIPLED':+ color_mix = output.inputs[0].links[0].from_node.inputs[0].links[0].from_node+ input = output.inputs[0].links[0].from_node.inputs[0]+ else:+ color_mix = output.inputs[0].links[0].from_node+ input = output.inputs[0]+ # Add equal node between color mix and bsdf+ equal = nodes.new("ShaderNodeMath")++ # Use compare operation to filter to only 1 or 0++ if context.scene.generation_method == 'sequential' and context.scene.sequential_smooth:+ # Add color ramp node+ compare = nodes.new("ShaderNodeValToRGB")+ compare.color_ramp.interpolation = 'LINEAR'+ compare.color_ramp.elements[0].color = (0.0, 0.0, 0.0, 1.0)+ compare.color_ramp.elements[0].position = context.scene.sequential_factor_smooth if context.scene.generation_method == 'sequential' else 0.5+ compare.color_ramp.elements[1].color = (1.0, 1.0, 1.0, 1.0)+ compare.color_ramp.elements[1].position = context.scene.sequential_factor_smooth_2 if context.scene.generation_method == 'sequential' else 1.0+ links.new(color_mix.outputs[0], compare.inputs[0])+ links.new(compare.outputs[0], input)+ elif not context.scene.allow_modify_existing_textures or context.scene.generation_method == 'sequential':+ equal.operation = 'COMPARE'+ equal.inputs[1].default_value = 1+ equal.inputs[2].default_value = context.scene.sequential_factor if context.scene.generation_method == 'sequential' else 0.0+ equal.location = (color_mix.location[0], color_mix.location[1])+ links.new(color_mix.outputs[0], equal.inputs[0])+ links.new(equal.outputs[0], input)+ else:+ links.new(color_mix.outputs[0], input)++ while True:+ # Remove color ramp connected to fac, connect directly to color ramp's fac+ color_ramp = color_mix.inputs[0].links[0].from_node+ fac_node = color_ramp.inputs[0].links[0].from_node+ # Add subtract node+ subtract = nodes.new("ShaderNodeMath")+ subtract.operation = 'SUBTRACT'+ subtract.location = (color_ramp.location[0], color_ramp.location[1])+ subtract.inputs[0].default_value = 1+ links.new(fac_node.outputs[0], subtract.inputs[1])+ links.new(subtract.outputs[0], color_mix.inputs["Fac"])+ nodes.remove(color_ramp)+ # Disconnect color1+ links.remove(color_mix.inputs[1].links[0])+ color_mix.inputs["Color1"].default_value = (0, 0, 0, 1)+ if not (color_mix.inputs["Color2"].links and (color_mix.inputs[2].links[0].from_node.type == 'MIX_RGB')):+ color_mix.inputs["Color2"].default_value = (1, 1, 1, 1)+ break+ else:+ color_mix = color_mix.inputs["Color2"].links[0].from_node+ # If there is previous tex_image node, remove it (for cases when this function is called multiple times)+ if color_mix.inputs["Color2"].is_linked:+ nodes.remove(color_mix.inputs["Color2"].links[0].from_node)++ for node in nodes:+ if node.type == 'SCRIPT' and "Power" in node.inputs:+ try:+ # Set according to weight_exponent_mask+ node.inputs["Power"].default_value = context.scene.weight_exponent if context.scene.weight_exponent_mask else 1.0+ except Exception as e:+ print(f" - Warning: Failed to set Power for node '{node.name}'. Error: {e}")++ return True++ # Prepare the material+ mesh_objects = [obj for obj in context.scene.objects if obj.type == 'MESH']+ if not obj:+ # Prepare for all objects+ for obj in mesh_objects:+ if not prepare_material(obj):+ return False+ else:+ if not prepare_material(obj):+ return False++ # Bake or render the texture+ if not camera_visibility:+ output_dir = get_dir_path(context, "uv_inpaint")["visibility"]+ output_file = f"{obj.name}_baked_visibility"+ prepare_baking(context)+ bake_texture(context, obj, suffix="_visibility", texture_resolution=1024, view_transform='Raw', output_dir=output_dir)+ # Use openCV to normalize the image+ image_path = os.path.join(output_dir, f"{output_file}.png")+ image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)+ # Normalize the image+ image = cv2.normalize(image, None, 0, 255, cv2.NORM_MINMAX)+ # Save the image+ cv2.imwrite(image_path, image)+ else:+ # Make sure the camera is active and set to render+ cameras = [obj for obj in context.scene.objects if obj.type == 'CAMERA']+ cameras.sort(key=lambda x: x.name)+ camera_visibility_index = [i for i, camera in enumerate(cameras) if camera == camera_visibility][0]+ camera_render_index = (camera_visibility_index + 1) % len(cameras)+ camera_render = cameras[camera_render_index]+ context.scene.camera = camera_render+ export_emit_image(context, camera_id=f"{camera_render_index}_visibility", bg_color=(1, 1, 1), view_transform='Raw')+ ### if camera_index == 1: return False # test++ # Restore original materials+ for obj, materials in original_materials.items():+ obj.data.materials.clear()+ # First append the original active material+ if original_active_material[obj]:+ obj.data.materials.append(original_active_material[obj])+ for mat in materials:+ if mat != original_active_material[obj]:+ obj.data.materials.append(mat)++ # Clean up temporary materials+ for _, temp_mat in temporary_materials.items():+ if temp_mat and temp_mat.name in bpy.data.materials:+ bpy.data.materials.remove(temp_mat)++ return True++class AddCameras(bpy.types.Operator):+ """Add cameras along a circle and adjust their positions++ Uses the active camera as a reference. If there is no active camera, a new one is created based on the viewport.++ Tips:+ - Try to frame the object / scene with minimal margin around it.+ - Aim to achieve a uniform coverage of the object / scene.+ - Areas not visible from any camera won't get textured. (Can still be UV-inpainted)+ - Aspect ratio is set by Blender's output settings."""+ bl_category = "ControlNet"+ bl_idname = "object.add_cameras"+ bl_label = "Add Cameras"+ bl_options = {'REGISTER', 'UNDO'}++ num_cameras: bpy.props.IntProperty(+ name="Number of Cameras",+ description="Number of cameras to add (including reference camera if none exists)",+ default=4,+ min=1,+ max=100+ ) # type: ignore++ center_type: bpy.props.EnumProperty(+ name="Center Type",+ description="Type of center for the cameras",+ items=[+ ('object', "Object", "Use the active object as the center"),+ ('view center', "View Center", "Use the view center as the center"),+ ],+ default='object'+ ) # type: ignore++ purge_others: bpy.props.BoolProperty(+ name="Remove Other Cameras",+ description="Delete all existing cameras except the active/reference camera before adding new ones",+ default=True+ ) # type: ignore++ _timer = None+ _last_time = 0.0+ _camera_index = 0+ _cameras = []+ _initial_camera = None+ _draw_handle = None++ def draw_callback(self, context):+ try:+ count = len(self._cameras)+ idx = self._camera_index+ except Exception:+ return+ if count == 0:+ return+ font_id = 0+ msg = f"Camera: {idx+1}/{count} | Press SPACE to confirm"+ region = context.region+ rw, rh = region.width, region.height+ text_width, text_height = blf.dimensions(font_id, msg)+ x = (rw - text_width) / 2+ y = rh * 0.10+ blf.position(font_id, x, y, 0)+ blf.size(20, 72)+ blf.draw(font_id, msg)++ def execute(self, context):+ # delete other cameras if requested+ if self.purge_others:+ scene = context.scene+ # gather all camera objects except the active/reference+ to_remove = [obj for obj in bpy.data.objects if obj.type == 'CAMERA' and obj != scene.camera]+ for cam in to_remove:+ # unlink from all collections+ for col in list(cam.users_collection):+ col.objects.unlink(cam)+ # remove the object+ bpy.data.objects.remove(cam, do_unlink=True)+ # also purge unused camera data+ for cam_data in list(bpy.data.cameras):+ if not cam_data.users:+ bpy.data.cameras.remove(cam_data)++ if self.center_type == 'object':+ obj = context.object+ if not obj:+ self.report({'WARNING'}, "No active object found. Using view center instead.")+ self.center_type = 'view center'++ # add draw handler+ if AddCameras._draw_handle is None:+ AddCameras._draw_handle = bpy.types.SpaceView3D.draw_handler_add(+ self.draw_callback, (context,), 'WINDOW', 'POST_PIXEL')++ # determine center location+ if self.center_type == 'object':+ obj = context.object+ cursor_loc = context.scene.cursor.location.copy()+ context.scene.cursor.location = obj.location.copy()+ bpy.ops.object.origin_set(type='ORIGIN_CENTER_OF_MASS')+ center_location = obj.location.copy()+ bpy.ops.object.origin_set(type='ORIGIN_CURSOR')+ context.scene.cursor.location = cursor_loc+ center_location = obj.matrix_world.translation + obj.matrix_world.to_3x3() @ (center_location - obj.matrix_world.translation)+ else:+ center_location = context.region_data.view_location.copy()++ # set or create reference camera+ self._initial_camera = context.scene.camera+ using_viewport_ref = False+ if not self._initial_camera:+ rv3d = context.region_data+ cam_data = bpy.data.cameras.new(name='Camera_0')+ cam_obj = bpy.data.objects.new('Camera_0', cam_data)+ context.collection.objects.link(cam_obj)+ cam_obj.matrix_world = rv3d.view_matrix.inverted()+ context.scene.camera = cam_obj+ self._initial_camera = cam_obj+ using_viewport_ref = True++ # capture transform & settings+ ref_mat = self._initial_camera.matrix_world.copy()+ initial_pos = self._initial_camera.location.copy()+ cam_settings = self._initial_camera.data++ # how many around circle+ total = self.num_cameras+ count = total - 1 if using_viewport_ref else total++ # compute circle+ radius = (initial_pos - center_location).length+ angle_initial = math.atan2(initial_pos.y - center_location.y, initial_pos.x - center_location.x)+ angle_step = 2 * math.pi / (count + 1)++ self._cameras.clear()+ self._cameras.append(self._initial_camera)+ self._camera_index = 0++ for i in range(count):+ angle = (i + 1) * angle_step + angle_initial+ cam_data_new = bpy.data.cameras.new(name=f'Camera_{i+1}')+ cam_obj_new = bpy.data.objects.new(f'Camera_{i+1}', cam_data_new)+ context.collection.objects.link(cam_obj_new)+ if using_viewport_ref:+ delta = (i + 1) * angle_step+ T1 = Matrix.Translation(-center_location)+ Rz = Matrix.Rotation(delta, 4, 'Z')+ T2 = Matrix.Translation(center_location)+ cam_obj_new.matrix_world = T2 @ Rz @ T1 @ ref_mat+ else:+ x = center_location.x + radius * math.cos(angle)+ y = center_location.y + radius * math.sin(angle)+ z = initial_pos.z+ cam_obj_new.location = (x, y, z)+ direction = center_location - cam_obj_new.location+ rot = direction.to_track_quat('-Z', 'Y')+ cam_obj_new.rotation_euler = rot.to_euler()+ # copy settings+ cam_obj_new.data.type = cam_settings.type+ cam_obj_new.data.lens = cam_settings.lens+ cam_obj_new.data.sensor_width = cam_settings.sensor_width+ cam_obj_new.data.sensor_height = cam_settings.sensor_height+ cam_obj_new.data.clip_start = cam_settings.clip_start+ cam_obj_new.data.clip_end = cam_settings.clip_end+ self._cameras.append(cam_obj_new)++ # frame camera in viewport+ rv3d = context.region_data+ context.scene.camera = self._cameras[0]+ if rv3d.view_perspective != 'CAMERA':+ bpy.ops.view3d.view_camera()+ bpy.ops.view3d.view_center_camera()+ try:+ rv3d.view_camera_zoom = 1.0+ except Exception:+ pass++ # start fly nav+ context.window_manager.modal_handler_add(self)+ self._timer = context.window_manager.event_timer_add(0.5, window=context.window)+ self._last_time = time.time()+ bpy.ops.view3d.fly('INVOKE_DEFAULT')+ return {'RUNNING_MODAL'}++ def modal(self, context, event):+ if event.type == 'LEFTMOUSE' and event.value == 'RELEASE':+ if time.time() - self._last_time < 0.2:+ return {'RUNNING_MODAL'}++ if event.type == 'TIMER':+ fly_running = any(op.bl_idname == 'VIEW3D_OT_fly'+ for w in context.window_manager.windows+ for op in w.modal_operators)+ if not fly_running:+ self._camera_index += 1+ if self._camera_index >= len(self._cameras):+ context.window_manager.event_timer_remove(self._timer)+ if AddCameras._draw_handle:+ bpy.types.SpaceView3D.draw_handler_remove(AddCameras._draw_handle, 'WINDOW')+ AddCameras._draw_handle = None+ context.scene.camera = self._initial_camera+ self.report({'INFO'}, "Cameras added successfully.")+ return {'FINISHED'}+ context.scene.camera = self._cameras[self._camera_index]+ self._last_time = time.time()+ bpy.ops.view3d.fly('INVOKE_DEFAULT')+ return {'PASS_THROUGH'}++ return {'PASS_THROUGH'}++ @classmethod+ def poll(cls, context):+ # Check for any running modal operator+ operator = None+ for window in context.window_manager.windows:+ for op in window.modal_operators:+ if op.bl_idname == 'OBJECT_OT_test_stable' or op.bl_idname == 'OBJECT_OT_collect_camera_prompts' or op.bl_idname == 'OBJECT_OT_bake_textures' or op.bl_idname == 'OBJECT_OT_add_cameras':+ operator = op+ break+ if operator:+ break+ if operator:+ return False+ return not any(op.bl_idname == cls.bl_idname+ for w in context.window_manager.windows+ for op in w.modal_operators)++ def invoke(self, context, event):+ return context.window_manager.invoke_props_dialog(self)++++def switch_viewport_to_camera(context, camera):+ """Switches the first found 3D viewport to the specified camera's view."""+ if not camera:+ return+ for area in context.screen.areas:+ if area.type == 'VIEW_3D':+ # Ensure we are in the right space and region+ for space in area.spaces:+ if space.type == 'VIEW_3D':+ space.region_3d.view_perspective = 'CAMERA'+ # Make sure the scene's active camera is set+ context.scene.camera = camera+ area.tag_redraw()+ break+ break++# Define the PropertyGroup to store camera prompts+class CameraPromptItem(bpy.types.PropertyGroup):+ name: bpy.props.StringProperty(+ name="Camera Name",+ description="Name of the camera object"+ ) # type: ignore+ prompt: bpy.props.StringProperty(+ name="View Description",+ description="Description of the view from this camera"+ ) # type: ignore++class CollectCameraPrompts(bpy.types.Operator):+ """Cycles through cameras and prompts for a viewpoint description for each. This can help when specific perspectives fail to generate correctly.++ - These prompts will be appended before the main prompt for each camera generation.+ - Applicable for separate, sequential and refine (also within grid mode) modes.+ - Examples: 'front view', 'close-up on face', 'from above'."""+ bl_idname = "object.collect_camera_prompts"+ bl_label = "Collect Camera View Prompts"+ bl_options = {'REGISTER', 'UNDO'}++ camera_prompt: bpy.props.StringProperty(+ name="View Description",+ description="Describe the view from this camera (e.g., 'front view', 'close-up on face', 'from above')",+ default=""+ ) # type: ignore++ # Internal state+ _cameras: list = []+ _camera_index: int = 0++ @classmethod+ def poll(cls, context):+ # Check for any running modal operator+ operator = None+ for window in context.window_manager.windows:+ for op in window.modal_operators:+ if op.bl_idname == 'OBJECT_OT_test_stable' or op.bl_idname == 'OBJECT_OT_add_cameras' or op.bl_idname == 'OBJECT_OT_bake_textures' or op.bl_idname == 'OBJECT_OT_collect_camera_prompts':+ operator = op+ break+ if operator:+ break+ if operator:+ return False+ return any(obj.type == 'CAMERA' for obj in context.scene.objects)++ def invoke(self, context, event):+ # Get all camera objects and sort them by name+ self._cameras = sorted([obj for obj in context.scene.objects if obj.type == 'CAMERA'], key=lambda x: x.name)++ if not self._cameras:+ self.report({'ERROR'}, "No cameras found in the scene.")+ return {'CANCELLED'}++ # Initialize state+ self._camera_index = 0++ # Set the first camera and pre-fill prompt if exists+ current_cam = self._cameras[self._camera_index]++ # Find existing prompt or set default+ existing_item = next((item for item in context.scene.camera_prompts if item.name == current_cam.name), None)+ self.camera_prompt = existing_item.prompt if existing_item else ""++ context.scene.camera = current_cam+ switch_viewport_to_camera(context, current_cam) # Switch viewport+ return context.window_manager.invoke_props_dialog(self, width=400)++ def draw(self, context):+ layout = self.layout+ if self._camera_index < len(self._cameras):+ layout.label(text=f"Camera: {self._cameras[self._camera_index].name} ({self._camera_index + 1}/{len(self._cameras)})")+ layout.prop(self, "camera_prompt")++ def execute(self, context):+ cam_name = self._cameras[self._camera_index].name++ # Find existing item or add a new one+ prompt_item = next((item for item in context.scene.camera_prompts if item.name == cam_name), None)+ if not prompt_item:+ prompt_item = context.scene.camera_prompts.add()+ prompt_item.name = cam_name++ prompt_item.prompt = self.camera_prompt.strip() # Store trimmed prompt++ self._camera_index += 1+ if self._camera_index < len(self._cameras):+ next_cam = self._cameras[self._camera_index]+ # Pre-fill next prompt+ existing_item = next((item for item in context.scene.camera_prompts if item.name == next_cam.name), None)+ self.camera_prompt = existing_item.prompt if existing_item else ""+ # Ensure scene camera is set for next dialog and switch view+ context.scene.camera = next_cam+ switch_viewport_to_camera(context, next_cam) # Switch viewport+ return context.window_manager.invoke_props_dialog(self, width=400) # Show next dialog+ else:+ self.report({'INFO'}, f"Collected prompts for {len(self._cameras)} cameras.")+ return {'FINISHED'}+++class SwitchMaterial(bpy.types.Operator):+ """Switches the material of all objects to a desired index."""++ bl_idname = "object.switch_material"+ bl_label = "Switch Material"+ bl_options = {'REGISTER', 'UNDO'}++ material_index: bpy.props.IntProperty(+ name="Material Index",+ description="Index of the material to switch to",+ default=0,+ min=0+ ) # type: ignore++ def invoke(self, context, event):+ return context.window_manager.invoke_props_dialog(self)++ def execute(self, context):+ """+ Executes the operator.+ :param context: Blender context.+ :return: {'FINISHED'}+ """+ # Select all objects+ bpy.ops.object.select_all(action='SELECT')+++ for obj in context.selected_objects:+ if obj.type != 'MESH':+ continue+ if self.material_index < len(obj.data.materials):+ obj.active_material_index = self.material_index+ # Store original materials+ original_materials = list(obj.data.materials)+ # Store the material to be set as active+ to_be_active_material = obj.active_material+ # Clear materials and assign the material at the specified index+ obj.data.materials.clear()+ obj.data.materials.append(to_be_active_material)+ # Restore original materials+ for mat in original_materials:+ if mat != to_be_active_material:+ obj.data.materials.append(mat)++ # Deselct all objects+ bpy.ops.object.select_all(action='DESELECT')+ return {'FINISHED'}++def prepare_baking(context):+ bpy.context.scene.render.engine = 'CYCLES'+ bpy.context.scene.cycles.use_osl = True+ bpy.context.scene.cycles.device = 'CPU'++ # Set bake type to diffuse and contributions to color only+ bpy.context.scene.cycles.bake_type = 'DIFFUSE'+ bpy.context.scene.render.bake.use_pass_direct = False+ bpy.context.scene.render.bake.use_pass_indirect = False+ bpy.context.scene.render.bake.use_pass_color = True+ bpy.context.scene.render.bake.view_from = 'ABOVE_SURFACE'++ # Set steps to 1 for faster baking+ bpy.context.scene.cycles.samples = 1++def unwrap(obj, method, overlap_only):+ """+ Unwraps the UVs of the given object using the selected method.+ :param obj: Blender object.+ :return: None+ """+ if method == 'none':+ return++ # Deselect all objects+ bpy.ops.object.select_all(action='DESELECT')+ # Set object as active and select it+ bpy.context.view_layer.objects.active = obj+ obj.select_set(True)++ is_new = False++ # If all UN maps are ProjectionUV, add new one+ if all(["ProjectionUV" in uv.name for uv in obj.data.uv_layers]):+ # Add a new UV map+ obj.data.uv_layers.new(name=f"BakeUV")+ is_new = True+ obj.data.uv_layers.active_index = len(obj.data.uv_layers) - 1+ # Set it for rendering+ obj.data.uv_layers.active = obj.data.uv_layers[-1]++ bpy.ops.object.mode_set(mode='EDIT')++ # Ensure UV selection sync is OFF+ bpy.context.scene.tool_settings.use_uv_select_sync = False++ if overlap_only:+ # Deselect+ bpy.ops.uv.select_all(action='DESELECT')+ # Check if the object has overlapping UVs, if not, skip unwrapping+ bpy.ops.uv.select_overlap()+ # Get a BMesh representation of the mesh+ bm = bmesh.from_edit_mesh(obj.data)+ bm.faces.ensure_lookup_table()+ # Use the active UV layer (this is a BMUVLayer)+ uv_layer = bm.loops.layers.uv.active+ uv_layer = bm.loops.layers.uv.active+ if not uv_layer:+ bpy.ops.object.mode_set(mode='OBJECT')+ return++ # Check for ANY selected UV elements+ has_overlap = any(+ loop[uv_layer].select+ for face in bm.faces+ for loop in face.loops+ )++ if not has_overlap:+ bpy.ops.object.mode_set(mode='OBJECT')+ return++ bpy.context.scene.tool_settings.use_uv_select_sync = True+ # Select all faces+ bpy.ops.mesh.select_all(action='SELECT')++ if method == 'basic':+ bpy.ops.uv.unwrap(method='ANGLE_BASED', margin=0.001)+ elif method == 'smart':+ bpy.ops.uv.smart_project()+ elif method == 'lightmap':+ bpy.ops.uv.lightmap_pack()+ elif method == 'pack':+ bpy.ops.uv.pack_islands()++ bpy.ops.uv.select_all(action='DESELECT')+ bpy.ops.object.mode_set(mode='OBJECT')++def bake_texture(context, obj, texture_resolution, suffix = "", view_transform = 'Standard', output_dir = None):+ """+ Bakes the texture of the given object.+ :param context: Blender context.+ :param obj: Blender object.+ :return: True if successful, False otherwise.+ """+ bpy.context.scene.display_settings.display_device = 'sRGB'+ # Backup original view transform+ original_view_transform = bpy.context.scene.view_settings.view_transform+ # Backup whether the object was enabled for rendering+ original_render = obj.hide_render++ bpy.context.scene.view_settings.view_transform = view_transform+ # Set the object to be rendered+ obj.hide_render = False++ # Create a new image for baking+ image_name = f"{obj.name}_baked{suffix}"+ image = bpy.data.images.new(name=image_name, width=texture_resolution, height=texture_resolution)++ # Create a new texture node in the object's material+ if not obj.data.materials:+ # Cancel+ print("No materials found")+ return False+ else:+ # Temporarily remove all original materials+ mat = obj.active_material.copy()+ original_materials = list(obj.data.materials)+ original_active_material = obj.active_material+ obj.data.materials.clear()+ obj.data.materials.append(mat)++ mat.use_nodes = True+ nodes = mat.node_tree.nodes+ links = mat.node_tree.links++ tex_image = nodes.new("ShaderNodeTexImage")+ tex_image.image = image+ tex_image.location = (0, 0)++ # Deselect all objects+ bpy.ops.object.select_all(action='DESELECT')+ # Set object as active and select it+ bpy.context.view_layer.objects.active = obj+ obj.select_set(True)+ # Set the image node as the active bake target+ nodes.active = tex_image++ # Check if there is a BSDF node before the output node+ output = None+ had_bsdf = False+ for node in nodes:+ if node.type == 'OUTPUT_MATERIAL':+ output = node+ break++ before_output = output.inputs[0].links[0].from_node if output and output.inputs[0].is_linked else None+ if before_output and before_output.type != 'BSDF_PRINCIPLED':+ bsdf_node = nodes.new("ShaderNodeBsdfPrincipled")+ bsdf_node.location = (before_output.location[0] + 200, before_output.location[1])+ # Connect the before output node to the BSDF node+ links.new(before_output.outputs[0], bsdf_node.inputs[0])+ # Connect the BSDF node to the output node+ links.new(bsdf_node.outputs[0], output.inputs[0])++ # Bake the texture+ bpy.ops.object.bake(type='DIFFUSE', save_mode='EXTERNAL', filepath=image.filepath, width=texture_resolution, height=texture_resolution)++ # Save the image if required+ if not os.path.exists(output_dir):+ os.makedirs(output_dir)+ if suffix == "":+ image.filepath_raw = os.path.join(output_dir, f"{obj.name}.png")+ else:+ image.filepath_raw = os.path.join(output_dir, f"{obj.name}_baked{suffix}.png")+ image.file_format = 'PNG'+ image.save()++ # Remove tex_image node+ nodes.remove(tex_image)++ # Restore original view transform+ bpy.context.scene.view_settings.view_transform = original_view_transform+ # Restore original render settings+ obj.hide_render = original_render++ # Restore original materials+ obj.data.materials.clear()+ # First append the original active material+ if original_active_material:+ obj.data.materials.append(original_active_material)+ for mat in original_materials:+ if mat != original_active_material:+ obj.data.materials.append(mat)++ return True++class BakeTextures(bpy.types.Operator):+ """Bakes textures using the cycles render engine.++ - This will convert the textures to use a UV map. The first non-projection UV map will be used. If there are none, a new one will be created.+ - Textures will be output to the "baked" directory in the output path.+ - This will make the generated textures available in the Material Preview viewport shading mode."""+ bl_idname = "object.bake_textures"+ bl_label = "Bake Textures"+ bl_options = {'REGISTER', 'UNDO'}++ texture_resolution: bpy.props.IntProperty(+ name="Texture Resolution",+ description="Resolution of the baked textures",+ default=2048,+ min=128,+ max=8192+ ) # type: ignore++ try_unwrap: bpy.props.EnumProperty(+ name="Unwrap Method",+ description="Method to unwrap UVs before baking",+ items=[+ ('none', 'None', 'Skip UV unwrapping'),+ ('basic', 'Basic Unwrap', 'Use basic angle-based unwrapping'),+ ('smart', 'Smart UV Project', 'Use Smart UV Project with default parameters'),+ ('lightmap', 'Lightmap Pack', 'Use Lightmap Pack with default parameters'),+ ('pack', 'Pack Islands', 'Use Pack Islands with default parameters')+ ],+ default='none'+ ) # type: ignore++ add_material: bpy.props.BoolProperty(+ name="Add Material",+ description="Add the baked texture as a material to the objects",+ default=True+ ) # type: ignore++ overlap_only: bpy.props.BoolProperty(+ name="Overlap Only",+ description="Only unwrap objects with overlapping UVs",+ default=False+ ) # type: ignore++ _timer = None+ _objects = []+ _current_index = 0+ _phase = 'unwrap'++ # Add properties to track progress+ _progress = 0.0+ _stage = ""+ _current_object = 0+ _total_objects = 0++ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ self._progress = 0+ self._stage = ""+ self._current_object = 0+ self._total_objects = 0++ @classmethod+ def poll(self, context):+ """+ Checks if the operator can be executed+ :param context: Blender context.+ :return: True if the operator can be executed, False otherwise.+ """+ # Check for any running modal operator+ operator = None+ for window in context.window_manager.windows:+ for op in window.modal_operators:+ if op.bl_idname == 'OBJECT_OT_test_stable' or op.bl_idname == 'OBJECT_OT_add_cameras' or op.bl_idname == 'OBJECT_OT_collect_camera_prompts' or op.bl_idname == 'OBJECT_OT_bake_textures':+ operator = op+ break+ if operator:+ break+ if operator:+ return False++ # Check if there are any textures to bake+ return True++ def invoke(self, context, event):+ """+ Invokes the operator.+ :param context: Blender context.+ :param event: Blender event.+ :return: {'RUNNING_MODAL'}+ """+ self._objects = [obj for obj in context.scene.objects if obj.type == 'MESH']+ self._current_index = 0+ self._phase = 'unwrap'+ self._total_objects = len(self._objects)+ self._stage = "Preparing"+ return context.window_manager.invoke_props_dialog(self)++ def execute(self, context):+ """+ Executes the operator.+ :param context: Blender context.+ :return: {'RUNNING_MODAL'}+ """++ self.original_engine = bpy.context.scene.render.engine+ self.original_shading = bpy.context.space_data.shading.type+ # Set render engine to CYCLES+ bpy.context.scene.render.engine = 'CYCLES'+ # Set viewport shading to "MATERIAL_PREVIEW"+ for area in context.screen.areas:+ if area.type == 'VIEW_3D':+ for space in area.spaces:+ if space.type == 'VIEW_3D':+ space.shading.type = 'MATERIAL'+ break+ prepare_baking(context)++ # Start modal operation+ context.window_manager.modal_handler_add(self)+ self._timer = context.window_manager.event_timer_add(0.1, window=context.window)+ return {'RUNNING_MODAL'}++ def modal(self, context, event):+ """+ Handles modal events.+ :param context: Blender context.+ :param event: Blender event.+ :return: {'PASS_THROUGH'}+ """+ if event.type == 'TIMER':+ def redraw():+ for area in context.screen.areas:+ area.tag_redraw()+ redraw()++ if self._current_index < len(self._objects):+ obj = self._objects[self._current_index]+ if self._phase == 'unwrap':+ self._stage = f"Unwrapping {obj.name}"+ self._progress = 0+ redraw()+ unwrap(obj, self.try_unwrap, self.overlap_only)+ self._progress = 100+ elif self._phase == 'bake':+ self._stage = f"Baking {obj.name}"+ self._progress = 0+ redraw()+ if not bake_texture(context, obj, self.texture_resolution, output_dir=get_dir_path(context, "baked")):+ self.report({'ERROR'}, f"Failed to bake texture for {obj.name}. No materials found.")+ context.window_manager.event_timer_remove(self._timer)+ return {'CANCELLED'}+ self._progress = 100+ elif self._phase == 'apply_material' and self.add_material:+ self._stage = f"Applying Material to {obj.name}"+ self._progress = 0+ redraw()+ self.add_baked_material(context, obj)+ self._progress = 100+ self._current_index += 1+ if self._current_index < len(self._objects):+ self._current_object = self._current_index+ else:+ if self._phase == 'unwrap':+ self.report({'INFO'}, "Baking textures...")+ self._phase = 'bake'+ self._current_index = 0+ elif self._phase == 'bake':+ self.report({'INFO'}, "Applying materials...")+ self._phase = 'apply_material'+ self._current_index = 0+ else:+ context.window_manager.event_timer_remove(self._timer)+ bpy.context.scene.render.engine = self.original_engine+ # Restore original shading type+ for area in context.screen.areas:+ if area.type == 'VIEW_3D':+ for space in area.spaces:+ if space.type == 'VIEW_3D':+ space.shading.type = self.original_shading+ break+ self.report({'INFO'}, "Textures baked successfully.")+ remove_empty_dirs(context)+ return {'FINISHED'}+ return {'PASS_THROUGH'}++ def add_baked_material(self, context, obj):+ mat = bpy.data.materials.new(name=f"{obj.name}_baked")+ obj.data.materials.append(mat)++ mat.use_nodes = True+ nodes = mat.node_tree.nodes+ links = mat.node_tree.links+ # Remove all existing nodes+ for node in nodes:+ nodes.remove(node)++ # Switch the active material to the new material (Switch to edit mode, select all, assign the material)+ obj.active_material_index = len(obj.material_slots) - 1+ bpy.context.view_layer.objects.active = obj+ bpy.ops.object.mode_set(mode='EDIT')+ bpy.ops.mesh.select_all(action='SELECT')+ bpy.ops.object.material_slot_assign()+ bpy.ops.object.mode_set(mode='OBJECT')++ # Add output node+ output_node = nodes.new("ShaderNodeOutputMaterial")+ output_node.location = (600, 0)++ # Add principled shader node+ principled_node = nodes.new("ShaderNodeBsdfPrincipled")+ principled_node.location = (400, 0)+ principled_node.inputs["Roughness"].default_value = 1.0+++ # Add uv map node+ uv_map_node = nodes.new("ShaderNodeUVMap")+ # If there is "BakeUV" uv map, use it+ if "BakeUV" in [uv.name for uv in obj.data.uv_layers]:+ uv_map_node.uv_map = "BakeUV"+ else:+ uv_map_node.uv_map = obj.data.uv_layers[0].name+ uv_map_node.location = (-200, 0)++ mat.use_nodes = True+ nodes = mat.node_tree.nodes+ links = mat.node_tree.links++ # Add image texture node+ tex_image = nodes.new("ShaderNodeTexImage")+ # Load the saved image+ tex_image.image = bpy.data.images.load(get_file_path(context, "baked", object_name=obj.name))+ tex_image.location = (0, 0)++ # Connect nodes+ links.new(uv_map_node.outputs["UV"], tex_image.inputs["Vector"])++ if context.scene.apply_bsdf:+ links.new(tex_image.outputs["Color"], principled_node.inputs["Base Color"])+ links.new(principled_node.outputs["BSDF"], output_node.inputs["Surface"])+ else:+ links.new(tex_image.outputs["Color"], output_node.inputs["Surface"])+++class ExportOrbitGIF(bpy.types.Operator):+ """Exports a GIF and MP4 animation orbiting the active object"""+ bl_idname = "object.export_orbit_gif"+ bl_label = "Export Orbit GIF/MP4"+ bl_options = {'REGISTER', 'UNDO'}++ duration: bpy.props.FloatProperty(+ name="Duration (seconds)",+ description="Duration of the 360-degree orbit",+ default=5.0,+ min=0.1,+ max=60.0+ ) # type: ignore++ frame_rate: bpy.props.IntProperty(+ name="Frame Rate (fps)",+ description="Frames per second for the animation",+ default=24,+ min=1,+ max=60+ ) # type: ignore++ resolution_percentage: bpy.props.IntProperty(+ name="Resolution %",+ description="Percentage of the scene's render resolution to use",+ default=50,+ min=10,+ max=100,+ subtype='PERCENTAGE'+ ) # type: ignore++ samples: bpy.props.IntProperty(+ name="Samples",+ description="Number of render samples per frame",+ default=32,+ min=1,+ max=4096+ ) # type: ignore++ engine: bpy.props.EnumProperty(+ name="Render Engine",+ description="Render engine to use",+ items=[+ ('BLENDER_WORKBENCH', "Workbench", "Use Workbench render engine"),+ ('BLENDER_EEVEE_NEXT', "Eevee", "Use Eevee render engine"),+ ('CYCLES', "Cycles", "Use Cycles render engine")+ ],+ default='CYCLES'+ ) # type: ignore++ _timer = None+ _rendering = False+ _cancelled = False # Added flag to track cancellation+ _handle_complete = None+ _handle_cancel = None+ _initial_settings = {}+ _temp_empty = None # Added for the pivot empty+ _output_path = "" # Internal variable to store the final GIF path+ _output_path_mp4 = "" # Internal variable to store the final MP4 path+ _temp_dir = "" # Temporary directory for frames+ _frame_paths = [] # List to store paths of rendered frames+ _original_camera_parent = None # Store original camera parent+ _original_camera_matrix = None # Store original camera matrix++ @classmethod+ def poll(cls, context):+ # Check if imageio is available+ try:+ import imageio+ # Optionally check for ffmpeg plugin if strict MP4 support is needed+ # This basic check is usually sufficient as imageio tries to find ffmpeg+ except ImportError:+ return False+ # Check for active object (Mesh or Empty) and active camera+ return context.active_object is not None and context.active_object.type in {'MESH', 'EMPTY'} and context.scene.camera is not None++ def invoke(self, context, event):+ # Check dependency again in invoke to provide feedback+ try:+ import imageio+ # Check if ffmpeg is likely available for MP4 export+ if not imageio.plugins.ffmpeg.is_available():+ self.report({'WARNING'}, "FFmpeg plugin for imageio not found. MP4 export might fail. Install 'imageio-ffmpeg'.")+ except ImportError:+ self.report({'ERROR'}, "Python module 'imageio' not found. Please install it (e.g., 'pip install imageio imageio-ffmpeg').")+ return {'CANCELLED'}+ except Exception as e:+ self.report({'WARNING'}, f"Could not check imageio ffmpeg availability: {e}. MP4 export might fail.")+++ # Check for active camera+ if not context.scene.camera:+ self.report({'ERROR'}, "No active camera found in the scene.")+ return {'CANCELLED'}++ # Determine output paths using get_dir_path+ try:+ revision_dir = get_dir_path(context, "revision")+ os.makedirs(revision_dir, exist_ok=True)+ self._output_path = os.path.join(revision_dir, "orbit.gif")+ self._output_path_mp4 = os.path.join(revision_dir, "orbit.mp4") # MP4 path+ except Exception as e:+ self.report({'ERROR'}, f"Could not determine output directory: {e}")+ return {'CANCELLED'}++ # Create temporary directory for frames+ try:+ self._temp_dir = tempfile.mkdtemp(prefix="blender_gif_")+ except Exception as e:+ self.report({'ERROR'}, f"Could not create temporary directory: {e}")+ self.cleanup(context) # Clean up if temp dir fails+ return {'CANCELLED'}++ return context.window_manager.invoke_props_dialog(self)++ def setup_animation(self, context):+ obj = context.active_object+ scene = context.scene+ active_camera = scene.camera # Use the scene's active camera++ if not active_camera: # Should be caught by poll/invoke, but double-check+ raise RuntimeError("No active camera found during setup.")++ # Store original camera state+ self._original_camera_parent = active_camera.parent+ self._original_camera_matrix = active_camera.matrix_world.copy()++ # Calculate Center (Center of Mass or Bounds)+ cursor_location = scene.cursor.location.copy()+ # Use object bounds center for better visual centering+ bpy.ops.object.select_all(action='DESELECT')+ context.view_layer.objects.active = obj+ obj.select_set(True)+ # Use geometry center for pivot, less prone to being skewed by outliers than bounds+ bpy.ops.object.origin_set(type='ORIGIN_CENTER_OF_MASS')+ center_location = obj.matrix_world.translation.copy()+ # Restore cursor location (origin setting might change cursor)+ scene.cursor.location = cursor_location++ # Create Temporary Empty at Center+ self._temp_empty = bpy.data.objects.new("OrbitPivot", None)+ self._temp_empty.location = center_location+ scene.collection.objects.link(self._temp_empty)+ # Update matrices after linking and setting location+ context.view_layer.update()++ # Calculate camera's local transform relative to the empty *before* parenting+ cam_original_world_matrix = self._original_camera_matrix.copy()+ empty_world_matrix_inv = self._temp_empty.matrix_world.inverted()+ cam_local_matrix = empty_world_matrix_inv @ cam_original_world_matrix++ # Parent Active Camera to Empty+ active_camera.parent = self._temp_empty+ # Set the camera's local transform (matrix_basis)+ active_camera.matrix_basis = cam_local_matrix++ # Set Up Animation Timing+ total_frames = int(self.duration * self.frame_rate)+ scene.frame_start = 1+ scene.frame_end = total_frames+ scene.render.fps = self.frame_rate++ # Animate Empty's Rotation+ self._temp_empty.rotation_euler = (0, 0, 0)+ self._temp_empty.keyframe_insert(data_path="rotation_euler", index=2, frame=1) # Keyframe Z rotation at frame 1++ self._temp_empty.rotation_euler = (0, 0, math.radians(360))+ # Keyframe Z rotation at end frame + 1 for full circle and correct interpolation+ self._temp_empty.keyframe_insert(data_path="rotation_euler", index=2, frame=total_frames + 1)++ # Set Interpolation to Linear for smooth rotation+ if self._temp_empty.animation_data and self._temp_empty.animation_data.action:+ for fcurve in self._temp_empty.animation_data.action.fcurves:+ if fcurve.data_path == "rotation_euler" and fcurve.array_index == 2: # Z rotation+ for kf_point in fcurve.keyframe_points:+ kf_point.interpolation = 'LINEAR'+ # Ensure extrapolation is also linear if needed (usually default)+ fcurve.extrapolation = 'LINEAR'+++ def execute(self, context):+ scene = context.scene+ render = scene.render+ cycles = scene.cycles # Get cycles settings++ # Store Initial Settings+ self._initial_settings = {+ 'frame_start': scene.frame_start,+ 'frame_end': scene.frame_end,+ 'fps': render.fps,+ 'camera': scene.camera, # Store the camera object itself+ 'filepath': render.filepath,+ 'file_format': render.image_settings.file_format,+ 'color_mode': render.image_settings.color_mode,+ 'resolution_percentage': render.resolution_percentage,+ 'use_overwrite': render.use_overwrite,+ 'use_placeholder': render.use_placeholder,+ 'samples': cycles.samples, # Store original samples+ 'engine': scene.render.engine, # Store original engine+ 'film_transparent': render.film_transparent, # Store original film transparency+ 'light': scene.display.shading.light, # Store original shading light+ 'color_type': scene.display.shading.color_type # Store original shading color type+ }++ scene.render.engine = self.engine # Use selected engine++ if scene.render.engine == 'BLENDER_WORKBENCH':+ context.scene.display.shading.light = 'STUDIO'+ context.scene.display.shading.color_type = 'SINGLE'++ # Apply Render Settings for PNG sequence+ render.filepath = os.path.join(self._temp_dir, "frame_") # Base path for frames+ render.image_settings.file_format = 'PNG' # Render as PNG sequence+ render.image_settings.color_mode = 'RGBA' # Use RGBA (needed for potential alpha, even if we make background opaque)+ render.resolution_percentage = self.resolution_percentage+ render.use_overwrite = True+ render.use_placeholder = False+ render.film_transparent = True+ cycles.samples = self.samples # Set samples for rendering++ # Setup Animation+ try:+ self.setup_animation(context)+ except Exception as e:+ # Clean up partially created objects if setup fails+ self.cleanup(context)+ self.report({'ERROR'}, f"Animation setup failed: {e}")+ # Print traceback for debugging+ import traceback+ traceback.print_exc()+ return {'CANCELLED'}++ # Start Rendering+ self._rendering = True+ self._cancelled = False # Reset cancellation flag+ self._frame_paths.clear() # Clear list for new render+ self._handle_complete = bpy.app.handlers.render_complete.append(self.render_complete_handler)+ self._handle_cancel = bpy.app.handlers.render_cancel.append(self.render_cancel_handler)+ # Add handler for each rendered frame to collect paths+ bpy.app.handlers.render_post.append(self.render_post_handler)+++ # Use timer to check render status without blocking UI completely+ self._timer = context.window_manager.event_timer_add(0.5, window=context.window)+ context.window_manager.modal_handler_add(self)++ # Start the render process+ bpy.ops.render.render('INVOKE_DEFAULT', animation=True)++ self.report({'INFO'}, f"Rendering frames to temporary directory...")+ return {'RUNNING_MODAL'}++ def modal(self, context, event):+ if event.type == 'TIMER':+ if not self._rendering:+ # Render finished or cancelled+ context.window_manager.event_timer_remove(self._timer)++ files_created = False+ # Check if frames exist AND it wasn't cancelled before trying to create files+ if self._frame_paths and not self._cancelled:+ files_created = self.create_output_files() # Call create_output_files++ # Perform cleanup regardless+ self.cleanup(context)++ # Check for error AFTER cleanup, using the cancellation flag+ if not files_created and not self._cancelled: # Use self._cancelled flag+ self.report({'ERROR'}, "No frames rendered or collected, or output file creation failed.")+ elif files_created: # Report success only if files were made+ self.report({'INFO'}, f"GIF saved to {self._output_path}, MP4 saved to {self._output_path_mp4}")+++ return {'FINISHED'}+ # Allow render window events to pass through+ return {'PASS_THROUGH'}+++ def cleanup(self, context):+ # Remove handlers first to prevent them running during cleanup+ if self._handle_complete in bpy.app.handlers.render_complete:+ bpy.app.handlers.render_complete.remove(self._handle_complete)+ if self._handle_cancel in bpy.app.handlers.render_cancel:+ bpy.app.handlers.render_cancel.remove(self._handle_cancel)+ if self.render_post_handler in bpy.app.handlers.render_post:+ bpy.app.handlers.render_post.remove(self.render_post_handler)+ self._handle_complete = None+ self._handle_cancel = None++ # Restore initial settings+ scene = context.scene+ render = scene.render+ cycles = scene.cycles # Get cycles settings+ original_camera = self._initial_settings.get('camera')++ # Restore camera parent and transform BEFORE restoring scene.camera setting+ if original_camera and original_camera.name in bpy.data.objects:+ try:+ # Check if it's still parented to the temp empty before unparenting+ if original_camera.parent == self._temp_empty:+ original_camera.parent = self._original_camera_parent+ # Restore world matrix after unparenting+ original_camera.matrix_world = self._original_camera_matrix+ else:+ # If parent changed unexpectedly, just restore matrix+ print("Warning: Camera parent changed during render, restoring world matrix only.")+ original_camera.matrix_world = self._original_camera_matrix+ # Clear potentially stale parent inverse matrix+ original_camera.matrix_parent_inverse.identity()++ except Exception as e:+ print(f"Warning: Could not restore camera state for '{original_camera.name}': {e}")++ # Restore other settings+ for key, value in self._initial_settings.items():+ if key == 'camera':+ # Restore the scene's active camera object if it exists+ if value and value.name in bpy.data.objects:+ scene.camera = value+ continue # Already handled transform/parent above+ try:+ # Handle nested properties correctly+ if key == 'file_format':+ setattr(render.image_settings, 'file_format', value)+ elif key == 'color_mode':+ setattr(render.image_settings, 'color_mode', value)+ elif key == 'samples': # Restore samples+ setattr(cycles, key, value)+ elif key == 'engine': # Restore engine+ setattr(render, key, value)+ elif key == 'film_transparent': # Restore film transparency+ setattr(render, key, value)+ elif hasattr(render, key):+ setattr(render, key, value)+ elif hasattr(scene, key):+ setattr(scene, key, value)+ except Exception as e:+ print(f"Warning: Could not restore setting '{key}': {e}")++ self._initial_settings = {} # Clear stored settings+ self._original_camera_parent = None+ self._original_camera_matrix = None++ # Remove temporary empty+ if self._temp_empty:+ # Remove animation data+ if self._temp_empty.animation_data and self._temp_empty.animation_data.action:+ action = self._temp_empty.animation_data.action+ # Check if action exists before removing+ if action and action.name in bpy.data.actions:+ bpy.data.actions.remove(action)+ # Unlink and remove object+ if self._temp_empty.name in context.scene.collection.objects:+ context.scene.collection.objects.unlink(self._temp_empty)+ if self._temp_empty.name in bpy.data.objects:+ bpy.data.objects.remove(self._temp_empty, do_unlink=True)+ self._temp_empty = None+++ self._rendering = False # Ensure rendering flag is reset+ self._cancelled = False # Reset cancellation flag++ # Clean up temporary directory if it exists+ if self._temp_dir and os.path.exists(self._temp_dir):+ try:+ shutil.rmtree(self._temp_dir)+ print(f"Removed temporary directory: {self._temp_dir}")+ except Exception as e:+ print(f"Warning: Could not remove temporary directory '{self._temp_dir}': {e}")+ self._temp_dir = ""+ self._frame_paths.clear() # Clear frame paths+++ def render_post_handler(self, scene, _):+ """Called after each frame is rendered."""+ if self._rendering and self._temp_dir: # Check temp_dir exists+ frame_num = scene.frame_current+ # Construct the expected filename based on Blender's padding+ filename = f"frame_{frame_num:04d}.png"+ filepath = os.path.join(self._temp_dir, filename)+ if os.path.exists(filepath):+ self._frame_paths.append(filepath)+ else:+ # Check if render path uses frame number suffix differently+ # Use scene.render.frame_path() which respects output settings+ alt_filepath = scene.render.frame_path(frame=frame_num)+ if os.path.exists(alt_filepath):+ self._frame_paths.append(alt_filepath)+ # print(f"Used alternative frame path: {alt_filepath}") # Less verbose+ else:+ print(f"Warning: Frame file not found after render: {filepath} or {alt_filepath}")+++ def render_complete_handler(self, scene, _):+ try:+ # Only respond if we're still in the rendering phase+ if not getattr(self, "_rendering", False):+ return++ print("Frame rendering complete.")+ # Signal that rendering is done so modal can wrap up+ self._rendering = False++ # Unregister this handler so it won't fire after operator finishes+ # Check if handler exists before removing+ if hasattr(self, 'render_complete_handler') and self.render_complete_handler in bpy.app.handlers.render_complete:+ try:+ bpy.app.handlers.render_complete.remove(self.render_complete_handler)+ except ValueError:+ pass # Ignore if already removed elsewhere+ except ReferenceError:+ # RNA is gone ignore+ pass+ except Exception as e:+ print(f"Error in render_complete_handler: {e}") # Log other potential errors+++ def render_cancel_handler(self, scene, _):+ if self._rendering: # Check if it was our render job that was cancelled+ self.report({'WARNING'}, "Render cancelled by user.")+ self._cancelled = True # Set the cancellation flag+ self._rendering = False # Signal modal loop to finish and cleanup+ # Unregister this handler+ if hasattr(self, 'render_cancel_handler') and self.render_cancel_handler in bpy.app.handlers.render_cancel:+ try:+ bpy.app.handlers.render_cancel.remove(self.render_cancel_handler)+ except ValueError:+ pass # Ignore if already removed+++ def create_output_files(self):+ """Creates the GIF and MP4 from the rendered frames using imageio. Returns True on success, False otherwise."""+ if not self._frame_paths:+ # Error is reported in modal loop if needed+ return False++ print(f"Assembling output files from {len(self._frame_paths)} frames...")+ gif_success = False+ mp4_success = False++ try:+ # Sort frames numerically just in case paths weren't added perfectly in order+ self._frame_paths.sort()++ images = []+ for filename in self._frame_paths:+ try:+ images.append(imageio.imread(filename))+ except FileNotFoundError:+ print(f"Warning: Frame file disappeared before processing: {filename}")+ continue # Skip missing frame++ if not images: # Check if any images were actually loaded+ self.report({'ERROR'}, "No valid frame images found to create output files.")+ return False++ # Calculate duration per frame for imageio (in seconds)+ frame_duration = 1.0 / self.frame_rate++ # --- Create GIF ---+ print(f"Creating GIF: {self._output_path}")+ try:+ # imageio v3+ uses 'duration' in seconds per frame+ imageio.mimsave(self._output_path, images, fps=self.frame_rate, loop=0, disposal=2) # loop=0 means infinite loop+ print(f"GIF saved successfully.")+ gif_success = True+ except TypeError:+ # Fallback if 'duration' is not accepted+ imageio.mimsave(self._output_path, images, duration=frame_duration, loop=0)+ print(f"GIF saved successfully (fallback duration).")+ gif_success = True+ except Exception as e:+ self.report({'ERROR'}, f"Failed to create GIF: {e}")+ # Print traceback for debugging GIF errors+ import traceback+ traceback.print_exc()++ # --- Create MP4 ---+ print(f"Creating MP4: {self._output_path_mp4}")+ try:+ imageio.mimsave(self._output_path_mp4, images, format='mp4', fps=self.frame_rate, quality=8)+ print(f"MP4 saved successfully.")+ mp4_success = True+ except ImportError:+ self.report({'ERROR'}, "Python module 'imageio' or its 'ffmpeg' plugin not found/configured correctly. Cannot create MP4.")+ except Exception as e:+ self.report({'ERROR'}, f"Failed to create MP4: {e}")+ # Print traceback for debugging MP4 errors+ import traceback+ traceback.print_exc()+++ return gif_success and mp4_success # Return True only if both succeed++ except ImportError:+ # This top-level catch handles if imageio itself wasn't imported initially+ self.report({'ERROR'}, "Python module 'imageio' not found. Cannot create output files.")+ return False+ except Exception as e:+ # Catch other potential errors during image loading or sorting+ self.report({'ERROR'}, f"Failed during output file creation process: {e}")+ import traceback+ traceback.print_exc()+ return False\ No newline at end of filediff --git a/stablegen/stablegen.py b/stablegen/stablegen.pynew file mode 100755index 0000000..871cb9e--- /dev/null+++ b/stablegen/stablegen.py@@ -0,0 +1,846 @@+""" This file contains the operators and panels for the StableGen addon """+# disable import-error because pylint doesn't recognize the blenders internal modules+import os+import bpy # pylint: disable=import-error+import mathutils # pylint: disable=import-error+import math # pylint: disable=import-error++# Stock presets+PRESETS = {+ "DEFAULT": {"description": "Default settings for general purpose generation", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.5, 0.5, 0.5)), "lora_type": "lightning_8step", "discard_factor": 90.0, "weight_exponent": 3.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "bake_texture": False, "bake_texture_size": 2048, "bake_unwrap_method": "none", "bake_unwrap_overlap_only": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.7, "sequential_factor_smooth": 0.15, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_ipadapter_regenerate": True, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.5, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}],},+ "MODEL IS IMPORTANT": {"description": "Same as default, but is more guided by the model", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.5, 0.5, 0.5)), "lora_type": "lightning_8step", "discard_factor": 90.0, "weight_exponent": 3.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "bake_texture": False, "bake_texture_size": 2048, "bake_unwrap_method": "none", "bake_unwrap_overlap_only": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.7, "sequential_factor_smooth": 0.15, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": False, "sequential_ipadapter_mode": "first", "sequential_ipadapter_regenerate": True, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.75, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}],},+ "CHARACTERS": {"description": "Optimized settings for character generation", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.5, 0.5, 0.5)), "lora_type": "lightning_8step", "discard_factor": 70.0, "weight_exponent": 3.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "bake_texture": False, "bake_texture_size": 2048, "bake_unwrap_method": "none", "bake_unwrap_overlap_only": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.7, "sequential_factor_smooth": 0.1, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "first", "sequential_ipadapter_regenerate": True, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 1, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.5, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}],},+ "CHARACTERS (ALTERNATIVE MASKING)": {"description": "Optimized for character generation. Uses alternative masking parameters to be more consistent between images, but may produce more artifacts. Try if \"Characters\" fails.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.5, 0.5, 0.5)), "lora_type": "lightning_8step", "discard_factor": 70.0, "weight_exponent": 3.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "bake_texture": False, "bake_texture_size": 2048, "bake_unwrap_method": "none", "bake_unwrap_overlap_only": True, "generation_method": "sequential", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.5, "sequential_factor_smooth": 0.3499999940395355, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "first", "sequential_ipadapter_regenerate": True, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 10, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.5, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}],},+ "QUICK DRAFT": {"description": "Optimized for speed", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 4, "cfg": 1.0, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.5, 0.5, 0.5)), "lora_type": "hyper_4step", "discard_factor": 70.0, "weight_exponent": 3.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "bake_texture": False, "bake_texture_size": 2048, "bake_unwrap_method": "none", "bake_unwrap_overlap_only": True, "generation_method": "grid", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "", "sequential_factor": 0.7, "sequential_factor_smooth": 0.1, "sequential_ipadapter": True, "sequential_ipadapter_mode": "first", "sequential_ipadapter_regenerate": True, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 2, "blur_mask_sigma": 1.0, "grow_mask_by": 2, "canny_threshold_low": 0, "canny_threshold_high": 80, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.5, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}],},+ "UV INPAINTING": {"description": "Recommended UV Inpainting setup. It is recommended to bake texutures manually before running the generation to fine-tune unwrapping and avoid lag when generating.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 10, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.5, 0.5, 0.5)), "lora_type": "lightning_8step", "discard_factor": 70.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "bake_texture": False, "bake_texture_size": 2048, "bake_unwrap_method": "none", "bake_unwrap_overlap_only": True, "generation_method": "uv_inpaint", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": True, "sequential_custom_camera_order": "3,0,1,2", "sequential_factor": 0.6000000238418579, "sequential_factor_smooth": 0.11000001430511475, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "first", "sequential_ipadapter_regenerate": True, "ipadapter_weight_type": "style", "ipadapter_strength": 1.0, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": True, "blur_mask": True, "blur_mask_radius": 3, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, },+ "ARCHITECTURE": {"description": "Prioritizes onlt the most straigh-on camera for each point. This means details generated on flat surfaces will not get blurred by getting generated differently from two or more viewpoints. Does not use visibility masking. Each picutre will get generated as new, consistency depends on IPAdapter + geometry.", "control_after_generate": "fixed", "model_architecture": "sdxl", "steps": 8, "cfg": 1.5, "sampler": "dpmpp_2s_ancestral", "scheduler": "sgm_uniform", "fallback_color": mathutils.Color((0.5, 0.5, 0.5)), "lora_type": "lightning_8step", "discard_factor": 80.0, "weight_exponent": 10.0, "clip_skip": 1, "auto_rescale": True, "overwrite_material": True, "bake_texture": False, "bake_texture_size": 2048, "bake_unwrap_method": "none", "bake_unwrap_overlap_only": True, "generation_method": "separate", "refine_images": False, "refine_steps": 8, "refine_sampler": "dpmpp_2s_ancestral", "refine_scheduler": "sgm_uniform", "denoise": 1.0, "refine_cfg": 1.5, "refine_prompt": "", "refine_upscale_method": "lanczos", "sequential_smooth": False, "sequential_custom_camera_order": "", "sequential_factor": 0.75, "sequential_factor_smooth": 0.15000000596046448, "sequential_factor_smooth_2": 1.0, "sequential_ipadapter": True, "sequential_ipadapter_mode": "first", "ipadapter_weight_type": "style", "ipadapter_strength": 0.800000011920929, "ipadapter_start": 0.0, "ipadapter_end": 1.0, "differential_diffusion": True, "differential_noise": False, "blur_mask": True, "blur_mask_radius": 3, "blur_mask_sigma": 1.0, "grow_mask_by": 3, "canny_threshold_low": 0, "canny_threshold_high": 80, "controlnet_units": [{'unit_type': 'depth', 'model_name': 'controlnet_depth_sdxl.safetensors', 'strength': 0.6000000238418579, 'start_percent': 0.0, 'end_percent': 1.0, 'is_union': False, 'use_union_type': True}],},+}++# Global list of all generation parameter names to check for a preset.+GEN_PARAMETERS = [+ "control_after_generate",+ "model_architecture",+ "steps",+ "cfg",+ "sampler",+ "scheduler",+ "fallback_color",+ "lora_type",+ "discard_factor",+ "weight_exponent",+ "clip_skip",+ "auto_rescale",+ "overwrite_material",+ "bake_texture",+ "bake_texture_size",+ "bake_unwrap_method",+ "bake_unwrap_overlap_only",+ "generation_method",+ "refine_images",+ "refine_steps",+ "refine_sampler",+ "refine_scheduler",+ "denoise",+ "refine_cfg",+ "refine_prompt",+ "refine_upscale_method",+ "sequential_smooth",+ "sequential_custom_camera_order",+ "sequential_factor",+ "sequential_factor_smooth",+ "sequential_factor_smooth_2",+ "sequential_ipadapter",+ "sequential_ipadapter_mode",+ "sequential_ipadapter_regenerate",+ "ipadapter_weight_type",+ "ipadapter_strength",+ "ipadapter_start",+ "ipadapter_end",+ "differential_diffusion",+ "differential_noise",+ "blur_mask",+ "blur_mask_radius",+ "blur_mask_sigma",+ "grow_mask_by",+ "canny_threshold_low",+ "canny_threshold_high",+]++def get_preset_items(self, context):+ items = []+ for key in PRESETS.keys():+ description = PRESETS[key].get("description", f"Preset {key}")+ items.append((key, key.title(), description))+ items.append(("CUSTOM", "Custom", "Custom configuration"))+ return items++def update_parameters(self, context):+ scene = context.scene+ # Build a dictionary of current parameter values+ current = {key: getattr(scene, key) for key in GEN_PARAMETERS if hasattr(scene, key)}++ # Compare current values with every stock preset's stored values+ for name, preset in PRESETS.items():+ # First check regular parameters+ if all(+ (lambda v1, v2: math.isclose(v1, v2, rel_tol=1e-7, abs_tol=0.0) if isinstance(v1, (int, float)) and isinstance(v2, (int, float)) else v1 == v2)+ (current.get(key), preset.get(key))+ for key in GEN_PARAMETERS if key in preset+ ):+ # Now check ControlNet units if present in the preset+ if "controlnet_units" in preset:+ # Get current controlnet units as comparable data+ current_units = []+ for unit in scene.controlnet_units:+ unit_data = {+ "unit_type": unit.unit_type,+ "model_name": unit.model_name,+ "strength": unit.strength,+ "start_percent": unit.start_percent,+ "end_percent": unit.end_percent,+ "is_union": unit.is_union,+ "use_union_type": unit.use_union_type+ }++ current_units.append(unit_data)++ # Compare unit count+ if len(current_units) != len(preset["controlnet_units"]):+ continue # Different number of units, not a match++ # Compare each unit's properties+ units_match = True+ for i, unit_data in enumerate(current_units):+ preset_unit = preset["controlnet_units"][i]+ for key, value in unit_data.items():+ if key not in preset_unit or preset_unit[key] != value:+ units_match = False+ break+ if not units_match:+ break++ if not units_match:+ continue # ControlNet units don't match, try next preset++ # All parameters and ControlNet units match+ if scene.stablegen_preset != name:+ scene.stablegen_preset = name+ scene.active_preset = name+ return++ # No match found, set to custom+ scene.active_preset = "CUSTOM"+ scene.stablegen_preset = "CUSTOM"++class StableGenPanel(bpy.types.Panel):+ """+ Creates the main UI panel for the StableGen addon.+ """+ bl_label = "StableGen"+ bl_idname = "OBJECT_PT_stablegen"+ bl_space_type = "VIEW_3D"+ bl_region_type = "UI"+ bl_category = "StableGen"+ bl_context = "objectmode"+ bl_ui_units_x = 600++ def draw_header(self, _):+ """+ Draws the header of the panel.+ :param _: Unused parameter.+ :return: None+ """+ self.layout.label(icon="WORLD_DATA")++ def draw(self, context):+ """+ Draws the panel with reorganized Advanced Parameters.+ :param context: Blender context.+ :return: None+ """+ layout = self.layout+ scene = context.scene # Get the scene for easier access++ # Detect the current width of the panel+ region = context.region+ width = region.width+ width_mode = 'narrow' if width < 420 else 'wide'++ # --- Action Buttons & Progress ---+ cam_tools_row = layout.row()+ cam_tools_row.operator("object.add_cameras", text="Add Cameras", icon="CAMERA_DATA")+ if width_mode == 'narrow':+ cam_tools_row = layout.row()+ cam_tools_row.operator("object.collect_camera_prompts", text="Collect Camera Prompts", icon="FILE_TEXT")++ if not hasattr(scene, 'generation_status'):+ scene.generation_status = 'idle'++ addon_prefs = context.preferences.addons[__package__].preferences+ config_error_message = None++ if not os.path.exists(addon_prefs.output_dir):+ config_error_message = "Output Path Invalid"+ elif not os.path.exists(addon_prefs.model_dir):+ config_error_message = "Model Path Invalid"+ elif not addon_prefs.server_address:+ config_error_message = "Server Address Missing"++ action_row = layout.row()+ action_row.scale_y = 2.0 # Scale the row vertically++ if config_error_message:+ action_row.operator("object.test_stable", text="Cannot generate: " + config_error_message, icon="X")+ action_row.enabled = False+ else:+ action_row.enabled = True++ if scene.generation_status == 'idle':+ action_row.operator("object.test_stable", text="Generate", icon="PLAY")+ elif scene.generation_status == 'running':+ action_row.operator("object.test_stable", text="Cancel Generation", icon="CANCEL")++ operator_instance = next((op for win in context.window_manager.windows for op in win.modal_operators if op.bl_idname == 'OBJECT_OT_test_stable'), None)+ if operator_instance:+ progress_col = layout.column()+ progress_text = f"{getattr(operator_instance, '_stage', 'Generating')} ({getattr(operator_instance, '_progress', 0):.0f}%)"+ progress_factor = getattr(operator_instance, '_progress', 0) / 100.0+ progress_col.progress(text=progress_text, factor=max(0.0, min(progress_factor, 1.0))) # Ensure factor is <= 1.0 (logic maintained)++ total_images = getattr(operator_instance, '_total_images', 0)+ if total_images > 1:+ current_image_idx = getattr(operator_instance, '_current_image', 0)+ current_image_decimal_progress = max(0.0, min(progress_factor, 1.0))++ # Ensure total_images is not zero to prevent division by zero+ overall_progress_factor = (current_image_idx + current_image_decimal_progress) / total_images if total_images > 0 else 0+ overall_progress_factor_clamped = max(0.0, min(overall_progress_factor, 1.0))++ progress_col.progress(+ text=f"Overall: Image {current_image_idx + 1}/{total_images}",+ factor=overall_progress_factor_clamped # Ensure factor is <= 1.0 (logic maintained)+ )+ else:+ action_row.operator("object.test_stable", text="Fix Issues to Generate", icon="ERROR")+ action_row.enabled = False++ bake_row = layout.row()+ bake_row.operator("object.bake_textures", text="Bake Textures", icon="RENDER_STILL")+ bake_operator = next((op for win in context.window_manager.windows for op in win.modal_operators if op.bl_idname == 'OBJECT_OT_bake_textures'), None)+ if bake_operator:+ bake_progress_col = layout.column()+ bake_stage = getattr(bake_operator, '_stage', 'Baking')+ bake_progress = getattr(bake_operator, '_progress', 0) / 100.0+ bake_progress_col.progress(text=bake_stage, factor=bake_progress if bake_progress <=1.0 else 1.0) # Ensure factor is <= 1.0++ total_objects = getattr(bake_operator, '_total_objects', 0)+ if total_objects > 1:+ current_object = getattr(bake_operator, '_current_object', 0)+ # Ensure total_objects is not zero+ overall_bake_progress = ((current_object + bake_progress) / total_objects) if total_objects > 0 else 0+ bake_progress_col.progress(+ text=f"{bake_stage}: Object {current_object + 1}/{total_objects}",+ factor=overall_bake_progress if overall_bake_progress <=1.0 else 1.0 # Ensure factor is <= 1.0+ )++ # --- Preset Management ---+ preset_box = layout.box()+ row = preset_box.row(align=True)+ row.prop(scene, "stablegen_preset", text="Preset")++ # Conditional button: Apply for stock presets, Save for custom preset+ if not hasattr(scene, 'active_preset'):+ scene.active_preset = scene.stablegen_preset++ if scene.stablegen_preset == "CUSTOM":+ row.operator("stablegen.save_preset", text="Save Preset", icon="PLUS")+ else:+ if scene.active_preset != scene.stablegen_preset:+ row.operator("stablegen.apply_preset", text="Apply Preset", icon="CHECKMARK")++ is_stock_preset = PRESETS.get(scene.stablegen_preset, {}).get("custom", False) is False+ if not is_stock_preset and scene.stablegen_preset != "DEFAULT":+ row.operator("stablegen.delete_preset", text="Delete", icon="TRASH")+++ # --- Main Parameters section ---+ if not hasattr(scene, 'show_generation_params'):+ scene.show_generation_params = True++ main_params_box = layout.box()+ main_params_col = main_params_box.column()+ main_params_col.prop(scene, "show_generation_params", text="Main Parameters", icon="TRIA_DOWN" if scene.show_generation_params else "TRIA_RIGHT", emboss=False)+ if scene.show_generation_params:+ params_container = main_params_col.box()+ # Split for prompt+ split = params_container.split(factor=0.25)+ split.label(text="Prompt:")+ split.prop(scene, "comfyui_prompt", text="")++ if scene.model_architecture == 'sdxl':+ # Split for model name+ split = params_container.split(factor=0.25)+ split.label(text="Model:")+ split.prop(scene, "model_name", text="")++ # Split for model architecture+ split = params_container.split(factor=0.5)+ split.label(text="Architecture:")+ split.prop(scene, "model_architecture", text="")++ # Split for generation method+ split = params_container.split(factor=0.5)+ split.label(text="Generation Mode:")+ split.prop(scene, "generation_method", text="")++ # --- Helper to create collapsible sections ---+ def draw_collapsible_section(parent_layout, toggle_prop_name, title, icon="NONE"):+ if not hasattr(scene, toggle_prop_name):+ setattr(bpy.types.Scene, toggle_prop_name, bpy.props.BoolProperty(name=title, default=False))++ box = parent_layout.box()+ col = box.column()+ is_expanded = getattr(scene, toggle_prop_name, False)+ col.prop(scene, toggle_prop_name, text=title, icon="TRIA_DOWN" if is_expanded else "TRIA_RIGHT", emboss=False)+ if is_expanded:+ return col.box() # Return a new box for content if expanded+ return None++ core_settings_props = [+ "show_core_settings", "show_scene_understanding_settings",+ "show_output_material_settings", "show_image_guidance_settings",+ "show_masking_inpainting_settings", "show_mode_specific_settings"+ ]+ for prop_name in core_settings_props:+ if not hasattr(scene, prop_name):+ setattr(bpy.types.Scene, prop_name, bpy.props.BoolProperty(name=prop_name.replace("_", " ").title(), default=False))++ # --- ADVANCED PARAMETERS ---+ advanced_params_box = layout.box()+ advanced_params_box = advanced_params_box.column()+ advanced_params_box.prop(scene, "show_advanced_params", text="Advanced Parameters", icon="TRIA_DOWN" if scene.show_advanced_params else "TRIA_RIGHT", emboss=False)+ if context.scene.show_advanced_params:++ # --- Core Generation Settings ---++ content_box = draw_collapsible_section(advanced_params_box, "show_core_settings", "Core Generation Settings", icon="SETTINGS")+ if content_box:+ row = content_box.row()+ row.prop(scene, "seed", text="Seed")+ if width_mode == 'narrow':+ row = content_box.row()+ row.prop(scene, "steps", text="Steps")+ if width_mode == 'narrow':+ row = content_box.row()+ row.prop(scene, "cfg", text="CFG")++ split = content_box.split(factor=0.5)+ split.label(text="Negative Prompt:")+ split.prop(scene, "comfyui_negative_prompt", text="")++ split = content_box.split(factor=0.5)+ split.label(text="Control After Generate:")+ split.prop(scene, "control_after_generate", text="")++ split = content_box.split(factor=0.5)+ split.label(text="Sampler:")+ split.prop(scene, "sampler", text="")++ split = content_box.split(factor=0.5)+ split.label(text="Scheduler:")+ split.prop(scene, "scheduler", text="")++ split = content_box.split(factor=0.5)+ split.label(text="LoRa Type:")+ split.prop(scene, "lora_type", text="")++ row = content_box.row()+ row.prop(scene, "clip_skip", text="Clip Skip")+++ # --- Image & Scene Understanding ---+ content_box = draw_collapsible_section(advanced_params_box, "show_scene_understanding_settings", "Viewpoint Blending Settings", icon="ZOOM_IN")+ if content_box:+ row = content_box.row(align=True)+ row.prop(scene, "use_camera_prompts", text="Use camera prompts", toggle=True, icon="CAMERA_DATA")++ row = content_box.row()+ row.prop(scene, "discard_factor", text="Discard-Over Angle")++ row = content_box.row()+ row.prop(scene, "weight_exponent", text="Weight Exponent")+++ # --- Output & Material Settings ---+ content_box = draw_collapsible_section(advanced_params_box, "show_output_material_settings", "Output & Material Settings", icon="MATERIAL")+ if content_box:+ split = content_box.split(factor=0.5)+ split.label(text="Fallback Color:")+ split.prop(scene, "fallback_color", text="")+++ row = content_box.row()+ row.prop(scene, "apply_bsdf", text="Apply BSDF", toggle=True, icon="SHADING_RENDERED")++ row = content_box.row()+ row.prop(scene, "auto_rescale", text="Auto Rescale Resolution", toggle=True, icon="ARROW_LEFTRIGHT")+ if width_mode == "narrow":+ row = content_box.row()+ row.prop(scene, "overwrite_material", text="Overwrite Material", toggle=True, icon="FILE_REFRESH")++ row = content_box.row()+ row.prop(scene, "bake_texture", text="Bake Textures While Generating", toggle=True, icon="RENDER_STILL")+ if scene.bake_texture:+ sub_box = content_box.box()+ row = sub_box.row()+ row.prop(scene, "bake_texture_size", text="Bake Texture Resolution")+ split = sub_box.split(factor=0.5)+ split.label(text="Bake Unwrap Method:")+ split.prop(scene, "bake_unwrap_method", text="")+ if scene.bake_unwrap_method != 'none':+ row = sub_box.row()+ row.prop(scene, "bake_unwrap_overlap_only", text="Unwrap only overlapping UVs", toggle=True, icon="UV_SYNC_SELECT")++ # --- Image Guidance (IPAdapter & ControlNet) ---+ content_box = draw_collapsible_section(advanced_params_box, "show_image_guidance_settings", "Image Guidance (IPAdapter & ControlNet)", icon="MODIFIER")+ if content_box:+ # IPAdapter Parameters+ if scene.model_architecture == 'sdxl':+ ipadapter_main_box = content_box.box() # Group IPAdapter settings together+ row = ipadapter_main_box.row()+ row.prop(scene, "use_ipadapter", text="Use IPAdapter (External image)", toggle=True, icon="MOD_MULTIRES")+ if scene.use_ipadapter:+ sub_ip_box = ipadapter_main_box.box()+ row = sub_ip_box.row()+ row.prop(scene, "ipadapter_image", text="Image")+ row = sub_ip_box.row()+ row.prop(scene, "ipadapter_strength", text="Strength")+ if width_mode == 'narrow':+ row = sub_ip_box.row()+ row.prop(scene, "ipadapter_start", text="Start")+ if width_mode == 'narrow':+ row = sub_ip_box.row()+ row.prop(scene, "ipadapter_end", text="End")+ split = sub_ip_box.split(factor=0.5)+ split.label(text="Weight Type:")+ split.prop(scene, "ipadapter_weight_type", text="")++ content_box.separator() # Separator between IPAdapter and ControlNet if both are shown+ # ControlNet Parameters+ ctrl_box_group = content_box.box() # Group ControlNet settings together+ row = ctrl_box_group.row()+ row.alignment = 'CENTER'+ row.label(text="ControlNet Units", icon="NODETREE")+ for i, unit in enumerate(scene.controlnet_units):+ sub_unit_box = ctrl_box_group.box() # Each unit gets its own box+ row = sub_unit_box.row()+ row.label(text=f"Unit: {unit.unit_type.replace('_', ' ').title()}", icon="DOT")+ row.alignment = 'LEFT'++ if width_mode == 'narrow':+ split = sub_unit_box.split(factor=0.35, align=True)+ else:+ split = sub_unit_box.split(factor=0.2, align=True)+ split.label(text="Model:")+ split.prop(unit, "model_name", text="")++ row = sub_unit_box.row()+ row.prop(unit, "strength", text="Strength")+ if width_mode == 'narrow':+ row = sub_unit_box.row()+ row.prop(unit, "start_percent", text="Start")+ if width_mode == 'narrow':+ row = sub_unit_box.row()+ row.prop(unit, "end_percent", text="End")++ if unit.unit_type == 'canny':+ row = sub_unit_box.row()+ row.prop(scene, "canny_threshold_low", text="Canny Low")+ if width_mode == 'narrow':+ row = sub_unit_box.row()+ row.prop(scene, "canny_threshold_high", text="Canny High")+ if hasattr(unit, 'is_union') and unit.is_union:+ row = sub_unit_box.row()+ row.prop(unit, "use_union_type", text="Set Union Type", toggle=True, icon="MOD_BOOLEAN")++ btn_row = ctrl_box_group.row(align=True)+ if width_mode == 'wide':+ btn_row.operator("stablegen.add_controlnet_unit", text="Add Unit", icon="ADD")+ btn_row.operator("stablegen.remove_controlnet_unit", text="Remove Unit", icon="REMOVE")+ else:+ ctrl_box_group.operator("stablegen.add_controlnet_unit", text="Add ControlNet Unit", icon="ADD")+ ctrl_box_group.operator("stablegen.remove_controlnet_unit", text="Remove Last ControlNet Unit", icon="REMOVE")+++ # --- Inpainting Options (Conditional) ---+ if scene.generation_method == 'uv_inpaint' or scene.generation_method == 'sequential':+ content_box = draw_collapsible_section(advanced_params_box, "show_masking_inpainting_settings", "Inpainting Options", icon="MOD_MASK")+ if content_box: # content_box is the container for these settings+ row = content_box.row()+ row.prop(scene, "differential_diffusion", text="Use Differential Diffusion", toggle=True, icon="SMOOTHCURVE")++ if scene.differential_diffusion:+ row = content_box.row()+ row.prop(scene, "differential_noise", text="Add Latent Noise Mask", toggle=True, icon="MOD_NOISE")++ if not (scene.differential_diffusion and not scene.differential_noise):+ row = content_box.row()+ row.prop(scene, "mask_blocky", text="Use Blocky Mask", icon="MOD_MASK")++ if width_mode == 'narrow':+ row = content_box.row()++ row.prop(scene, "blur_mask", text="Blur Mask", toggle=True, icon="SURFACE_NSPHERE")++ if scene.blur_mask:+ row = content_box.row()+ row.prop(scene, "blur_mask_radius", text="Blur Radius")+ if width_mode == 'narrow':+ row = content_box.row()+ row.prop(scene, "blur_mask_sigma", text="Blur Sigma")++ row = content_box.row() # Draw directly in content_box+ row.prop(scene, "grow_mask_by", text="Grow Mask By")+++ # --- Generation Mode Specifics ---+ mode_specific_outer_box = draw_collapsible_section(advanced_params_box, "show_mode_specific_settings", "Generation Mode Specifics", icon="OPTIONS")+ if mode_specific_outer_box: # This is the box where all mode-specific UIs should go++ # Grid Mode Parameters+ if scene.generation_method == 'grid':+ # Draw Grid parameters directly into mode_specific_outer_box+ row = mode_specific_outer_box.row()+ row.alignment = 'CENTER'+ row.label(text="Grid Mode Parameters", icon="MESH_GRID")++ row = mode_specific_outer_box.row()+ row.prop(scene, "refine_images", text="Refine Images", toggle=True, icon="SHADERFX")+ if scene.refine_images:+ split = mode_specific_outer_box.split(factor=0.5)+ split.label(text="Refine Sampler:")+ split.prop(scene, "refine_sampler", text="")++ split = mode_specific_outer_box.split(factor=0.5)+ split.label(text="Refine Scheduler:")+ split.prop(scene, "refine_scheduler", text="")++ row = mode_specific_outer_box.row()+ row.prop(scene, "denoise", text="Denoise")+ if width_mode == 'narrow':+ row = mode_specific_outer_box.row()+ row.prop(scene, "refine_cfg", text="Refine CFG")+ if width_mode == 'narrow':+ row = mode_specific_outer_box.row()+ row.prop(scene, "refine_steps", text="Refine Steps")++ row = mode_specific_outer_box.row()+ split = mode_specific_outer_box.split(factor=0.25)+ split.label(text="Refine Prompt:")+ split.prop(scene, "refine_prompt", text="")++ split = mode_specific_outer_box.split(factor=0.5)+ split.label(text="Refine Upscale:")+ split.prop(scene, "refine_upscale_method", text="")++ # Separate Mode Parameters+ elif scene.generation_method == 'separate' and scene.model_architecture == 'sdxl':+ row = mode_specific_outer_box.row()+ row.alignment = 'CENTER'+ row.label(text="Separate Mode Parameters", icon='FORCE_FORCE')++ row = mode_specific_outer_box.row()+ row.prop(scene, "sequential_ipadapter", text="Use IPAdapter for Separate Mode", toggle=True, icon="MODIFIER")+ if scene.sequential_ipadapter:+ sub_ip_box_separate = mode_specific_outer_box.box()++ split = sub_ip_box_separate.split(factor=0.5)+ split.label(text="Mode:")+ split.prop(scene, "sequential_ipadapter_mode", text="")++ split = sub_ip_box_separate.split(factor=0.5)+ split.label(text="Weight Type:")+ split.prop(scene, "ipadapter_weight_type", text="")++ row = sub_ip_box_separate.row()+ row.prop(scene, "ipadapter_strength", text="Strength")+ if width_mode == 'narrow':+ row = sub_ip_box_separate.row()+ row.prop(scene, "ipadapter_start", text="Start")+ if width_mode == 'narrow':+ row = sub_ip_box_separate.row()+ row.prop(scene, "ipadapter_end", text="End")++ if context.scene.sequential_ipadapter_mode == 'first':+ row = sub_ip_box_separate.row()+ row.prop(scene, "sequential_ipadapter_regenerate", text="Regenerate First Image", toggle=True, icon="FILE_REFRESH")+ if context.scene.sequential_ipadapter_regenerate:+ row = sub_ip_box_separate.row()+ row.prop(scene, "sequential_ipadapter_regenerate_wo_controlnet", text="Generate reference without ControlNet", toggle=True, icon="HIDE_OFF")++ # Refine Mode Parameters+ elif scene.generation_method == 'refine':+ row = mode_specific_outer_box.row()+ row.alignment = 'CENTER'+ row.label(text="Refine Mode Parameters", icon='SHADERFX')+ row = mode_specific_outer_box.row()+ row.prop(scene, "denoise", text="Denoise")+ row = mode_specific_outer_box.row()+ row.prop(scene, "refine_preserve", text="Preserve Original Textures", toggle=True, icon="TEXTURE")+ row = mode_specific_outer_box.row()+ row.prop(scene, "sequential_ipadapter", text="Use IPAdapter for Refine Mode", toggle=True, icon="MODIFIER")+ if scene.sequential_ipadapter:+ sub_ip_box_separate = mode_specific_outer_box.box()++ split = sub_ip_box_separate.split(factor=0.5)+ split.label(text="Mode:")+ split.prop(scene, "sequential_ipadapter_mode", text="")++ split = sub_ip_box_separate.split(factor=0.5)+ split.label(text="Weight Type:")+ split.prop(scene, "ipadapter_weight_type", text="")++ row = sub_ip_box_separate.row()+ row.prop(scene, "ipadapter_strength", text="Strength")+ if width_mode == 'narrow':+ row = sub_ip_box_separate.row()+ row.prop(scene, "ipadapter_start", text="Start")+ if width_mode == 'narrow':+ row = sub_ip_box_separate.row()+ row.prop(scene, "ipadapter_end", text="End")++ if context.scene.sequential_ipadapter_mode == 'first':+ row = sub_ip_box_separate.row()+ row.prop(scene, "sequential_ipadapter_regenerate", text="Regenerate First Image", toggle=True, icon="FILE_REFRESH")+ if context.scene.sequential_ipadapter_regenerate:+ row = sub_ip_box_separate.row()+ row.prop(scene, "sequential_ipadapter_regenerate_wo_controlnet", text="Generate reference without ControlNet", toggle=True, icon="HIDE_OFF")++ # UV Inpainting Parameters+ elif scene.generation_method == 'uv_inpaint':+ row = mode_specific_outer_box.row()+ row.alignment = 'CENTER'+ row.label(text="UV Inpainting Parameters", icon="IMAGE_PLANE")+ row = mode_specific_outer_box.row()+ row.prop(scene, "allow_modify_existing_textures", text="Allow Modifying Existing Textures", toggle=True, icon="TEXTURE")+ row = mode_specific_outer_box.row()+ row.prop(scene, "ask_object_prompts", text="Ask for Object Specific Prompts", toggle=True, icon="QUESTION")++ # Sequential Mode Parameters+ elif scene.generation_method == 'sequential':+ row = mode_specific_outer_box.row()+ row.alignment = 'CENTER'+ row.label(text="Sequential Mode Parameters", icon="SEQUENCE")++ split = mode_specific_outer_box.split(factor=0.5)+ split.label(text="Custom Camera Order:")+ split.prop(scene, "sequential_custom_camera_order", text="")++ if not (scene.differential_diffusion and not scene.differential_noise):+ row = mode_specific_outer_box.row()+ row.prop(scene, "sequential_smooth", text="Use Smooth Visibility Map", toggle=True, icon="MOD_SMOOTH")+ if width_mode == 'narrow':+ row = mode_specific_outer_box.row()+ row.prop(scene, "weight_exponent_mask", text="Exponent for Visibility Map", toggle=True, icon="IPO_EXPO")++ if not scene.sequential_smooth:+ row = mode_specific_outer_box.row()+ row.prop(scene, "sequential_factor", text="Visibility Threshold")+ else:+ row = mode_specific_outer_box.row()+ row.prop(scene, "sequential_factor_smooth", text="Smooth Visibility Black Point")+ if width_mode == 'narrow':+ row = mode_specific_outer_box.row()+ row.prop(scene, "sequential_factor_smooth_2", text="Smooth Visibility White Point")++ if scene.model_architecture == 'sdxl':+ row = mode_specific_outer_box.row()+ row.prop(scene, "sequential_ipadapter", text="Use IPAdapter for Sequential Mode", toggle=True, icon="MODIFIER")+ if scene.sequential_ipadapter:+ sub_ip_seq_box = mode_specific_outer_box.box()++ split = sub_ip_seq_box.split(factor=0.5)+ split.label(text="Mode:")+ split.prop(scene, "sequential_ipadapter_mode", text="")++ split = sub_ip_seq_box.split(factor=0.5)+ split.label(text="Weight Type:")+ split.prop(scene, "ipadapter_weight_type", text="")++ row = sub_ip_seq_box.row()+ row.prop(scene, "ipadapter_strength", text="Strength")+ if width_mode == 'narrow':+ row = sub_ip_seq_box.row()+ row.prop(scene, "ipadapter_start", text="Start")+ if width_mode == 'narrow':+ row = sub_ip_seq_box.row()+ row.prop(scene, "ipadapter_end", text="End")++ if context.scene.sequential_ipadapter_mode == 'first':+ row = sub_ip_seq_box.row()+ row.prop(scene, "sequential_ipadapter_regenerate", text="Regenerate First Image", toggle=True, icon="FILE_REFRESH")+ if context.scene.sequential_ipadapter_regenerate:+ row = sub_ip_seq_box.row()+ row.prop(scene, "sequential_ipadapter_regenerate_wo_controlnet", text="Generate reference without ControlNet", toggle=True, icon="HIDE_OFF")++ # --- Tools ---+ layout.separator()+ tools_box = layout.box()+ row = tools_box.row()+ row.alignment = 'CENTER'+ row.label(text="Tools", icon="TOOL_SETTINGS")++ row = tools_box.row()+ row.operator("object.switch_material", text="Switch Material", icon="MATERIAL_DATA")+ if width_mode == 'narrow':+ row = tools_box.row()+ row.operator("object.add_hdri", text="Add HDRI Light", icon="WORLD")++ row = tools_box.row()+ row.operator("object.apply_all_mesh_modifiers", text="Apply All Modifiers", icon="MODIFIER_DATA")+ if width_mode == 'narrow':+ row = tools_box.row()+ row.operator("object.curves_to_mesh", text="Convert Curves to Mesh", icon="CURVE_DATA")++ row = tools_box.row()+ row.operator("object.export_orbit_gif", text="Export Orbit GIF/MP4", icon="RENDER_ANIMATION")++ layout.separator()+++class ApplyPreset(bpy.types.Operator):+ """Apply selected preset values to parameters"""+ bl_idname = "stablegen.apply_preset"+ bl_label = "Apply Preset"+ bl_description = "Set multiple parameters based on selected preset for easier configuration"++ def execute(self, context):+ preset = context.scene.stablegen_preset+ if preset in PRESETS:+ values = PRESETS[preset]++ # Apply regular parameters+ for key, value in values.items():+ if key not in ["controlnet_units", "description"] and hasattr(context.scene, key):+ setattr(context.scene, key, value)++ # Apply ControlNet units if present in the preset+ if "controlnet_units" in values:+ # Clear existing units+ context.scene.controlnet_units.clear()++ # Add new units from preset+ controlnet_units = values["controlnet_units"]+ for unit_data in controlnet_units:+ new_unit = context.scene.controlnet_units.add()+ for key, value in unit_data.items():+ try:+ setattr(new_unit, key, value)+ except TypeError:+ self.report({'ERROR'}, f"Failed to set {key} for ControlNet unit: {value}. Model might be missing or might not be named correctly.")+ return {'CANCELLED'}++ self.report({'INFO'}, f"Preset '{preset}' applied.")+ else:+ self.report({'INFO'}, "Custom preset active.")+ return {'FINISHED'}++class SavePreset(bpy.types.Operator):+ """Save the current parameter values as a custom preset"""+ bl_idname = "stablegen.save_preset"+ bl_label = "Save Custom Preset"++ preset_name: bpy.props.StringProperty(+ name="Preset Name",+ default="MyPreset"+ ) # type: ignore++ preset_description: bpy.props.StringProperty(+ name="Description",+ description="A short description of what this preset is good for",+ default=""+ ) # type: ignore++ include_controlnet: bpy.props.BoolProperty(+ name="Include ControlNet Units",+ default=True,+ description="Include ControlNet units in the preset"+ ) # type: ignore++ def execute(self, context):+ scene = context.scene+ key = self.preset_name.upper()++ # Save all parameters defined in GEN_PARAMETERS+ PRESETS[key] = {param: getattr(scene, param) for param in GEN_PARAMETERS if hasattr(scene, param)}++ # Add description+ PRESETS[key]["description"] = self.preset_description++ # Add custom flag+ PRESETS[key]["custom"] = True++ if self.include_controlnet:+ # Save ControlNet units+ controlnet_units = []+ for unit in scene.controlnet_units:+ unit_data = {+ "unit_type": unit.unit_type,+ "model_name": unit.model_name,+ "strength": unit.strength,+ "start_percent": unit.start_percent,+ "end_percent": unit.end_percent,+ "is_union": unit.is_union,+ "use_union_type": unit.use_union_type+ }+ controlnet_units.append(unit_data)++ # Add controlnet units to the preset+ PRESETS[key]["controlnet_units"] = controlnet_units++ scene.stablegen_preset = key+ scene.active_preset = key+ self.report({'INFO'}, f"Preset '{self.preset_name}' saved.")++ # Print in the console for debugging+ print(f'"{key}": {{', end="")+ print(f'"description": "{self.preset_description}", ', end="")+ for param in GEN_PARAMETERS:+ if hasattr(scene, param):+ value = getattr(scene, param)+ if isinstance(value, str):+ print(f'"{param}": "{value}", ', end="")+ else:+ print(f'"{param}": {value}, ', end="")++ # Print controlnet units in a compact format if included+ if self.include_controlnet:+ print(f'"controlnet_units": {controlnet_units},', end="")+ print("},")+ return {'FINISHED'}++ def invoke(self, context, event):+ return context.window_manager.invoke_props_dialog(self)++ def draw(self, context):+ layout = self.layout+ layout.prop(self, "preset_name")+ layout.prop(self, "preset_description")+ layout.prop(self, "include_controlnet")++class DeletePreset(bpy.types.Operator):+ """Delete a custom preset"""+ bl_idname = "stablegen.delete_preset"+ bl_label = "Delete Preset"++ def execute(self, context):+ preset = context.scene.stablegen_preset+ if preset in PRESETS:+ del PRESETS[preset]+ context.scene.stablegen_preset = "CUSTOM"+ self.report({'INFO'}, f"Preset '{preset}' deleted.")+ update_parameters(self, context)+ return {'FINISHED'}+ else:+ self.report({'WARNING'}, "Preset not found.")+ return {'CANCELLED'}diff --git a/stablegen/util/helpers.py b/stablegen/util/helpers.pynew file mode 100755index 0000000..110baf6--- /dev/null+++ b/stablegen/util/helpers.py@@ -0,0 +1,1207 @@+import random++# Prompt for ComfyUI in API format (SDXL)+prompt_text = """+ {+ "5": {+ "inputs": {+ "image": "",+ "upload": "image"+ },+ "class_type": "LoadImage",+ "_meta": {+ "title": "Load Image"+ }+ },+ "6": {+ "inputs": {+ "ckpt_name": "sd_xl_base_1.0.safetensors"+ },+ "class_type": "CheckpointLoaderSimple",+ "_meta": {+ "title": "Load Checkpoint"+ }+ },+ "9": {+ "inputs": {+ "text": "a monkey",+ "clip": [+ "247",+ 0+ ]+ },+ "class_type": "CLIPTextEncode",+ "_meta": {+ "title": "CLIP Text Encode (Prompt)"+ }+ },+ "10": {+ "inputs": {+ "text": "",+ "clip": [+ "247",+ 0+ ]+ },+ "class_type": "CLIPTextEncode",+ "_meta": {+ "title": "CLIP Text Encode (Prompt)"+ }+ },+ "15": {+ "inputs": {+ "seed": 24,+ "steps": 8,+ "cfg": 1.5,+ "sampler_name": "dpmpp_2s_ancestral",+ "scheduler": "sgm_uniform",+ "denoise": 1,+ "model": [+ "26",+ 0+ ],+ "positive": [+ "14",+ 0+ ],+ "negative": [+ "14",+ 1+ ],+ "latent_image": [+ "16",+ 0+ ]+ },+ "class_type": "KSampler",+ "_meta": {+ "title": "KSampler"+ }+ },+ "16": {+ "inputs": {+ "width": 1024,+ "height": 1024,+ "batch_size": 1+ },+ "class_type": "EmptyLatentImage",+ "_meta": {+ "title": "Empty Latent Image"+ }+ },+ "19": {+ "inputs": {+ "samples": [+ "15",+ 0+ ],+ "vae": [+ "6",+ 2+ ]+ },+ "class_type": "VAEDecode",+ "_meta": {+ "title": "VAE Decode"+ }+ },+ "25": {+ "inputs": {+ "images": [+ "19",+ 0+ ]+ },+ "class_type": "SaveImageWebsocket",+ "_meta": {+ "title": "SaveImageWebsocket"+ }+ },+ "26": {+ "inputs": {+ "lora_name": "sdxl_lightning_8step_lora.safetensors",+ "strength_model": 1,+ "strength_clip": 1,+ "model": [+ "6",+ 0+ ],+ "clip": [+ "6",+ 1+ ]+ },+ "class_type": "LoraLoader",+ "_meta": {+ "title": "Load LoRA"+ }+ },+ "27": {+ "inputs": {+ "image": "",+ "upload": "image"+ },+ "class_type": "LoadImage",+ "_meta": {+ "title": "Load Image"+ }+ },+ "239": {+ "inputs": {+ "type": "depth",+ "control_net": [+ "201",+ 0+ ]+ },+ "class_type": "SetUnionControlNetType",+ "_meta": {+ "title": "SetUnionControlNetType"+ }+ },+ "247": {+ "inputs": {+ "stop_at_clip_layer": -1,+ "clip": [+ "26",+ 1+ ]+ },+ "class_type": "CLIPSetLastLayer",+ "_meta": {+ "title": "CLIP Set Last Layer"+ }+ },+ "235": {+ "inputs": {+ "preset": "PLUS (high strength)",+ "model": [+ "26",+ 0+ ]+ },+ "class_type": "IPAdapterUnifiedLoader",+ "_meta": {+ "title": "IPAdapter Unified Loader"+ }+ },+ "236": {+ "inputs": {+ "weight": 1,+ "start_at": 0,+ "end_at": 1,+ "weight_type": "standard",+ "model": [+ "235",+ 0+ ],+ "ipadapter": [+ "235",+ 1+ ],+ "image": ["237", 0]+ },+ "class_type": "IPAdapter",+ "_meta": {+ "title": "IPAdapter"+ }+ },+ "237": {+ "inputs": {+ "upload": "image"+ },+ "class_type": "LoadImage",+ "_meta": {+ "title": "Load Image"+ }+ }+ }+ """++prompt_text_img2img = """+{+ "1": {+ "inputs": {+ "image": "",+ "upload": "image"+ },+ "class_type": "LoadImage",+ "_meta": {+ "title": "Load Image"+ }+ },+ "12": {+ "inputs": {+ "image": "",+ "upload": "image"+ },+ "class_type": "LoadImage",+ "_meta": {+ "title": "Load Image"+ }+ },+ "23": {+ "inputs": {+ "upscale_method": "nearest-exact",+ "width": 1024,+ "height": 1024,+ "crop": "disabled",+ "image": [+ "1",+ 0+ ]+ },+ "class_type": "ImageScale",+ "_meta": {+ "title": "Upscale Image"+ }+ },+ "13": {+ "inputs": {+ "grow_mask_by": 0,+ "pixels": [+ "23",+ 0+ ],+ "vae": [+ "38",+ 2+ ],+ "mask": [+ "25",+ 0+ ]+ },+ "class_type": "VAEEncodeForInpaint",+ "_meta": {+ "title": "VAE Encode (for Inpainting)"+ }+ },+ "25": {+ "inputs": {+ "channel": "red",+ "image": [+ "12",+ 0+ ]+ },+ "class_type": "ImageToMask",+ "_meta": {+ "title": "Convert Image to Mask"+ }+ },+ "37": {+ "inputs": {+ "lora_name": "sdxl_lightning_8step_lora.safetensors",+ "strength_model": 1,+ "strength_clip": 1,+ "model": [+ "38",+ 0+ ],+ "clip": [+ "38",+ 1+ ]+ },+ "class_type": "LoraLoader",+ "_meta": {+ "title": "Load LoRA"+ }+ },+ "38": {+ "inputs": {+ "ckpt_name": "realvisxlV40_v40Bakedvae.safetensors"+ },+ "class_type": "CheckpointLoaderSimple",+ "_meta": {+ "title": "Load Checkpoint"+ }+ },+ "102": {+ "inputs": {+ "text": "tifa lockhart, cosplay, final fantasy",+ "clip": [+ "247",+ 0+ ]+ },+ "class_type": "CLIPTextEncode",+ "_meta": {+ "title": "CLIP Text Encode (Prompt)"+ }+ },+ "103": {+ "inputs": {+ "text": "",+ "clip": [+ "247",+ 0+ ]+ },+ "class_type": "CLIPTextEncode",+ "_meta": {+ "title": "CLIP Text Encode (Prompt)"+ }+ },+ "105": {+ "inputs": {+ "seed": 42,+ "steps": 8,+ "cfg": 1.48,+ "sampler_name": "dpmpp_sde",+ "scheduler": "sgm_uniform",+ "denoise": 0.5,+ "model": [+ "37",+ 0+ ],+ "positive": [+ "104",+ 0+ ],+ "negative": [+ "104",+ 1+ ],+ "latent_image": [+ "116",+ 0+ ]+ },+ "class_type": "KSampler",+ "_meta": {+ "title": "KSampler"+ }+ },+ "108": {+ "inputs": {+ "image": "",+ "upload": "image"+ },+ "class_type": "LoadImage",+ "_meta": {+ "title": "Load Image"+ }+ },+ "110": {+ "inputs": {+ "samples": [+ "105",+ 0+ ],+ "vae": [+ "38",+ 2+ ]+ },+ "class_type": "VAEDecode",+ "_meta": {+ "title": "VAE Decode"+ }+ },+ "111": {+ "inputs": {+ "images": [+ "110",+ 0+ ]+ },+ "class_type": "SaveImageWebsocket",+ "_meta": {+ "title": "SaveImageWebsocket"+ }+ },+ "116": {+ "inputs": {+ "pixels": [+ "118",+ 0+ ],+ "vae": [+ "38",+ 2+ ]+ },+ "class_type": "VAEEncode",+ "_meta": {+ "title": "VAE Encode"+ }+ },+ "117": {+ "inputs": {+ "image": "",+ "upload": "image"+ },+ "class_type": "LoadImage",+ "_meta": {+ "title": "Load Image"+ }+ },+ "118": {+ "inputs": {+ "upscale_method": "lanczos",+ "width": 713,+ "height": 1080,+ "crop": "disabled",+ "image": [+ "117",+ 0+ ]+ },+ "class_type": "ImageScale",+ "_meta": {+ "title": "Upscale Image"+ }+ },+ "224": {+ "inputs": {+ "expand": 0,+ "tapered_corners": true,+ "mask": [+ "25",+ 0+ ]+ },+ "class_type": "GrowMask",+ "_meta": {+ "title": "GrowMask"+ }+ },+ "225": {+ "inputs": {+ "mask": [+ "224",+ 0+ ]+ },+ "class_type": "MaskToImage",+ "_meta": {+ "title": "Convert Mask to Image"+ }+ },+ "226": {+ "inputs": {+ "blur_radius": 1,+ "sigma": 1,+ "image": [+ "225",+ 0+ ]+ },+ "class_type": "ImageBlur",+ "_meta": {+ "title": "Image Blur"+ }+ },+ "227": {+ "inputs": {+ "channel": "red",+ "image": [+ "226",+ 0+ ]+ },+ "class_type": "ImageToMask",+ "_meta": {+ "title": "Convert Image to Mask"+ }+ },+ "228": {+ "inputs": {+ "noise_mask": true,+ "positive": [+ "102",+ 0+ ],+ "negative": [+ "103",+ 0+ ],+ "vae": [+ "38",+ 2+ ],+ "pixels": [+ "1",+ 0+ ],+ "mask": [+ "227",+ 0+ ]+ },+ "class_type": "InpaintModelConditioning",+ "_meta": {+ "title": "InpaintModelConditioning"+ }+ },+ "229": {+ "inputs": {+ "model": [+ "37",+ 0+ ]+ },+ "class_type": "DifferentialDiffusion",+ "_meta": {+ "title": "Differential Diffusion"+ }+ },+ "235": {+ "inputs": {+ "preset": "PLUS (high strength)",+ "model": [+ "37",+ 0+ ]+ },+ "class_type": "IPAdapterUnifiedLoader",+ "_meta": {+ "title": "IPAdapter Unified Loader"+ }+ },+ "236": {+ "inputs": {+ "weight": 1,+ "start_at": 0,+ "end_at": 1,+ "weight_type": "standard",+ "model": [+ "235",+ 0+ ],+ "ipadapter": [+ "235",+ 1+ ],+ "image": ["1", 0]+ },+ "class_type": "IPAdapter",+ "_meta": {+ "title": "IPAdapter"+ }+ },+ "237": {+ "inputs": {+ "upload": "image"+ },+ "class_type": "LoadImage",+ "_meta": {+ "title": "Load Image"+ }+ },+ "239": {+ "inputs": {+ "type": "depth",+ "control_net": [+ "201",+ 0+ ]+ },+ "class_type": "SetUnionControlNetType",+ "_meta": {+ "title": "SetUnionControlNetType"+ }+ },+ "247": {+ "inputs": {+ "stop_at_clip_layer": -1,+ "clip": [+ "37",+ 1+ ]+ },+ "class_type": "CLIPSetLastLayer",+ "_meta": {+ "title": "CLIP Set Last Layer"+ }+ }+}+"""++prompt_text_flux = """ {+ "6": {+ "inputs": {+ "text": "a monkey",+ "clip": [+ "11",+ 0+ ]+ },+ "class_type": "CLIPTextEncode",+ "_meta": {+ "title": "CLIP Text Encode (Positive Prompt)"+ }+ },+ "8": {+ "inputs": {+ "samples": [+ "13",+ 0+ ],+ "vae": [+ "10",+ 0+ ]+ },+ "class_type": "VAEDecode",+ "_meta": {+ "title": "VAE Decode"+ }+ },+ "10": {+ "inputs": {+ "vae_name": "ae.sft"+ },+ "class_type": "VAELoader",+ "_meta": {+ "title": "Load VAE"+ }+ },+ "11": {+ "inputs": {+ "clip_name1": "t5xxl_fp8_e4m3fn.safetensors",+ "clip_name2": "clip_l.safetensors",+ "type": "flux",+ "device": "default"+ },+ "class_type": "DualCLIPLoader",+ "_meta": {+ "title": "DualCLIPLoader"+ }+ },+ "12": {+ "inputs": {+ "unet_name": "flux1-dev.sft",+ "weight_dtype": "default"+ },+ "class_type": "UNETLoader",+ "_meta": {+ "title": "Load Diffusion Model"+ }+ },+ "13": {+ "inputs": {+ "noise": [+ "25",+ 0+ ],+ "guider": [+ "22",+ 0+ ],+ "sampler": [+ "16",+ 0+ ],+ "sigmas": [+ "17",+ 0+ ],+ "latent_image": [+ "30",+ 0+ ]+ },+ "class_type": "SamplerCustomAdvanced",+ "_meta": {+ "title": "SamplerCustomAdvanced"+ }+ },+ "16": {+ "inputs": {+ "sampler_name": "euler"+ },+ "class_type": "KSamplerSelect",+ "_meta": {+ "title": "KSamplerSelect"+ }+ },+ "17": {+ "inputs": {+ "scheduler": "simple",+ "steps": 21,+ "denoise": 1,+ "model": [+ "12",+ 0+ ]+ },+ "class_type": "BasicScheduler",+ "_meta": {+ "title": "BasicScheduler"+ }+ },+ "22": {+ "inputs": {+ "model": [+ "12",+ 0+ ],+ "conditioning": [+ "26",+ 0+ ]+ },+ "class_type": "BasicGuider",+ "_meta": {+ "title": "BasicGuider"+ }+ },+ "25": {+ "inputs": {+ "noise_seed": 42+ },+ "class_type": "RandomNoise",+ "_meta": {+ "title": "RandomNoise"+ }+ },+ "26": {+ "inputs": {+ "guidance": 40,+ "conditioning": [+ "6",+ 0+ ]+ },+ "class_type": "FluxGuidance",+ "_meta": {+ "title": "FluxGuidance"+ }+ },+ "30": {+ "inputs": {+ "width": 1024,+ "height": 1024,+ "batch_size": 1+ },+ "class_type": "EmptyLatentImage",+ "_meta": {+ "title": "Empty Latent Image"+ }+ },+ "32": {+ "inputs": {+ "images": [+ "8",+ 0+ ]+ },+ "class_type": "SaveImageWebsocket",+ "_meta": {+ "title": "SaveImageWebsocket"+ }+ },+ "239": {+ "inputs": {+ "type": "",+ "control_net": [+ "201",+ 0+ ]+ },+ "class_type": "SetUnionControlNetType",+ "_meta": {+ "title": "SetUnionControlNetType"+ }+ }+}+"""++prompt_text_img2img_flux = """ {+ "1": {+ "inputs": {+ "image": "",+ "upload": "image"+ },+ "class_type": "LoadImage",+ "_meta": {+ "title": "Load Image"+ }+ },+ "6": {+ "inputs": {+ "text": "a monkey",+ "clip": [+ "11",+ 0+ ]+ },+ "class_type": "CLIPTextEncode",+ "_meta": {+ "title": "CLIP Text Encode (Positive Prompt)"+ }+ },+ "8": {+ "inputs": {+ "samples": [+ "13",+ 0+ ],+ "vae": [+ "10",+ 0+ ]+ },+ "class_type": "VAEDecode",+ "_meta": {+ "title": "VAE Decode"+ }+ },+ "10": {+ "inputs": {+ "vae_name": "ae.sft"+ },+ "class_type": "VAELoader",+ "_meta": {+ "title": "Load VAE"+ }+ },+ "11": {+ "inputs": {+ "clip_name1": "t5xxl_fp8_e4m3fn.safetensors",+ "clip_name2": "clip_l.safetensors",+ "type": "flux",+ "device": "default"+ },+ "class_type": "DualCLIPLoader",+ "_meta": {+ "title": "DualCLIPLoader"+ }+ },+ "12": {+ "inputs": {+ "unet_name": "flux1-dev.sft",+ "weight_dtype": "default"+ },+ "class_type": "UNETLoader",+ "_meta": {+ "title": "Load Diffusion Model"+ }+ },+ "13": {+ "inputs": {+ "noise": [+ "25",+ 0+ ],+ "guider": [+ "22",+ 0+ ],+ "sampler": [+ "16",+ 0+ ],+ "sigmas": [+ "17",+ 0+ ],+ "latent_image": [+ "116",+ 0+ ]+ },+ "class_type": "SamplerCustomAdvanced",+ "_meta": {+ "title": "SamplerCustomAdvanced"+ }+ },+ "16": {+ "inputs": {+ "sampler_name": "euler"+ },+ "class_type": "KSamplerSelect",+ "_meta": {+ "title": "KSamplerSelect"+ }+ },+ "17": {+ "inputs": {+ "scheduler": "simple",+ "steps": 21,+ "denoise": 1,+ "model": [+ "12",+ 0+ ]+ },+ "class_type": "BasicScheduler",+ "_meta": {+ "title": "BasicScheduler"+ }+ },+ "22": {+ "inputs": {+ "model": [+ "12",+ 0+ ],+ "conditioning": [+ "26",+ 0+ ]+ },+ "class_type": "BasicGuider",+ "_meta": {+ "title": "BasicGuider"+ }+ },+ "25": {+ "inputs": {+ "noise_seed": 42+ },+ "class_type": "RandomNoise",+ "_meta": {+ "title": "RandomNoise"+ }+ },+ "26": {+ "inputs": {+ "guidance": 40,+ "conditioning": [+ "6",+ 0+ ]+ },+ "class_type": "FluxGuidance",+ "_meta": {+ "title": "FluxGuidance"+ }+ },+ "30": {+ "inputs": {+ "width": 1024,+ "height": 1024,+ "batch_size": 1+ },+ "class_type": "EmptyLatentImage",+ "_meta": {+ "title": "Empty Latent Image"+ }+ },+ "32": {+ "inputs": {+ "images": [+ "8",+ 0+ ]+ },+ "class_type": "SaveImageWebsocket",+ "_meta": {+ "title": "SaveImageWebsocket"+ }+ },+ "42": {+ "inputs": {+ "image": "",+ "upload": "image"+ },+ "class_type": "LoadImage",+ "_meta": {+ "title": "Load Image"+ }+ },+ "43": {+ "inputs": {+ "upscale_method": "nearest-exact",+ "width": 1024,+ "height": 1024,+ "crop": "disabled",+ "image": [+ "1",+ 0+ ]+ },+ "class_type": "ImageScale",+ "_meta": {+ "title": "Upscale Image"+ }+ },+ "44": {+ "inputs": {+ "grow_mask_by": 0,+ "pixels": [+ "43",+ 0+ ],+ "vae": [+ "10",+ 0+ ],+ "mask": [+ "45",+ 0+ ]+ },+ "class_type": "VAEEncodeForInpaint",+ "_meta": {+ "title": "VAE Encode (for Inpainting)"+ }+ },+ "45": {+ "inputs": {+ "channel": "red",+ "image": [+ "42",+ 0+ ]+ },+ "class_type": "ImageToMask",+ "_meta": {+ "title": "Convert Image to Mask"+ }+ },+ "50": {+ "inputs": {+ "model": [+ "12",+ 0+ ]+ },+ "class_type": "DifferentialDiffusion",+ "_meta": {+ "title": "Differential Diffusion"+ }+ },+ "51": {+ "inputs": {+ "noise_mask": true,+ "positive": [+ "6",+ 0+ ],+ "negative": [+ "6",+ 0+ ],+ "vae": [+ "10",+ 0+ ],+ "pixels": [+ "1",+ 0+ ],+ "mask": [+ "227",+ 0+ ]+ },+ "class_type": "InpaintModelConditioning",+ "_meta": {+ "title": "InpaintModelConditioning"+ }+ },+ "116": {+ "inputs": {+ "pixels": [+ "118",+ 0+ ],+ "vae": [+ "10",+ 0+ ]+ },+ "class_type": "VAEEncode",+ "_meta": {+ "title": "VAE Encode"+ }+ },+ "117": {+ "inputs": {+ "image": "",+ "upload": "image"+ },+ "class_type": "LoadImage",+ "_meta": {+ "title": "Load Image"+ }+ },+ "118": {+ "inputs": {+ "upscale_method": "lanczos",+ "width": 713,+ "height": 1080,+ "crop": "disabled",+ "image": [+ "117",+ 0+ ]+ },+ "class_type": "ImageScale",+ "_meta": {+ "title": "Upscale Image"+ }+ },+ "224": {+ "inputs": {+ "expand": 0,+ "tapered_corners": true,+ "mask": [+ "45",+ 0+ ]+ },+ "class_type": "GrowMask",+ "_meta": {+ "title": "GrowMask"+ }+ },+ "225": {+ "inputs": {+ "mask": [+ "224",+ 0+ ]+ },+ "class_type": "MaskToImage",+ "_meta": {+ "title": "Convert Mask to Image"+ }+ },+ "226": {+ "inputs": {+ "blur_radius": 1,+ "sigma": 1,+ "image": [+ "225",+ 0+ ]+ },+ "class_type": "ImageBlur",+ "_meta": {+ "title": "Image Blur"+ }+ },+ "227": {+ "inputs": {+ "channel": "red",+ "image": [+ "226",+ 0+ ]+ },+ "class_type": "ImageToMask",+ "_meta": {+ "title": "Convert Image to Mask"+ }+ },+ "239": {+ "inputs": {+ "type": "",+ "control_net": [+ "201",+ 0+ ]+ },+ "class_type": "SetUnionControlNetType",+ "_meta": {+ "title": "SetUnionControlNetType"+ }+ }+}+"""diff --git a/stablegen/util/install_testing.py b/stablegen/util/install_testing.pynew file mode 100644index 0000000..84dbe5e--- /dev/null+++ b/stablegen/util/install_testing.py@@ -0,0 +1,36 @@+"""Install requirements in Blenders interpreter if not already installed."""+import sys+import subprocess+import bpy+import site++def install():+ """+ Install pip and websocket-client in Blenders interpreter if not already installed.+ :return: None+ """+ python = sys.executable++ print('Installing websocket-client and websockets in Blender interpreter...')+ print('Python:', python)++ # Get directory for packages+ packages_dir = bpy.utils.user_resource('SCRIPTS', path='modules', create=True)+ if packages_dir not in sys.path:+ sys.path.append(packages_dir)+ site.addsitedir(packages_dir)++ try:+ import websocket #NOTE: websocket-client (https://github.com/websocket-client/websocket-client)+ import websockets+ import imageio+ import imageio_ffmpeg+ import cv2+ except ImportError or ModuleNotFoundError:+ subprocess.check_call([python, '-m', 'ensurepip'])+ subprocess.check_call([python, '-m', 'pip', 'install', '--upgrade', '--target', packages_dir, 'pip'])+ subprocess.check_call([python, '-m', 'pip', 'install', '--target', packages_dir, 'websocket-client'])+ subprocess.check_call([python, '-m', 'pip', 'install', '--target', packages_dir, 'websockets'])+ subprocess.check_call([python, '-m', 'pip', 'install', '--target', packages_dir, 'imageio'])+ subprocess.check_call([python, '-m', 'pip', 'install', '--target', packages_dir, 'imageio-ffmpeg'])+ subprocess.check_call([python, '-m', 'pip', 'install', '--target', packages_dir, 'opencv-python'])diff --git a/stablegen/utils.py b/stablegen/utils.pynew file mode 100644index 0000000..f1a9874--- /dev/null+++ b/stablegen/utils.py@@ -0,0 +1,389 @@+import bpy+import os+from datetime import datetime++class AddHDRI(bpy.types.Operator):+ """Add HDRI Global Illumination to the scene."""+ bl_idname = "object.add_hdri"+ bl_label = "Add HDRI Global Illumination"+ bl_options = {'REGISTER', 'UNDO'}++ hdri_path: bpy.props.StringProperty(+ name="HDRI Path",+ description="Path to the HDRI image",+ default="",+ subtype='FILE_PATH'+ ) # type: ignore++ def execute(self, context):+ world = context.scene.world+ if not world:+ world = bpy.data.worlds.new("World")+ context.scene.world = world+ world.use_nodes = True+ tree = world.node_tree+ nodes = tree.nodes+ links = tree.links++ # Clear existing nodes+ nodes.clear()++ # Create Environment Texture node+ env_node = nodes.new("ShaderNodeTexEnvironment")+ env_node.name = "Environment Texture"+ env_node.location = (-300, 200)+ try:+ env_node.image = bpy.data.images.load(self.hdri_path)+ except Exception as e:+ self.report({'ERROR'}, f"Failed to load HDRI: {e}")+ return {'CANCELLED'}++ # Create Light Path node to separate background from lighting+ light_path = nodes.new('ShaderNodeLightPath')+ light_path.location = (-300, -100)++ # Create Mix Shader node to mix background color with HDRI lighting+ mix_shader = nodes.new('ShaderNodeMixShader')+ mix_shader.location = (200, 0)++ # Create Background nodes - one for HDRI lighting and one for a solid background+ bg_hdri = nodes.new("ShaderNodeBackground")+ bg_hdri.name = "HDRI Background"+ bg_hdri.location = (0, 100)++ bg_solid = nodes.new("ShaderNodeBackground")+ bg_solid.name = "Solid Background"+ bg_solid.location = (0, -100)+ bg_solid.inputs['Color'].default_value = (0.05, 0.05, 0.05, 1) # Default gray++ # Create Output node+ output_node = nodes.new("ShaderNodeOutputWorld")+ output_node.location = (400, 0)++ # Connect nodes+ links.new(env_node.outputs['Color'], bg_hdri.inputs['Color'])+ links.new(light_path.outputs['Is Camera Ray'], mix_shader.inputs['Fac'])+ links.new(bg_hdri.outputs['Background'], mix_shader.inputs[1])+ links.new(bg_solid.outputs['Background'], mix_shader.inputs[2])+ links.new(mix_shader.outputs['Shader'], output_node.inputs['Surface'])++ self.report({'INFO'}, "HDRI lighting added (background hidden).")+ return {'FINISHED'}++ def invoke(self, context, event):+ wm = context.window_manager+ return wm.invoke_props_dialog(self)++class ApplyModifiers(bpy.types.Operator):+ """Applies every modifier on every mesh in the scene and converts all instanced geometry into real meshes.++ Some modifiers (and instanced geometry) can interfere with automated texture generation+ or baking workflows. Running this operator ensures that:++ - All modifier stacks on every mesh object are applied in turn.+ - Any instanced or duplicated geometry (particle instances, dupliverts, collection instances,+ geometry‑nodes instances, etc.) is converted into real, editable mesh data.++ Use this as a preprocessing step to guarantee clean, final meshes before generating or baking textures."""+ bl_idname = "object.apply_all_mesh_modifiers"+ bl_label = "Apply All Modifiers on All Meshes"+ bl_options = {'REGISTER', 'UNDO'}++ @classmethod+ def poll(cls, context):+ # Operator can only run in Object Mode+ return context.mode == 'OBJECT'++ def execute(self, context):+ if context.mode != 'OBJECT':+ self.report({'WARNING'}, "Operator requires Object Mode")+ return {'CANCELLED'}++ scene = context.scene+ view_layer = context.view_layer++ # Store original state+ original_active_object = view_layer.objects.active+ original_selected_objects = context.selected_objects[:] # Make a copy++ applied_count = 0+ object_count = 0++ # Deselect all initially to avoid issues with operator context+ bpy.ops.object.select_all(action='DESELECT')++ # Iterate through all objects in the scene+ for obj in scene.objects:+ # Check if the object is a mesh and has modifiers+ if (obj.type == 'MESH') and obj.modifiers:+ object_count += 1+ self.report({'INFO'}, f"Processing object: {obj.name}")++ # Set the object as the active object in the view layer+ view_layer.objects.active = obj+ obj.select_set(True)++ # First, make any instances real on this object+ # This should correspond to the "Make Instances Real" button+ try:+ bpy.ops.object.duplicates_make_real(use_base_parent=True,+ use_hierarchy=True)+ self.report({'INFO'}, f" Made instances real on {obj.name}")+ except RuntimeError:+ # if there were no instances, or operator failed, ignore+ pass++ # Loop through modifiers and apply them+ num_modifiers = len(obj.modifiers)+ applied_modifiers_on_obj = 0++ # Use a while loop as applying modifies the collection+ while obj.modifiers:+ modifier = obj.modifiers[0] # Always target the first one+ modifier_name = modifier.name+ try:+ bpy.ops.object.modifier_apply(modifier=modifier_name)+ self.report({'INFO'}, f" Applied modifier '{modifier_name}' on {obj.name}")+ applied_modifiers_on_obj += 1+ applied_count += 1+ except RuntimeError as e:+ self.report({'ERROR'}, f"Failed to apply modifier '{modifier_name}' on {obj.name}: {e}")+ # If applying fails, break the loop for this object+ break++ # Deselect the object after processing+ obj.select_set(False)++ # Restore original selection and active object+ view_layer.objects.active = original_active_object+ for sel_obj in original_selected_objects:+ # Check if the originally selected object still exists+ if sel_obj.name in scene.objects:+ sel_obj.select_set(True)+ else:+ self.report({'WARNING'}, f"Originally selected object '{sel_obj.name}' no longer exists.")+++ self.report({'INFO'}, f"Finished applying {applied_count} modifiers on {object_count} mesh objects.")+ return {'FINISHED'}++class CurvesToMesh(bpy.types.Operator):+ """Convert all curve objects in the scene into meshes.++ - Mesh geometry is required for texturing and baking operations."""+ bl_idname = "object.curves_to_mesh"+ bl_label = "Convert Curves to Mesh"+ bl_options = {'REGISTER', 'UNDO'}++ def execute(self, context):+ # Select all objects+ bpy.ops.object.select_all(action='SELECT')+ for obj in context.scene.objects:+ if obj.type == 'CURVE':+ bpy.context.view_layer.objects.active = obj+ bpy.ops.object.convert(target='MESH')+ # Deselect all objects+ bpy.ops.object.select_all(action='DESELECT')+ self.report({'INFO'}, "All curves converted to meshes.")+ return {'FINISHED'}++def get_last_material_index(obj):+ """+ Get the index of the last material of the object.+ The index is hidden inside default value of (the only) subtract node.+ If there are no subtract nodes, return -1.+ :param obj: Blender object.+ :return: Index of the last material.+ """++ highest_index = -1++ if obj.data.materials:+ for mat in obj.data.materials:+ if mat.use_nodes:+ for node in obj.active_material.node_tree.nodes:+ if node.type == 'MATH' and node.operation == 'SUBTRACT':+ if node.inputs[0].default_value > highest_index:+ highest_index = node.inputs[0].default_value++ return int(highest_index)++def get_generation_dirs(context):+ """+ Gets the directory structure for the current generation session.+ Creates a dictionary with paths to all required subdirectories for output files.+ :param context: Blender context containing addon preferences and scene data.+ :return: Dictionary with paths to all subdirectories (revision, controlnet, generated, baked, inpaint).+ """+ base_dir = context.preferences.addons[__package__].preferences.output_dir+ scene_name = os.path.splitext(os.path.basename(bpy.data.filepath))[0]+ # Use scene name as fallback if the blend file hasn't been saved yet+ if not scene_name:+ scene_name = context.scene.name+ timestamp = context.scene.output_timestamp++ if not timestamp:+ # If no timestamp set, use current time+ timestamp = datetime.now().strftime("%Y-%m-%dT%H-%M-%S")+ context.scene.output_timestamp = timestamp++ # Define directory structure+ revision_dir = os.path.join(base_dir, scene_name, timestamp)++ return {+ "revision": revision_dir,+ "controlnet_root": os.path.join(revision_dir, "controlnet"),+ "controlnet": {+ "depth": os.path.join(revision_dir, "controlnet", "depth"),+ "canny": os.path.join(revision_dir, "controlnet", "canny"),+ "normal": os.path.join(revision_dir, "controlnet", "normal"),+ },+ "generated": os.path.join(revision_dir, "generated"),+ "generated_baked": os.path.join(revision_dir, "generated_baked"),+ "baked": os.path.join(revision_dir, "baked"),+ "inpaint": {+ "render": os.path.join(revision_dir, "inpaint", "render"),+ "visibility": os.path.join(revision_dir, "inpaint", "visibility"),+ },+ "inpaint_root": os.path.join(revision_dir, "inpaint"),+ "uv_inpaint": {+ "visibility": os.path.join(revision_dir, "uv_inpaint", "uv_visibility"),+ },+ "uv_inpaint_root": os.path.join(revision_dir, "uv_inpaint"),+ "misc" : os.path.join(revision_dir, "misc"),+ }++def ensure_dirs_exist(dirs_dict):+ """+ Ensure that all required directories exist.+ :param dirs_dict: Dictionary of directory paths.+ :return: None+ """++ # Create the main directories+ os.makedirs(dirs_dict["revision"], exist_ok=True)+ os.makedirs(dirs_dict["generated"], exist_ok=True)+ os.makedirs(dirs_dict["generated_baked"], exist_ok=True)+ os.makedirs(dirs_dict["baked"], exist_ok=True)++ # Create controlnet subdirectories+ for key, path in dirs_dict["controlnet"].items():+ os.makedirs(path, exist_ok=True)++ # Create inpaint subdirectories+ for key, path in dirs_dict["inpaint"].items():+ os.makedirs(path, exist_ok=True)++ # Create uv_inpaint subdirectories+ for key, path in dirs_dict["uv_inpaint"].items():+ os.makedirs(path, exist_ok=True)+ # Create misc directory+ os.makedirs(dirs_dict["misc"], exist_ok=True)++def get_file_path(context, file_type, subtype=None, filename=None, camera_id=None, object_name=None, material_id=None):+ """+ Generate the full file path for saving images based on the type of file and other parameters.+ :param context: Blender context+ :param file_type: The type of file (controlnet, generated, baked, inpaint)+ :param subtype: Subtype for controlnet or inpaint (depth, canny, normal, render, etc.)+ :param filename: Base filename without extension+ :param camera_id: Optional camera ID for camera-specific files+ :param object_name: Optional object name for object-specific files+ :param material_id: Optional material ID for material-specific files+ :return: The full file path+ """+ dirs = get_generation_dirs(context)++ # Ensure the directories exist+ ensure_dirs_exist(dirs)++ if file_type == "controlnet" and subtype:+ base_dir = dirs["controlnet"][subtype]+ if not filename:+ if subtype == "depth":+ filename = f"depth_map{camera_id}0001" if camera_id is not None else "depth_map_grid"+ elif subtype == "canny":+ filename = f"canny{camera_id}0001" if camera_id is not None else "canny_grid"+ elif subtype == "normal":+ filename = f"normal_map{camera_id}0001" if camera_id is not None else "normal_grid"+ return os.path.join(base_dir, f"{filename}.png")++ elif file_type == "generated":+ base_dir = dirs["generated"]+ material_suffix = f"-{material_id}" if material_id is not None else ""+ return os.path.join(base_dir, f"generated_image{camera_id}{material_suffix}-0001.png" if camera_id is not None else "generated_image.png")++ elif file_type == "generated_baked":+ base_dir = dirs["generated_baked"]+ if object_name:+ material_suffix = f"{camera_id}-{material_id}" if material_id is not None else ""+ return os.path.join(base_dir, f"{object_name}_baked{material_suffix}.png")++ elif file_type == "baked":+ base_dir = dirs["baked"]+ if not filename:+ filename = f"{object_name}" if object_name else "baked_texture"+ return os.path.join(base_dir, f"{filename}.png")++ elif file_type == "inpaint" and subtype:+ base_dir = dirs["inpaint"][subtype]+ if subtype == "render":+ filename = f"render{camera_id}0001" if not filename else filename+ elif subtype == "visibility":+ filename = f"render{camera_id}_visibility0001" if not filename else filename+ return os.path.join(base_dir, f"{filename}.png")++ elif file_type == "uv_inpaint" and subtype:+ base_dir = dirs["uv_inpaint"][subtype]+ if subtype == "visibility":+ filename = f"{object_name}_baked_visibility" if not filename else filename+ return os.path.join(base_dir, f"{filename}.png")++ # Fallback to revision directory+ return os.path.join(dirs["revision"], f"{filename or 'file'}.png")++def get_dir_path(context, file_type):+ """+ Get the directory path for a specific file type.+ :param context: Blender context+ :param file_type: The type of file (controlnet, generated, baked, inpaint)+ :return: The directory path+ """+ dirs = get_generation_dirs(context)++ # Ensure the directories exist+ ensure_dirs_exist(dirs)++ if file_type == "revision":+ return dirs["revision"]+ elif file_type == "controlnet":+ return dirs["controlnet"]+ elif file_type == "generated":+ return dirs["generated"]+ elif file_type == "generated_baked":+ return dirs["generated_baked"]+ elif file_type == "baked":+ return dirs["baked"]+ elif file_type == "inpaint":+ return dirs["inpaint"]+ elif file_type == "uv_inpaint":+ return dirs["uv_inpaint"]+ else:+ return dirs["misc"]++ return None++def remove_empty_dirs(context, dirs_obj = None):+ """+ Remove empty directories from the generation structure.+ :param context: Blender context+ """+ if dirs_obj is None:+ dirs_obj = get_generation_dirs(context)++ for key, value in dirs_obj.items():+ if isinstance(value, dict):+ remove_empty_dirs(context, dirs_obj=value)+ else:+ if os.path.exists(value) and not os.listdir(value):+ os.rmdir(value)