Created
October 13, 2024 20:10
-
-
Save andytriboletti/4053fbdae8612523d320cf27615cd9bf to your computer and use it in GitHub Desktop.
decimate.py for blender. used for infinigen project to reduce huge file size - adjust ratio and minimum as needed - I think I used different values - I forget
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import bpy | |
# 1. Purge unused data (materials, textures, meshes) | |
bpy.ops.outliner.orphans_purge(do_local_ids=True, do_linked_ids=True, do_recursive=True) | |
# 2. Apply Decimate Modifier to all selected objects with high-polygon meshes | |
def apply_decimate(threshold=10, ratio=0.0001): | |
# Loop through all mesh objects in the scene | |
for obj in bpy.data.objects: | |
if obj.type == 'MESH': | |
# Only decimate objects with more than the threshold number of vertices | |
if len(obj.data.vertices) > threshold: | |
decimate_mod = obj.modifiers.new(name="Decimate", type='DECIMATE') | |
decimate_mod.ratio = ratio | |
bpy.context.view_layer.objects.active = obj | |
bpy.ops.object.modifier_apply(modifier="Decimate") | |
# Apply decimation to objects with more than 10,000 vertices, reducing to 50% | |
apply_decimate(threshold=1000decimate, ratio=0.05) | |
# 3. Reduce texture size | |
def reduce_texture_size(max_resolution=1024): | |
for image in bpy.data.images: | |
if image.size[0] > max_resolution or image.size[1] > max_resolution: | |
image.scale(max_resolution, max_resolution) | |
print(f"Resized texture: {image.name} to {max_resolution}x{max_resolution}") | |
# Reduce texture size to 1024x1024 | |
reduce_texture_size(max_resolution=1024) | |
# 4. Remove duplicate materials by consolidating them | |
def remove_duplicate_materials(): | |
materials = bpy.data.materials | |
material_names = {} | |
for mat in materials: | |
if mat.name in material_names: | |
# Replace users of this material with the existing one | |
mat.user_clear() | |
materials.remove(mat) | |
else: | |
material_names[mat.name] = mat | |
# Consolidate duplicate materials | |
remove_duplicate_materials() | |
# 5. Enable compression when saving the file | |
bpy.context.preferences.filepaths.use_file_compression = True | |
# 6. Save the file as a compressed .blend file | |
blend_filepath = bpy.data.filepath # Current file path | |
if blend_filepath: | |
bpy.ops.wm.save_as_mainfile(filepath=blend_filepath, compress=True) | |
print(f"File saved and compressed: {blend_filepath}") | |
else: | |
print("No file path found. Please save the file manually after running the script.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment