Major Comment and codebase cleanup
This commit is contained in:
@@ -20,7 +20,7 @@ import json
|
||||
from pathlib import Path
|
||||
import time
|
||||
import base64 # Although not directly used here, keep for consistency if reusing more code later
|
||||
import sys # <<< ADDED IMPORT
|
||||
import sys
|
||||
|
||||
# --- USER CONFIGURATION ---
|
||||
|
||||
@@ -133,9 +133,7 @@ def reconstruct_image_path_with_fallback(asset_dir_path, asset_name, map_type, r
|
||||
)
|
||||
primary_path = asset_dir_path / filename
|
||||
if primary_path.is_file():
|
||||
# print(f" Found primary path: {str(primary_path)}") # Verbose
|
||||
return str(primary_path)
|
||||
# else: print(f" Primary path not found: {str(primary_path)}") # Verbose
|
||||
except KeyError as e:
|
||||
print(f" !!! ERROR: Missing key '{e}' in IMAGE_FILENAME_PATTERN. Cannot reconstruct path.")
|
||||
return None # Cannot proceed without valid pattern
|
||||
@@ -144,7 +142,6 @@ def reconstruct_image_path_with_fallback(asset_dir_path, asset_name, map_type, r
|
||||
# Continue to fallback
|
||||
|
||||
# 2. Try fallback extensions
|
||||
# print(f" Trying fallback extensions for {map_type}/{resolution}...") # Verbose
|
||||
for ext in FALLBACK_IMAGE_EXTENSIONS:
|
||||
# Skip if we already tried this extension as primary (and it failed)
|
||||
if primary_format and ext.lower() == primary_format.lower():
|
||||
@@ -198,9 +195,7 @@ def get_stat_value(stats_dict, map_type_list, stat_key):
|
||||
if isinstance(map_stats, dict) and stat_key in map_stats:
|
||||
return map_stats[stat_key] # Return the value for the first match
|
||||
else:
|
||||
# print(f" Debug: Stats for '{map_type}' found but key '{stat_key}' or format is invalid.") # Optional debug
|
||||
pass # Continue checking other map types in the list
|
||||
# else: print(f" Debug: Map type '{map_type}' not found in stats_dict.") # Optional debug
|
||||
|
||||
return None # Return None if no matching map type or stat key was found
|
||||
|
||||
@@ -214,11 +209,11 @@ def process_library_for_materials(context, asset_library_root_override=None, nod
|
||||
Scans the library, reads metadata, finds PBRSET node groups in the specified
|
||||
.blend file, and creates/updates materials linking to them.
|
||||
"""
|
||||
print("DEBUG: Script started.") # DEBUG LOG
|
||||
print("DEBUG: Script started.")
|
||||
start_time = time.time()
|
||||
print(f"\n--- Starting Material Creation from Node Groups ({time.strftime('%Y-%m-%d %H:%M:%S')}) ---")
|
||||
print(f" DEBUG: Received asset_library_root_override: {asset_library_root_override}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Received nodegroup_blend_file_path_override: {nodegroup_blend_file_path_override}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Received asset_library_root_override: {asset_library_root_override}")
|
||||
print(f" DEBUG: Received nodegroup_blend_file_path_override: {nodegroup_blend_file_path_override}")
|
||||
|
||||
|
||||
# --- Determine Asset Library Root ---
|
||||
@@ -229,7 +224,7 @@ def process_library_for_materials(context, asset_library_root_override=None, nod
|
||||
print("!!! ERROR: Processed asset library root not set in script and not provided via argument.")
|
||||
print("--- Script aborted. ---")
|
||||
return False
|
||||
print(f" DEBUG: Using final PROCESSED_ASSET_LIBRARY_ROOT: {PROCESSED_ASSET_LIBRARY_ROOT}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Using final PROCESSED_ASSET_LIBRARY_ROOT: {PROCESSED_ASSET_LIBRARY_ROOT}")
|
||||
|
||||
# --- Determine Nodegroup Blend File Path ---
|
||||
if nodegroup_blend_file_path_override:
|
||||
@@ -239,7 +234,7 @@ def process_library_for_materials(context, asset_library_root_override=None, nod
|
||||
print("!!! ERROR: Nodegroup blend file path not set in script and not provided via argument.")
|
||||
print("--- Script aborted. ---")
|
||||
return False
|
||||
print(f" DEBUG: Using final NODEGROUP_BLEND_FILE_PATH: {NODEGROUP_BLEND_FILE_PATH}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Using final NODEGROUP_BLEND_FILE_PATH: {NODEGROUP_BLEND_FILE_PATH}")
|
||||
|
||||
|
||||
# --- Pre-run Checks ---
|
||||
@@ -281,8 +276,8 @@ def process_library_for_materials(context, asset_library_root_override=None, nod
|
||||
else:
|
||||
placeholder_node_found_in_template = True
|
||||
print(f" Found Template Material: '{TEMPLATE_MATERIAL_NAME}' with placeholder '{PLACEHOLDER_NODE_LABEL}'")
|
||||
print(f" DEBUG: Template Material Found: {template_mat is not None}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Placeholder Node Found in Template: {placeholder_node_found_in_template}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Template Material Found: {template_mat is not None}")
|
||||
print(f" DEBUG: Placeholder Node Found in Template: {placeholder_node_found_in_template}")
|
||||
|
||||
|
||||
if not valid_setup:
|
||||
@@ -296,7 +291,6 @@ def process_library_for_materials(context, asset_library_root_override=None, nod
|
||||
assets_processed = 0
|
||||
assets_skipped = 0
|
||||
materials_created = 0
|
||||
# materials_updated = 0 # Not updating existing materials anymore
|
||||
node_groups_linked = 0
|
||||
previews_set = 0
|
||||
viewport_colors_set = 0
|
||||
@@ -322,7 +316,7 @@ def process_library_for_materials(context, asset_library_root_override=None, nod
|
||||
|
||||
metadata_files_found = len(metadata_paths)
|
||||
print(f"Found {metadata_files_found} metadata.json files.")
|
||||
print(f" DEBUG: Metadata paths found: {metadata_paths}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Metadata paths found: {metadata_paths}")
|
||||
|
||||
|
||||
if metadata_files_found == 0:
|
||||
@@ -331,11 +325,11 @@ def process_library_for_materials(context, asset_library_root_override=None, nod
|
||||
return True # No work needed is considered success
|
||||
|
||||
# --- Process Each Metadata File ---
|
||||
print(f" DEBUG: Starting metadata file loop. Found {len(metadata_paths)} files.") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Starting metadata file loop. Found {len(metadata_paths)} files.")
|
||||
for metadata_path in metadata_paths:
|
||||
asset_dir_path = metadata_path.parent
|
||||
print(f"\n--- Processing Metadata: {metadata_path.relative_to(root_path)} ---")
|
||||
print(f" DEBUG: Processing file: {metadata_path}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Processing file: {metadata_path}")
|
||||
try:
|
||||
with open(metadata_path, 'r', encoding='utf-8') as f:
|
||||
metadata = json.load(f)
|
||||
@@ -355,7 +349,7 @@ def process_library_for_materials(context, asset_library_root_override=None, nod
|
||||
print(f" !!! ERROR: Metadata file is missing 'asset_name'. Skipping.")
|
||||
errors_encountered += 1
|
||||
continue
|
||||
print(f" DEBUG: Valid metadata loaded for asset: {asset_name}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Valid metadata loaded for asset: {asset_name}")
|
||||
|
||||
|
||||
print(f" Asset Name: {asset_name}")
|
||||
@@ -363,8 +357,8 @@ def process_library_for_materials(context, asset_library_root_override=None, nod
|
||||
# --- Determine Target Names ---
|
||||
target_material_name = f"{MATERIAL_NAME_PREFIX}{asset_name}"
|
||||
target_pbrset_group_name = f"{PBRSET_GROUP_PREFIX}{asset_name}"
|
||||
print(f" DEBUG: Target Material Name: {target_material_name}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Target PBRSET Group Name: {target_pbrset_group_name}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Target Material Name: {target_material_name}")
|
||||
print(f" DEBUG: Target PBRSET Group Name: {target_pbrset_group_name}")
|
||||
|
||||
|
||||
# --- Check if Material Already Exists (Skip Logic) ---
|
||||
@@ -372,12 +366,12 @@ def process_library_for_materials(context, asset_library_root_override=None, nod
|
||||
print(f" Skipping asset '{asset_name}': Material '{target_material_name}' already exists.")
|
||||
assets_skipped += 1
|
||||
continue # Move to the next metadata file
|
||||
print(f" DEBUG: Material '{target_material_name}' does not exist. Proceeding with creation.") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Material '{target_material_name}' does not exist. Proceeding with creation.")
|
||||
|
||||
|
||||
# --- Create New Material ---
|
||||
print(f" Creating new material: '{target_material_name}'")
|
||||
print(f" DEBUG: Copying template material '{TEMPLATE_MATERIAL_NAME}'") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Copying template material '{TEMPLATE_MATERIAL_NAME}'")
|
||||
material = template_mat.copy()
|
||||
if not material:
|
||||
print(f" !!! ERROR: Failed to copy template material '{TEMPLATE_MATERIAL_NAME}'. Skipping asset '{asset_name}'.")
|
||||
@@ -385,7 +379,7 @@ def process_library_for_materials(context, asset_library_root_override=None, nod
|
||||
continue
|
||||
material.name = target_material_name
|
||||
materials_created += 1
|
||||
print(f" DEBUG: Material '{material.name}' created.") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Material '{material.name}' created.")
|
||||
|
||||
|
||||
# --- Find Placeholder Node ---
|
||||
@@ -400,13 +394,13 @@ def process_library_for_materials(context, asset_library_root_override=None, nod
|
||||
placeholder_node = None # Ensure it's None
|
||||
else:
|
||||
placeholder_node = placeholder_nodes[0] # Assume first is correct
|
||||
print(f" DEBUG: Found placeholder node '{placeholder_node.label}' in material '{material.name}'.") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Found placeholder node '{placeholder_node.label}' in material '{material.name}'.")
|
||||
|
||||
|
||||
# --- Find and Link PBRSET Node Group from Library ---
|
||||
linked_pbrset_group = None
|
||||
if placeholder_node and pbrset_blend_file_path: # Only proceed if placeholder exists and library file is known
|
||||
print(f" DEBUG: Placeholder node exists and PBRSET library file path is known: {pbrset_blend_file_path}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Placeholder node exists and PBRSET library file path is known: {pbrset_blend_file_path}")
|
||||
# Check if the group is already linked in the current file
|
||||
existing_linked_group = bpy.data.node_groups.get(target_pbrset_group_name)
|
||||
# Check if the existing group's library filepath matches the target blend file path
|
||||
@@ -440,7 +434,7 @@ def process_library_for_materials(context, asset_library_root_override=None, nod
|
||||
|
||||
# --- Link Linked Node Group to Placeholder ---
|
||||
if placeholder_node and linked_pbrset_group:
|
||||
print(f" DEBUG: Attempting to link PBRSET group '{linked_pbrset_group.name}' to placeholder '{placeholder_node.label}'.") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Attempting to link PBRSET group '{linked_pbrset_group.name}' to placeholder '{placeholder_node.label}'.")
|
||||
if placeholder_node.node_tree != linked_pbrset_group:
|
||||
try:
|
||||
placeholder_node.node_tree = linked_pbrset_group
|
||||
@@ -459,7 +453,7 @@ def process_library_for_materials(context, asset_library_root_override=None, nod
|
||||
|
||||
# --- Mark Material as Asset ---
|
||||
if not material.asset_data:
|
||||
print(f" DEBUG: Marking material '{material.name}' as asset.") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Marking material '{material.name}' as asset.")
|
||||
try:
|
||||
material.asset_mark()
|
||||
print(f" Marked material '{material.name}' as asset.")
|
||||
@@ -468,7 +462,7 @@ def process_library_for_materials(context, asset_library_root_override=None, nod
|
||||
|
||||
# --- Copy Asset Tags ---
|
||||
if material.asset_data and linked_pbrset_group and linked_pbrset_group.asset_data:
|
||||
print(f" DEBUG: Copying asset tags from PBRSET group to material.") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Copying asset tags from PBRSET group to material.")
|
||||
tags_copied_count = 0
|
||||
if supplier_name:
|
||||
if add_tag_if_new(material.asset_data, supplier_name): tags_copied_count += 1
|
||||
@@ -477,8 +471,6 @@ def process_library_for_materials(context, asset_library_root_override=None, nod
|
||||
# Copy other tags from PBRSET group
|
||||
for ng_tag in linked_pbrset_group.asset_data.tags:
|
||||
if add_tag_if_new(material.asset_data, ng_tag.name): tags_copied_count += 1
|
||||
# if tags_copied_count > 0: print(f" Copied {tags_copied_count} asset tags to material.") # Optional info
|
||||
# else: print(f" Warn: Cannot copy tags. Material asset_data: {material.asset_data is not None}, Linked Group: {linked_pbrset_group}, Group asset_data: {linked_pbrset_group.asset_data if linked_pbrset_group else None}") # Debug
|
||||
|
||||
|
||||
# --- Set Custom Preview ---
|
||||
@@ -525,12 +517,12 @@ def process_library_for_materials(context, asset_library_root_override=None, nod
|
||||
|
||||
# --- Set Viewport Properties from Stats ---
|
||||
if image_stats_1k and isinstance(image_stats_1k, dict):
|
||||
print(f" DEBUG: Applying viewport properties from stats.") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Applying viewport properties from stats.")
|
||||
# Viewport Color
|
||||
color_mean = get_stat_value(image_stats_1k, VIEWPORT_COLOR_MAP_TYPES, 'mean')
|
||||
if isinstance(color_mean, list) and len(color_mean) >= 3:
|
||||
color_rgba = (*color_mean[:3], 1.0)
|
||||
print(f" Debug: Raw color_mean from metadata: {color_mean[:3]}") # Added logging
|
||||
print(f" Debug: Raw color_mean from metadata: {color_mean[:3]}")
|
||||
if tuple(material.diffuse_color[:3]) != tuple(color_rgba[:3]):
|
||||
material.diffuse_color = color_rgba
|
||||
print(f" Set viewport color: {color_rgba[:3]}")
|
||||
@@ -594,14 +586,13 @@ def process_library_for_materials(context, asset_library_root_override=None, nod
|
||||
print(f"Assets Processed/Attempted: {assets_processed}")
|
||||
print(f"Assets Skipped (Already Exist): {assets_skipped}")
|
||||
print(f"Materials Created: {materials_created}")
|
||||
# print(f"Materials Updated: {materials_updated}") # Removed as we skip existing
|
||||
print(f"PBRSET Node Groups Linked: {node_groups_linked}")
|
||||
print(f"Material Previews Set: {previews_set}")
|
||||
print(f"Viewport Colors Set: {viewport_colors_set}")
|
||||
print(f"Viewport Roughness Set: {viewport_roughness_set}")
|
||||
print(f"Viewport Metallic Set: {viewport_metallic_set}")
|
||||
if pbrset_groups_missing_in_library > 0:
|
||||
print(f"!!! PBRSET Node Groups Missing in Library File: {pbrset_groups_missing_in_library} !!!") # Updated message
|
||||
print(f"!!! PBRSET Node Groups Missing in Library File: {pbrset_groups_missing_in_library} !!!")
|
||||
if library_link_errors > 0:
|
||||
print(f"!!! Library Link Errors: {library_link_errors} !!!")
|
||||
if placeholder_nodes_missing > 0:
|
||||
@@ -611,7 +602,7 @@ def process_library_for_materials(context, asset_library_root_override=None, nod
|
||||
print("---------------------------------------")
|
||||
|
||||
# --- Explicit Save ---
|
||||
print(f" DEBUG: Attempting explicit save for file: {bpy.data.filepath}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Attempting explicit save for file: {bpy.data.filepath}")
|
||||
try:
|
||||
bpy.ops.wm.save_as_mainfile(filepath=bpy.data.filepath)
|
||||
print("\n--- Explicitly saved the .blend file. ---")
|
||||
@@ -649,7 +640,6 @@ if __name__ == "__main__":
|
||||
print(f"Found nodegroup blend file path argument: {nodegroup_blend_file_arg}")
|
||||
else:
|
||||
print("Info: '--' found but not enough arguments after it for nodegroup blend file.")
|
||||
# else: print("Info: No '--' found in arguments.") # Optional debug
|
||||
except Exception as e:
|
||||
print(f"Error parsing command line arguments: {e}")
|
||||
# --- End Argument Parsing ---
|
||||
|
||||
@@ -28,7 +28,7 @@ from pathlib import Path
|
||||
import time
|
||||
import re # For parsing aspect ratio string
|
||||
import base64 # For encoding node group names
|
||||
import sys # <<< ADDED IMPORT
|
||||
import sys
|
||||
|
||||
# --- USER CONFIGURATION ---
|
||||
|
||||
@@ -36,7 +36,7 @@ import sys # <<< ADDED IMPORT
|
||||
# Example: r"G:\Assets\Processed"
|
||||
# IMPORTANT: This should point to the base directory containing supplier folders (e.g., Poliigon)
|
||||
# This will be overridden by command-line arguments if provided.
|
||||
PROCESSED_ASSET_LIBRARY_ROOT = None # Set to None initially
|
||||
PROCESSED_ASSET_LIBRARY_ROOT = None
|
||||
|
||||
# Names of the required node group templates in the Blender file
|
||||
PARENT_TEMPLATE_NAME = "Template_PBRSET"
|
||||
@@ -109,7 +109,6 @@ CATEGORIES_FOR_NODEGROUP_GENERATION = ["Surface", "Decal"]
|
||||
def encode_name_b64(name_str):
|
||||
"""Encodes a string using URL-safe Base64 for node group names."""
|
||||
try:
|
||||
# Ensure the input is a string
|
||||
name_str = str(name_str)
|
||||
return base64.urlsafe_b64encode(name_str.encode('utf-8')).decode('ascii')
|
||||
except Exception as e:
|
||||
@@ -174,7 +173,6 @@ def get_color_space(map_type):
|
||||
return PBR_COLOR_SPACE_MAP[short_type]
|
||||
|
||||
# Fallback if no specific rule found
|
||||
# print(f" Debug: Color space for '{map_type}' (candidates: '{map_type_upper}', '{base_type_candidate}') not found in PBR_COLOR_SPACE_MAP. Using default: {DEFAULT_COLOR_SPACE}")
|
||||
return DEFAULT_COLOR_SPACE
|
||||
|
||||
def calculate_aspect_correction_factor(image_width, image_height, aspect_string):
|
||||
@@ -188,13 +186,11 @@ def calculate_aspect_correction_factor(image_width, image_height, aspect_string)
|
||||
print(" Warn: Invalid image dimensions for aspect ratio calculation. Returning 1.0.")
|
||||
return 1.0
|
||||
|
||||
# Calculate the actual aspect ratio of the image file
|
||||
current_aspect_ratio = image_width / image_height
|
||||
|
||||
if not aspect_string or aspect_string.upper() == "EVEN":
|
||||
# If scaling was even, the correction factor is just the image's aspect ratio
|
||||
# to make UVs match the image proportions.
|
||||
# print(f" Aspect string is EVEN. Correction factor = current aspect ratio: {current_aspect_ratio:.4f}")
|
||||
return current_aspect_ratio
|
||||
|
||||
# Handle non-uniform scaling cases ("Xnnn", "Ynnn")
|
||||
@@ -216,7 +212,7 @@ def calculate_aspect_correction_factor(image_width, image_height, aspect_string)
|
||||
|
||||
# Apply the non-uniform correction formula based on original script logic
|
||||
scaling_factor_percent = amount / 100.0
|
||||
correction_factor = current_aspect_ratio # Default
|
||||
correction_factor = current_aspect_ratio
|
||||
|
||||
try:
|
||||
if axis == 'X':
|
||||
@@ -235,7 +231,6 @@ def calculate_aspect_correction_factor(image_width, image_height, aspect_string)
|
||||
print(f" Error calculating aspect correction factor: {e}. Returning current ratio {current_aspect_ratio:.4f}.")
|
||||
return current_aspect_ratio
|
||||
|
||||
# print(f" Calculated aspect correction factor: {correction_factor:.4f} (from {image_width}x{image_height}, Scaling='{aspect_string}')")
|
||||
return correction_factor
|
||||
|
||||
|
||||
@@ -256,16 +251,14 @@ def reconstruct_image_path_with_fallback(asset_dir_path, asset_name, map_type, r
|
||||
if primary_format:
|
||||
try:
|
||||
filename = IMAGE_FILENAME_PATTERN.format(
|
||||
assetname=asset_name, # Token is 'assetname'
|
||||
maptype=map_type, # Token is 'maptype'
|
||||
resolution=resolution, # Token is 'resolution'
|
||||
ext=primary_format.lower() # Token is 'ext'
|
||||
assetname=asset_name,
|
||||
maptype=map_type,
|
||||
resolution=resolution,
|
||||
ext=primary_format.lower()
|
||||
)
|
||||
primary_path = asset_dir_path / filename
|
||||
if primary_path.is_file():
|
||||
# print(f" Found primary path: {str(primary_path)}") # Verbose
|
||||
return str(primary_path)
|
||||
# else: print(f" Primary path not found: {str(primary_path)}") # Verbose
|
||||
except KeyError as e:
|
||||
print(f" !!! ERROR: Missing key '{e}' in IMAGE_FILENAME_PATTERN. Cannot reconstruct path.")
|
||||
return None # Cannot proceed without valid pattern
|
||||
@@ -274,17 +267,16 @@ def reconstruct_image_path_with_fallback(asset_dir_path, asset_name, map_type, r
|
||||
# Continue to fallback
|
||||
|
||||
# 2. Try fallback extensions
|
||||
# print(f" Trying fallback extensions for {map_type}/{resolution}...") # Verbose
|
||||
for ext in FALLBACK_IMAGE_EXTENSIONS:
|
||||
# Skip if we already tried this extension as primary (and it failed)
|
||||
if primary_format and ext.lower() == primary_format.lower():
|
||||
continue
|
||||
try:
|
||||
fallback_filename = IMAGE_FILENAME_PATTERN.format(
|
||||
assetname=asset_name, # Token is 'assetname'
|
||||
maptype=map_type, # Token is 'maptype'
|
||||
resolution=resolution, # Token is 'resolution'
|
||||
ext=ext.lower() # Token is 'ext'
|
||||
assetname=asset_name,
|
||||
maptype=map_type,
|
||||
resolution=resolution,
|
||||
ext=ext.lower()
|
||||
)
|
||||
fallback_path = asset_dir_path / fallback_filename
|
||||
if fallback_path.is_file():
|
||||
@@ -400,13 +392,13 @@ def update_manifest(manifest_data, asset_name, map_type=None, resolution=None):
|
||||
|
||||
# --- Core Logic ---
|
||||
|
||||
def process_library(context, asset_library_root_override=None): # Add override parameter
|
||||
def process_library(context, asset_library_root_override=None):
|
||||
global ENABLE_MANIFEST # Declare intent to modify global if needed
|
||||
global PROCESSED_ASSET_LIBRARY_ROOT # Allow modification of global
|
||||
"""Scans the library, reads metadata, creates/updates node groups."""
|
||||
start_time = time.time()
|
||||
print(f"\n--- Starting Node Group Processing ({time.strftime('%Y-%m-%d %H:%M:%S')}) ---")
|
||||
print(f" DEBUG: Received asset_library_root_override: {asset_library_root_override}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Received asset_library_root_override: {asset_library_root_override}")
|
||||
|
||||
# --- Determine Asset Library Root ---
|
||||
if asset_library_root_override:
|
||||
@@ -416,7 +408,7 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
print("!!! ERROR: Processed asset library root not set in script and not provided via argument.")
|
||||
print("--- Script aborted. ---")
|
||||
return False
|
||||
print(f" DEBUG: Using final PROCESSED_ASSET_LIBRARY_ROOT: {PROCESSED_ASSET_LIBRARY_ROOT}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Using final PROCESSED_ASSET_LIBRARY_ROOT: {PROCESSED_ASSET_LIBRARY_ROOT}")
|
||||
|
||||
# --- Pre-run Checks ---
|
||||
print("Performing pre-run checks...")
|
||||
@@ -429,7 +421,7 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
valid_setup = False
|
||||
else:
|
||||
print(f" Asset Library Root: '{root_path}'")
|
||||
print(f" DEBUG: Checking for templates: '{PARENT_TEMPLATE_NAME}', '{CHILD_TEMPLATE_NAME}'") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Checking for templates: '{PARENT_TEMPLATE_NAME}', '{CHILD_TEMPLATE_NAME}'")
|
||||
|
||||
# 2. Check Templates
|
||||
template_parent = bpy.data.node_groups.get(PARENT_TEMPLATE_NAME)
|
||||
@@ -442,8 +434,8 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
valid_setup = False
|
||||
if template_parent and template_child:
|
||||
print(f" Found Templates: '{PARENT_TEMPLATE_NAME}', '{CHILD_TEMPLATE_NAME}'")
|
||||
print(f" DEBUG: Template Parent Found: {template_parent is not None}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Template Child Found: {template_child is not None}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Template Parent Found: {template_parent is not None}")
|
||||
print(f" DEBUG: Template Child Found: {template_child is not None}")
|
||||
|
||||
# 3. Check Blend File Saved (if manifest enabled)
|
||||
if ENABLE_MANIFEST and not context.blend_data.filepath:
|
||||
@@ -495,7 +487,7 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
|
||||
metadata_files_found = len(metadata_paths)
|
||||
print(f"Found {metadata_files_found} metadata.json files.")
|
||||
print(f" DEBUG: Metadata paths found: {metadata_paths}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Metadata paths found: {metadata_paths}")
|
||||
|
||||
if metadata_files_found == 0:
|
||||
print("No metadata files found. Nothing to process.")
|
||||
@@ -504,9 +496,9 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
|
||||
# --- Process Each Metadata File ---
|
||||
for metadata_path in metadata_paths:
|
||||
asset_dir_path = metadata_path.parent # Get the directory containing the metadata file
|
||||
asset_dir_path = metadata_path.parent
|
||||
print(f"\n--- Processing Metadata: {metadata_path.relative_to(root_path)} ---")
|
||||
print(f" DEBUG: Processing file: {metadata_path}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Processing file: {metadata_path}")
|
||||
try:
|
||||
with open(metadata_path, 'r', encoding='utf-8') as f:
|
||||
metadata = json.load(f)
|
||||
@@ -515,8 +507,7 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
asset_name = metadata.get("asset_name")
|
||||
supplier_name = metadata.get("supplier_name")
|
||||
archetype = metadata.get("archetype")
|
||||
asset_category = metadata.get("category", "Unknown") # Read "category" key from metadata
|
||||
# Get map info from the correct keys
|
||||
asset_category = metadata.get("category", "Unknown")
|
||||
processed_resolutions = metadata.get("processed_map_resolutions", {}) # Default to empty dict
|
||||
merged_resolutions = metadata.get("merged_map_resolutions", {}) # Get merged maps too
|
||||
map_details = metadata.get("map_details", {}) # Default to empty dict
|
||||
@@ -536,7 +527,7 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
errors_encountered += 1
|
||||
continue
|
||||
# map_details check remains a warning as merged maps won't be in it
|
||||
print(f" DEBUG: Valid metadata loaded for asset: {asset_name}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Valid metadata loaded for asset: {asset_name}")
|
||||
|
||||
print(f" Asset Name: {asset_name}")
|
||||
|
||||
@@ -625,8 +616,8 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
|
||||
|
||||
# Conditional skip based on asset_category
|
||||
if asset_category not in CATEGORIES_FOR_NODEGROUP_GENERATION: # Check asset_category
|
||||
print(f" Skipping nodegroup content generation for asset '{asset_name}' (Category: '{asset_category}'). Tag added.") # Use asset_category in log
|
||||
if asset_category not in CATEGORIES_FOR_NODEGROUP_GENERATION:
|
||||
print(f" Skipping nodegroup content generation for asset '{asset_name}' (Category: '{asset_category}'). Tag added.")
|
||||
assets_processed += 1 # Still count as processed for summary, even if skipped
|
||||
continue # Skip the rest of the processing for this asset
|
||||
|
||||
@@ -637,7 +628,7 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
|
||||
if parent_group is None:
|
||||
print(f" Creating new parent group: '{target_parent_name}'")
|
||||
print(f" DEBUG: Copying parent template '{PARENT_TEMPLATE_NAME}'") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Copying parent template '{PARENT_TEMPLATE_NAME}'")
|
||||
parent_group = template_parent.copy()
|
||||
if not parent_group:
|
||||
print(f" !!! ERROR: Failed to copy parent template '{PARENT_TEMPLATE_NAME}'. Skipping asset '{asset_name}'.")
|
||||
@@ -648,7 +639,7 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
is_new_parent = True
|
||||
else:
|
||||
print(f" Updating existing parent group: '{target_parent_name}'")
|
||||
print(f" DEBUG: Found existing parent group.") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Found existing parent group.")
|
||||
parent_groups_updated += 1
|
||||
|
||||
# Ensure marked as asset
|
||||
@@ -666,10 +657,9 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
add_tag_if_new(parent_group.asset_data, supplier_name)
|
||||
if archetype:
|
||||
add_tag_if_new(parent_group.asset_data, archetype)
|
||||
if asset_category: # Use asset_category for tagging
|
||||
if asset_category:
|
||||
add_tag_if_new(parent_group.asset_data, asset_category)
|
||||
# Add other tags if needed
|
||||
# else: print(f" Warn: Cannot apply tags, asset_data not available for '{parent_group.name}'.") # Optional warning
|
||||
|
||||
|
||||
# Apply Aspect Ratio Correction
|
||||
@@ -689,7 +679,6 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
aspect_node.outputs[0].default_value = correction_factor
|
||||
print(f" Set '{ASPECT_RATIO_NODE_LABEL}' value to {correction_factor:.4f} (was {current_val:.4f})")
|
||||
aspect_ratio_set += 1
|
||||
# else: print(f" Warn: Aspect ratio node '{ASPECT_RATIO_NODE_LABEL}' not found in parent group.") # Optional
|
||||
|
||||
# Apply Highest Resolution Value
|
||||
hr_nodes = find_nodes_by_label(parent_group, HIGHEST_RESOLUTION_NODE_LABEL, 'ShaderNodeValue')
|
||||
@@ -700,7 +689,6 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
hr_node.outputs[0].default_value = highest_resolution_value
|
||||
print(f" Set '{HIGHEST_RESOLUTION_NODE_LABEL}' value to {highest_resolution_value} ({highest_resolution_str}) (was {current_hr_val:.1f})")
|
||||
highest_res_set += 1 # Count successful sets
|
||||
# else: print(f" Warn: Highest resolution node '{HIGHEST_RESOLUTION_NODE_LABEL}' not found in parent group.") # Optional
|
||||
|
||||
|
||||
# Apply Stats (using image_stats_1k)
|
||||
@@ -712,7 +700,7 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
stats_nodes = find_nodes_by_label(parent_group, stats_node_label, 'ShaderNodeCombineXYZ')
|
||||
if stats_nodes:
|
||||
stats_node = stats_nodes[0]
|
||||
stats = image_stats_1k[map_type_to_stat] # Get stats dict for this map type
|
||||
stats = image_stats_1k[map_type_to_stat]
|
||||
|
||||
if stats and isinstance(stats, dict):
|
||||
# Handle potential list format for RGB stats (use first value) or direct float
|
||||
@@ -743,10 +731,6 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
|
||||
if updated_stat:
|
||||
print(f" Set stats in '{stats_node_label}': Min={min_val:.4f}, Max={max_val:.4f}, Mean={mean_val:.4f}")
|
||||
# else: print(f" Info: No valid 'stats' dictionary found for map type '{map_type_to_stat}' in image_stats_1k.") # Optional
|
||||
# else: print(f" Warn: Stats node '{stats_node_label}' not found in parent group.") # Optional
|
||||
# else: print(f" Info: Map type '{map_type_to_stat}' not present in image_stats_1k for stats application.") # Optional
|
||||
# else: print(f" Warn: 'image_stats_1k' missing or invalid in metadata.") # Optional
|
||||
|
||||
# --- Set Asset Preview (only for new parent groups) ---
|
||||
# Use the reference image path found earlier if available
|
||||
@@ -768,14 +752,13 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
|
||||
# --- Child Group Handling ---
|
||||
# Iterate through the COMBINED map types
|
||||
print(f" DEBUG: Starting child group loop for asset '{asset_name}'. Map types: {list(all_map_resolutions.keys())}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Starting child group loop for asset '{asset_name}'. Map types: {list(all_map_resolutions.keys())}")
|
||||
for map_type, resolutions in all_map_resolutions.items():
|
||||
print(f" Processing Map Type: {map_type}")
|
||||
|
||||
# Determine if this is a merged map (not in map_details)
|
||||
is_merged_map = map_type not in map_details
|
||||
|
||||
# Get details for this map type if available
|
||||
current_map_details = map_details.get(map_type, {})
|
||||
# For merged maps, primary_format will be None
|
||||
output_format = current_map_details.get("output_format")
|
||||
@@ -792,7 +775,7 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
print(f" !!! WARNING: No placeholder node labeled '{map_type}' found in parent group '{parent_group.name}'. Skipping this map type.")
|
||||
continue
|
||||
holder_node = holder_nodes[0] # Assume first is correct
|
||||
print(f" DEBUG: Found placeholder node '{holder_node.label}' for map type '{map_type}'.") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Found placeholder node '{holder_node.label}' for map type '{map_type}'.")
|
||||
|
||||
# Determine child group name (LOGICAL and ENCODED)
|
||||
logical_child_name = f"{asset_name}_{map_type}"
|
||||
@@ -802,8 +785,7 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
is_new_child = False
|
||||
|
||||
if child_group is None:
|
||||
print(f" DEBUG: Child group '{target_child_name_b64}' not found. Creating new one.") # DEBUG LOG (Indented)
|
||||
# print(f" Creating new child group: '{target_child_name_b64}' (logical: '{logical_child_name}')") # Verbose
|
||||
print(f" DEBUG: Child group '{target_child_name_b64}' not found. Creating new one.")
|
||||
child_group = template_child.copy()
|
||||
if not child_group:
|
||||
print(f" !!! ERROR: Failed to copy child template '{CHILD_TEMPLATE_NAME}'. Skipping map type '{map_type}'.")
|
||||
@@ -813,8 +795,7 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
child_groups_created += 1
|
||||
is_new_child = True
|
||||
else:
|
||||
print(f" DEBUG: Found existing child group '{target_child_name_b64}'.") # DEBUG LOG (Indented)
|
||||
# print(f" Updating existing child group: '{target_child_name_b64}'") # Verbose
|
||||
print(f" DEBUG: Found existing child group '{target_child_name_b64}'.")
|
||||
child_groups_updated += 1
|
||||
|
||||
# Assign child group to placeholder if needed
|
||||
@@ -842,10 +823,6 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
if not link_exists:
|
||||
parent_group.links.new(source_socket, target_socket)
|
||||
print(f" Linked '{holder_node.label}' output to parent output socket '{map_type}'.")
|
||||
# else: # Optional warnings
|
||||
# if not source_socket: print(f" Warn: Could not find suitable output socket on placeholder '{holder_node.label}'.")
|
||||
# if not target_socket: print(f" Warn: Could not find input socket '{map_type}' on parent output node.")
|
||||
# else: print(f" Warn: Parent group '{parent_group.name}' has no Group Output node.")
|
||||
|
||||
except Exception as e_link:
|
||||
print(f" !!! ERROR linking sockets for '{map_type}': {e_link}")
|
||||
@@ -859,7 +836,6 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
# Defaulting to Color seems reasonable for most PBR outputs
|
||||
if item.socket_type != 'NodeSocketColor':
|
||||
item.socket_type = 'NodeSocketColor'
|
||||
# print(f" Set parent output socket '{map_type}' type to Color.") # Optional info
|
||||
except Exception as e_sock_type:
|
||||
print(f" Warn: Could not verify/set socket type for '{map_type}': {e_sock_type}")
|
||||
|
||||
@@ -872,10 +848,9 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
for resolution in resolutions:
|
||||
# --- Manifest Check (Map/Resolution Level) ---
|
||||
if ENABLE_MANIFEST and is_map_processed(manifest_data, asset_name, map_type, resolution):
|
||||
# print(f" Skipping {resolution} (Manifest)") # Verbose
|
||||
maps_skipped_manifest += 1
|
||||
continue
|
||||
print(f" DEBUG: Processing map '{map_type}' resolution '{resolution}'. Manifest skip check passed.") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Processing map '{map_type}' resolution '{resolution}'. Manifest skip check passed.")
|
||||
|
||||
print(f" Processing Resolution: {resolution}")
|
||||
|
||||
@@ -888,7 +863,7 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
resolution=resolution,
|
||||
primary_format=output_format
|
||||
)
|
||||
print(f" DEBUG: Reconstructed image path for {map_type}/{resolution}: {image_path_str}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Reconstructed image path for {map_type}/{resolution}: {image_path_str}")
|
||||
|
||||
if not image_path_str:
|
||||
# Error already printed by reconstruct function
|
||||
@@ -900,7 +875,7 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
if not image_nodes:
|
||||
print(f" !!! WARNING: No Image Texture node labeled '{resolution}' found in child group '{child_group.name}'. Cannot assign image.")
|
||||
continue # Skip this resolution if node not found
|
||||
print(f" DEBUG: Found {len(image_nodes)} image node(s) labeled '{resolution}' in child group '{child_group.name}'.") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Found {len(image_nodes)} image node(s) labeled '{resolution}' in child group '{child_group.name}'.")
|
||||
|
||||
# --- Load Image ---
|
||||
img = None
|
||||
@@ -954,7 +929,6 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
# --- Update Manifest (Map/Resolution Level) ---
|
||||
if update_manifest(manifest_data, asset_name, map_type, resolution):
|
||||
manifest_needs_saving = True
|
||||
# print(f" Marked {map_type}/{resolution} processed in manifest.") # Verbose
|
||||
maps_processed += 1
|
||||
|
||||
else:
|
||||
@@ -1008,13 +982,13 @@ def process_library(context, asset_library_root_override=None): # Add override p
|
||||
print(f"Individual Maps Processed: {maps_processed}")
|
||||
print(f"Asset Previews Set: {previews_set}")
|
||||
print(f"Highest Resolution Nodes Set: {highest_res_set}")
|
||||
print(f"Aspect Ratio Nodes Set: {aspect_ratio_set}") # Added counter
|
||||
print(f"Aspect Ratio Nodes Set: {aspect_ratio_set}")
|
||||
if errors_encountered > 0:
|
||||
print(f"!!! Errors Encountered: {errors_encountered} !!!")
|
||||
print("---------------------------")
|
||||
|
||||
# --- Explicit Save ---
|
||||
print(f" DEBUG: Attempting explicit save for file: {bpy.data.filepath}") # DEBUG LOG (Indented)
|
||||
print(f" DEBUG: Attempting explicit save for file: {bpy.data.filepath}")
|
||||
try:
|
||||
bpy.ops.wm.save_as_mainfile(filepath=bpy.data.filepath)
|
||||
print("\n--- Explicitly saved the .blend file. ---")
|
||||
@@ -1047,7 +1021,6 @@ if __name__ == "__main__":
|
||||
print(f"Found asset library root argument: {asset_root_arg}")
|
||||
else:
|
||||
print("Info: '--' found but no arguments after it.")
|
||||
# else: print("Info: No '--' found in arguments.") # Optional debug
|
||||
except Exception as e:
|
||||
print(f"Error parsing command line arguments: {e}")
|
||||
# --- End Argument Parsing ---
|
||||
|
||||
Reference in New Issue
Block a user