У меня есть аддон для Blender 3.3.0, вот его код:
bl_info = {
"name": "F1 Track Material Maker",
"author": "AlonsoBeast",
"version": (1, 0),
"blender": (3, 3, 0),
"location": "3D View > Sidebar",
"description": "Addon for managing F1 Track materials",
"category": "Material",
}
import bpy
import os
from bpy.props import StringProperty, CollectionProperty, EnumProperty, IntProperty
from bpy.types import Panel, Operator, PropertyGroup
import xml.etree.ElementTree as ET
from io import BytesIO
import bmesh
SHADER_GROUP_BLOCKS = {
"#env_diff.fx": {
"parameterCount": "22",
"parameterSavedCount": "3",
"renderSortPriority": "0",
"inputs": [
('7', "constant", "float", "0.000000000e+000"),
('17', "texture", "#diffuse_d.tga"),
('18', "texture", "#normal_n.tga"),
]
},
"#env_diffalpha.fx": {
"parameterCount": "22",
"parameterSavedCount": "3",
"renderSortPriority": "0",
"inputs": [
('7', "constant", "float", "0.000000000e+000"),
('17', "texture", "#alpha_d.tga"),
('18', "texture", "#normal_n.tga"),
]
},
"#env_diffalphaspecnorm.fx": {
"parameterCount": "24",
"parameterSavedCount": "5",
"renderSortPriority": "0",
"inputs": [
('7', "constant", "float", "0.000000000e+000"),
('17', "texture", "#diffuse_d.tga"),
('18', "texture", "#specular_s.tga"),
('19', "texture", "#normal_n.tga"),
('20', "texture", "#ambient_a.tga"),
]
},
"#env_diffmask.fx": {
"parameterCount": "22",
"parameterSavedCount": "3",
"renderSortPriority": "0",
"inputs": [
('7', "constant", "float", "0.000000000e+000"),
('17', "texture", "#alpha_diffuse.tga"),
('18', "texture", "#normal.tga"),
]
},
"#track_offtracksurface.fx": {
"parameterCount": "42",
"parameterSavedCount": "14",
"renderSortPriority": "0",
"inputs": [
('7', "constant", "float", "0.000000000e+000"),
('21', "texture", "#diffuse_tarmac_white_01_d.tga"),
('22', "constant", "float", "5.000000000e-001"),
('23', "texture", "#normal_offtrack_a_01_n.tga"),
('24', "constant", "float", "2.000000000e+001"),
('25', "constant", "float", "1.000000000e+001"),
('26', "texture", "#diffuse_macro_01_d.tga"),
('27', "texture", "#terrain_01_a.tga"),
('28', "texture", "#track_skidmarks_long.tga"),
('29', "constant", "float", "2.500000000e-001"),
('30', "constant", "float", "1.000000000e+000"),
('31', "texture", "#track_weteffects.tga"),
('32', "constant", "float", "1.000000000e+000"),
('33', "constant", "float", "1.000000000e+000"),
]
},
}
class TextureEntry(PropertyGroup):
parameter_id: StringProperty(name="Parameter ID")
type: StringProperty(name="Type", default="texture")
name_middle: StringProperty(name="Middle", default="")
class MaterialBlock(PropertyGroup):
def update_shader_group(self, context):
self.texture_inputs.clear()
block_data = SHADER_GROUP_BLOCKS.get(self.shader_group, {})
for input_data in block_data.get("inputs", []):
param_id = input_data[0]
tex_type = input_data[1]
if tex_type == "texture":
tex_name = input_data[2].strip('#.tga')
tex_entry = self.texture_inputs.add()
tex_entry.parameter_id = param_id
tex_entry.type = tex_type
tex_entry.name_middle = tex_name
shader_group: EnumProperty(
name="Shader Group",
items=[(key, key, "") for key in SHADER_GROUP_BLOCKS.keys()],
update=update_shader_group
)
material_id: StringProperty(name="Material ID", default="new_material")
texture_inputs: CollectionProperty(type=TextureEntry)
def find_image_texture_node(input_socket):
if not input_socket.is_linked:
return None
link_node = input_socket.links[0].from_node
if link_node.type == 'TEX_IMAGE':
return link_node
for input_ in link_node.inputs:
if input_.is_linked:
texture_node = find_image_texture_node(input_)
if texture_node:
return texture_node
return None
def draw_texture_or_color_preview(col, material):
texture_node = None
if material.use_nodes:
node_tree = material.node_tree
for node in node_tree.nodes:
if node.type == 'BSDF_PRINCIPLED':
base_color = node.inputs["Base Color"]
texture_node = find_image_texture_node(base_color)
if texture_node:
break
row = col.row(align=True)
if texture_node:
row.template_ID_preview(texture_node, "image", hide_buttons=True)
col = col.column(align=True)
# Удаляем прежнюю кнопку копирования
# copy_name_op = browse_row.operator("f1_material.copy_texture_name", text="", icon="COPY_ID", emboss=True)
# copy_name_op.name_to_copy = texture_node.image.name if texture_node.image else ""
col.operator("f1_material.import_image", text="Import Image", icon="FILEBROWSER", emboss=True)
# Добавляем новую кнопку копирования
if texture_node and texture_node.image:
copy_name_op = col.operator("f1_material.copy_texture_name", text="Copy Name Texture", icon="COPY_ID", emboss=True)
copy_name_op.name_to_copy = texture_node.image.name if texture_node.image else ""
delete_op = col.operator("f1_material.delete_image", text="Delete Image", icon="TRASH", emboss=True)
delete_op.image_name = texture_node.image.name
unlink_op = col.operator("f1_material.unlink_image", text="Unlink Image", icon="UNLINKED", emboss=True)
unlink_op.image_name = texture_node.image.name
unlink_op.material_name = material.name
class F1MaterialMakerPanel(Panel):
bl_label = "F1 Track Material Maker"
bl_idname = "VIEW3D_PT_f1_material_maker"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'F1 Material Maker'
def draw(self, context):
layout = self.layout
scene = context.scene
row = layout.row()
row.operator("f1_material.import", text="Import XML")
row.operator("f1_material.export", text="Export XML")
layout.label(text="Library of SHADERINSTANCE")
for i, block in enumerate(scene.material_blocks):
box = layout.box()
box.prop(block, "shader_group")
material = bpy.data.materials.get(block.material_id)
if material:
row = box.row()
draw_texture_or_color_preview(row, material)
box.prop_search(block, "material_id", bpy.data, "materials", text="Material")
assign_op = box.operator("f1_material.assign_material", text="Assign Material", icon='MATERIAL')
assign_op.material_name = block.material_id
pick_op = box.operator("f1_material.pick_material", text="Pick Material", icon='EYEDROPPER')
pick_op.block_index = i
highlight_op = box.operator("f1_material.highlight_material", text="Highlight Material", icon='RESTRICT_SELECT_OFF')
highlight_op.material_name = block.material_id
for tex_input in block.texture_inputs:
col = box.column(align=True)
row = col.split(factor=0.9, align=True)
row.prop(tex_input, "name_middle", text=f"TextureID ({tex_input.parameter_id})", full_event=True)
row.label(text=".tga")
box.operator("f1_material.remove_block", text="Remove Block")
layout.operator("f1_material.add_block", text="Add Material Block")
class CopyTextureNameOperator(Operator):
bl_idname = "f1_material.copy_texture_name"
bl_label = "Copy Texture Name"
bl_description = "Copy texture name to clipboard"
name_to_copy: StringProperty()
def execute(self, context):
# Извлекаем имя текстуры без расширения
name_without_extension = os.path.splitext(self.name_to_copy)[0]
context.window_manager.clipboard = name_without_extension
self.report({'INFO'}, f"Texture name '{name_without_extension}' copied to clipboard")
return {'FINISHED'}
class ImportOperator(Operator):
bl_idname = "f1_material.import"
bl_label = "Import Material XML"
filepath: StringProperty(subtype='FILE_PATH')
def execute(self, context):
global xml_tree_global
try:
xml_tree_global = ET.parse(self.filepath)
self.report({'INFO'}, f"Succeed import from {self.filepath}")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Failed to import XML: {str(e)}")
return {'CANCELLED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class ExportOperator(Operator):
bl_idname = "f1_material.export"
bl_label = "Export Material XML"
filepath: StringProperty(subtype='FILE_PATH')
def execute(self, context):
global xml_tree_global
try:
if not xml_tree_global:
self.report({'ERROR'}, "No XML data to export")
return {'CANCELLED'}
root = xml_tree_global.getroot()
library = root.find('./LIBRARY[@type="SHADERINSTANCE"]')
if library is None:
library = ET.SubElement(root, "LIBRARY", type="SHADERINSTANCE")
for block in context.scene.material_blocks:
block_data = SHADER_GROUP_BLOCKS[block.shader_group]
shader_instance = ET.Element(
"SHADERINSTANCE",
shaderGroup=block.shader_group,
parameterCount=block_data["parameterCount"],
parameterSavedCount=block_data["parameterSavedCount"],
renderSortPriority=block_data["renderSortPriority"],
id=block.material_id
)
for input_data in block_data["inputs"]:
param_id = input_data[0]
tex_type = input_data[1]
shader_input = ET.Element(
"SHADERINPUT",
parameterID=param_id,
type=tex_type
)
if tex_type == "texture":
corresponding_input = next(
(ti for ti in block.texture_inputs if ti.parameter_id == param_id), None)
updated_texture = f"#{corresponding_input.name_middle}.tga" if corresponding_input else input_data[2]
shader_input.set("texture", updated_texture)
else:
shader_input.set("format", input_data[2])
shader_input.text = input_data[3]
shader_instance.append(shader_input)
library.append(shader_instance)
def indent(elem, level=0):
i = "\n" + level * " "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level + 1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
indent(root)
buffer = BytesIO()
xml_tree_global.write(buffer, encoding='utf-8', xml_declaration=True)
with open(self.filepath, 'wb') as f:
f.write(buffer.getvalue())
self.report({'INFO'}, f"Succeed export to {self.filepath}")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Failed to export XML: {str(e)}")
return {'CANCELLED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class ImportImageOperator(Operator):
bl_idname = "f1_material.import_image"
bl_label = "Import Image"
bl_description = "Add image to project"
filepath: StringProperty(subtype='FILE_PATH')
def execute(self, context):
try:
image = bpy.data.images.load(self.filepath, check_existing=True)
self.report({'INFO'}, f"Image '{image.name}' imported successfully")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Failed to import image: {str(e)}")
return {'CANCELLED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class DeleteImageOperator(Operator):
bl_idname = "f1_material.delete_image"
bl_label = "Delete Image"
bl_description = "Full delete image from project"
image_name: StringProperty()
def execute(self, context):
image = bpy.data.images.get(self.image_name)
if image:
bpy.data.images.remove(image)
self.report({'INFO'}, f"Image '{self.image_name}' deleted successfully")
return {'FINISHED'}
else:
self.report({'ERROR'}, f"Image '{self.image_name}' not found")
return {'CANCELLED'}
class UnlinkImageOperator(Operator):
bl_idname = "f1_material.unlink_image"
bl_label = "Unlink Image from Material"
bl_description = "Unlink image from material"
image_name: StringProperty()
material_name: StringProperty()
def execute(self, context):
material = bpy.data.materials.get(self.material_name)
if material and material.use_nodes:
for node in material.node_tree.nodes:
if node.type == 'TEX_IMAGE' and node.image and node.image.name == self.image_name:
node.image = None
self.report({'INFO'}, f"Image '{self.image_name}' unlinked from material '{self.material_name}'")
return {'FINISHED'}
else:
self.report({'ERROR'}, f"Material '{self.material_name}' not found or not using nodes")
return {'CANCELLED'}
class AssignMaterialOperator(Operator):
bl_idname = "f1_material.assign_material"
bl_label = "Assign Material"
material_name: StringProperty()
def execute(self, context):
material = bpy.data.materials.get(self.material_name)
if not material:
self.report({'ERROR'}, f"Material '{self.material_name}' not found!")
return {'CANCELLED'}
selected_objects = [obj for obj in context.selected_objects if obj.type == 'MESH']
if not selected_objects:
self.report({'ERROR'}, "No selected mesh objects")
return {'CANCELLED'}
for obj in selected_objects:
bpy.context.view_layer.objects.active = obj
if len(obj.data.materials) == 0:
obj.data.materials.append(material)
mat_index = 0
else:
active_index = obj.active_material_index
if active_index >= 0:
obj.data.materials[active_index] = material
mat_index = active_index
else:
mat_index = obj.data.materials.find(material.name)
if mat_index == -1:
obj.data.materials.append(material)
mat_index = obj.data.materials.find(material.name)
if obj.mode == 'EDIT':
bpy.ops.object.mode_set(mode='EDIT')
bm = bmesh.from_edit_mesh(obj.data)
for face in bm.faces:
if face.select:
face.material_index = mat_index
bmesh.update_edit_mesh(obj.data)
self.report({'INFO'}, f"Material '{self.material_name}' assigned to selected faces of '{obj.name}'")
else:
obj.active_material_index = mat_index
for face in obj.data.polygons:
if face.material_index == active_index:
face.material_index = mat_index
self.report({'INFO'}, f"Material '{self.material_name}' set as active on '{obj.name}'")
return {'FINISHED'}
class HighlightMaterialOperator(Operator):
bl_idname = "f1_material.highlight_material"
bl_label = "Highlight Material"
material_name: StringProperty()
bl_description = "Highlights all objects in the scene using the selected material"
def execute(self, context):
if self.material_name in bpy.data.materials:
material = bpy.data.materials[self.material_name]
bpy.ops.object.select_all(action='DESELECT')
for obj in bpy.data.objects:
if obj.type == 'MESH' and obj.data is not None:
if self.material_name in [mat.name for mat in obj.data.materials if mat is not None]:
obj.select_set(True)
self.report({'INFO'}, f"Objects using '{self.material_name}' are highlighted")
else:
self.report({'ERROR'}, f"Material '{self.material_name}' not found!")
return {'FINISHED'}
class PickMaterialOperator(Operator):
bl_idname = "f1_material.pick_material"
bl_label = "Pick Material"
block_index: IntProperty()
def execute(self, context):
obj = context.object
if not obj or obj.type != 'MESH':
self.report({'ERROR'}, "Selected object is not a mesh")
return {'CANCELLED'}
active_material = None
if obj.mode == 'EDIT':
bm = bmesh.from_edit_mesh(obj.data)
bm.faces.ensure_lookup_table()
active_face = bm.select_history.active
if active_face:
active_material_index = active_face.material_index
if active_material_index < len(obj.data.materials):
active_material = obj.data.materials[active_material_index]
else:
self.report({'ERROR'}, "No active face selected in edit mode")
return {'CANCELLED'}
elif obj.data.materials:
active_material = obj.data.materials[0]
if not active_material:
self.report({'ERROR'}, "No material attached to selected object")
return {'CANCELLED'}
if self.block_index < len(context.scene.material_blocks):
block = context.scene.material_blocks[self.block_index]
block.material_id = active_material.name
self.report({'INFO'}, f"Material '{active_material.name}' picked in block {self.block_index}")
return {'FINISHED'}
class AddBlockOperator(Operator):
bl_idname = "f1_material.add_block"
bl_label = "Add Material Block"
def execute(self, context):
block = context.scene.material_blocks.add()
block.shader_group = "#env_diff.fx"
block.material_id = "new_material"
block.update_shader_group(context)
return {'FINISHED'}
class RemoveBlockOperator(Operator):
bl_idname = "f1_material.remove_block"
bl_label = "Remove Material Block"
def execute(self, context):
scene = context.scene
if scene.material_blocks:
scene.material_blocks.remove(len(scene.material_blocks) - 1)
return {'FINISHED'}
def register():
bpy.utils.register_class(TextureEntry)
bpy.utils.register_class(MaterialBlock)
bpy.types.Scene.material_blocks = CollectionProperty(type=MaterialBlock)
bpy.utils.register_class(F1MaterialMakerPanel)
bpy.utils.register_class(ImportOperator)
bpy.utils.register_class(ExportOperator)
bpy.utils.register_class(ImportImageOperator)
bpy.utils.register_class(DeleteImageOperator)
bpy.utils.register_class(UnlinkImageOperator)
bpy.utils.register_class(CopyTextureNameOperator)
bpy.utils.register_class(AssignMaterialOperator)
bpy.utils.register_class(HighlightMaterialOperator)
bpy.utils.register_class(PickMaterialOperator)
bpy.utils.register_class(AddBlockOperator)
bpy.utils.register_class(RemoveBlockOperator)
def unregister():
bpy.utils.unregister_class(TextureEntry)
bpy.utils.unregister_class(MaterialBlock)
del bpy.types.Scene.material_blocks
bpy.utils.unregister_class(F1MaterialMakerPanel)
bpy.utils.unregister_class(ImportOperator)
bpy.utils.unregister_class(ExportOperator)
bpy.utils.unregister_class(ImportImageOperator)
bpy.utils.unregister_class(DeleteImageOperator)
bpy.utils.unregister_class(UnlinkImageOperator)
bpy.utils.unregister_class(CopyTextureNameOperator)
bpy.utils.unregister_class(AssignMaterialOperator)
bpy.utils.unregister_class(HighlightMaterialOperator)
bpy.utils.unregister_class(PickMaterialOperator)
bpy.utils.unregister_class(AddBlockOperator)
bpy.utils.unregister_class(RemoveBlockOperator)
if name == "main":
register()