import bpy
import os
from bpy.props import StringProperty, CollectionProperty, EnumProperty
from bpy.types import Panel, Operator, PropertyGroup
import xml.etree.ElementTree as ET
from io import BytesIO
class ImportOperator(Operator):
bl_idname = "f1_material.import"
bl_label = "Import Material XML"
code
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"
code
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 = corresponding_input.name 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}")
print("Export Succeed")
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 Already Image"
code
filepath: StringProperty(subtype='FILE_PATH')
target_texture: StringProperty()
def execute(self, context):
new_name = os.path.splitext(os.path.basename(self.filepath))[0]
for block in context.scene.material_blocks:
for tex_input in block.texture_inputs:
if tex_input.name == self.target_texture:
tex_input.name = f"#{new_name}.tga"
print(f"Updated texture name to '{new_name}'")
return {'FINISHED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class SelectMaterialOperator(Operator):
bl_idname = "f1_material.select_material"
bl_label = "Select Active Material"
material_name: StringProperty()
code
def execute(self, context):
if self.material_name in bpy.data.materials:
context.object.active_material = bpy.data.materials[self.material_name]
bpy.context.view_layer.objects.active.active_material = bpy.data.materials[self.material_name]
self.report({'INFO'}, f"Material '{self.material_name}' selected")
else:
self.report({'ERROR'}, f"Material '{self.material_name}' not found!")
return {'FINISHED'}
class AddBlockOperator(Operator):
bl_idname = "f1_material.add_block"
bl_label = "Add Material Block"
Привет! Спасибо за предоставленный код аддона для Blender. Похоже, это аддон для управления материалами трасс F1, который предоставляет функционал для импорта и экспорта XML-файлов с информацией о материалах, а также возможность настройки и выбора материалов через пользовательский интерфейс.
Если у тебя есть вопросы или ты столкнулся с какой-то проблемой в работе этого аддона, дай знать — постараюсь помочь!
User
Там, где селектор материалов (Material: здесь выбор материалов из списка), можно ли сделать так, чтобы слева от селектора отображалось превью выбранного материала квадратиком 40 на 40 пикселей. Главное, чтобы не сломать обработчик, импорта и экспорта материала, нужно просто добавить в код этот элемент, я запрещаю трогать оригинальный код, чтобы его не сломать.
Assistant
Чтобы добавить превью материала рядом с селектором без изменения существующего функционала обработки, импорта и экспорта, вы можете просто дополнить метод draw вашего UI-панеля. В Blender интерфейсах, вы можете использовать метод template_preview для отображения превью материала. Ниже приведен пример, как это можно сделать:
python
class F1MaterialMakerPanel(Panel):
# ... остальной код ...
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 block in scene.material_blocks:
box = layout.box()
box.prop(block, "shader_group")
material = bpy.data.materials.get(block.material_id)
# Добавляем новый столбец для превью и селектора материала
material_row = box.row(align=True)
# Отображаем превью материала
if material:
material_row.template_preview(material, show_buttons=False, scale=2)
# Селектор материалов
material_row.prop_search(block, "material_id", bpy.data, "materials", text="Material")
select_op = box.operator("f1_material.select_material", text="Make Active", icon='CHECKMARK')
select_op.material_name = block.material_id
for tex_input in block.texture_inputs:
row = box.row()
row.prop(tex_input, "name", text=f"TextureID ({tex_input.parameter_id})")
import_op = row.operator("f1_material.import_image", text="", icon="IMPORT", emboss=True)
import_op.target_texture = tex_input.name
box.operator("f1_material.remove_block", text="Remove Block")
layout.operator("f1_material.add_block", text="Add Material Block")
User
Дай пожалуйста полный код аддона вместе с моим
Assistant
Конечно! Вот полный код аддона с добавленным превью материала в пользовательском интерфейсе:
python
User
Сломал аддон..(
Python: Traceback (most recent call last):
File "C:\Users\USER\AppData\Roaming\Blender Foundation\Blender\3.3\scripts\addons\f1_track_material_maker_full.py", line 143, in draw
material_row.template_preview(material, show_buttons=False, scale=2)
TypeError: UILayout.template_preview(): was called with invalid keyword argument(s) (scale), expected (id, show_buttons, parent, slot, preview_id)
Assistant
Извините за ошибку, это, вероятно, произошло из-за неправильного использования функции template_preview. Давайте попробуем исправить это. Метод template_preview требует некоторые специфические параметры для корректного отображения превью материала.
Попробуем использовать layout.template_ID_preview, которая может корректно показывать превью материала, если просто указать активный материал. Изменим соответствующую часть в коде следующим образом:
python
class F1MaterialMakerPanel(Panel):
# ... остальной код ...
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 block in scene.material_blocks:
box = layout.box()
box.prop(block, "shader_group")
material = bpy.data.materials.get(block.material_id)
# Добавляем новый столбец для превью и селектора материала
material_row = box.row(align=True)
# Отображаем превью материала
if material:
material_row.template_ID_preview(context.object, "active_material", new="material.new", rows=3, cols=8)
# Селектор материалов
material_row.prop_search(block, "material_id", bpy.data, "materials", text="Material")
select_op = box.operator("f1_material.select_material", text="Make Active", icon='CHECKMARK')
select_op.material_name = block.material_id
for tex_input in block.texture_inputs:
row = box.row()
row.prop(tex_input, "name", text=f"TextureID ({tex_input.parameter_id})")
import_op = row.operator("f1_material.import_image", text="", icon="IMPORT", emboss=True)
import_op.target_texture = tex_input.name
box.operator("f1_material.remove_block", text="Remove Block")
layout.operator("f1_material.add_block", text="Add Material Block")
User
Давай полнйы код аддона всегдла
Assistant
Конечно, вот полный код аддона с исправлениями для отображения превью материала:
python
User
Супер, только правку внеси. Смысл в том, чтобы сделать превью материала, который мы ВЫБИРАЕМ в селекторе, а не превью материала, который мы выбираем в сцене кликая на меш. Понимаешь?
Assistant
Понял! Мы должны отобразить превью материала, который выбирается в выпадающем списке, а не устанавливать активный материал сцены. Давайте исправим метод draw, чтобы он показывал превью конкретного материала, выбранного из списка:
python
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 block in scene.material_blocks:
box = layout.box()
box.prop(block, "shader_group")
# Получаем указанный в блоке материал по его имени
material = bpy.data.materials.get(block.material_id)
# Строка для превью и выбора материала
material_row = box.row(align=True)
# Превью материала
if material:
material_row.template_ID_preview({"material": material}, "material", new="", rows=1, cols=1)
# Селектор материалов
material_row.prop_search(block, "material_id", bpy.data, "materials", text="Material")
select_op = box.operator("f1_material.select_material", text="Make Active", icon='CHECKMARK')
select_op.material_name = block.material_id
for tex_input in block.texture_inputs:
row = box.row()
row.prop(tex_input, "name", text=f"TextureID ({tex_input.parameter_id})")
import_op = row.operator("f1_material.import_image", text="", icon="IMPORT", emboss=True)
import_op.target_texture = tex_input.name
box.operator("f1_material.remove_block", text="Remove Block")
layout.operator("f1_material.add_block", text="Add Material Block")
Что изменилось:
Используем template_ID_preview с {"material": material} контекстом для отрисовки превью материала по его имени, указанному в блоке.
Таким образом, превью отображает материал, который был выбран в выпадающем списке prop_search.
Попробуйте новую версию, и дайте знать, если необходимо сделать какие-то дополнительные правки.
User
ПОлный код аддона давай
Assistant
Конечно, вот полный код аддона с необходимыми изменениями для отображения превью материала, выбранного в селекторе:
python
User
Супер просто, всё хорошо, не трогай больше, такие превью мне нравтяся, только единственный баг, обновление превью в окошке не работает при выборе, она обновляется только тогда, когда я делаю ресайз. Делай так, чтобы при клике на материал в селекторе, превью автоматичеки обновлялось после этого действияя
Assistant
Чтобы обеспечить обновление превью материала при выборе его в селекторе, можно использовать механизм обновления свойств через callback-функцию. Этот подход позволяет обновлять изображение превью при каждом изменении выбранного материала.
Для этого слегка изменим код, добавив метод обновления, который будет вызываться при изменении материала. В итоге код будет выглядеть следующим образом:
python
User
Не сработаетывает, он обновляется только когда ресайз делаю...В чем дело?
Assistant
Я извиняюсь за предыдущие недоразумения. Иногда проблема с обновлением в Blender может происходить из-за того, что элемент UI не понимает, что ему нужно обновиться. Попробуем другой подход для принудительного обновления UI.
Вместо использования context.area.tag_redraw(), мы можем использовать bpy.context.area.tag_redraw() и убедиться, что обновление происходит для соответствующей области интерфейса:
python
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]
tex_entry = self.texture_inputs.add()
tex_entry.parameter_id = param_id
tex_entry.type = tex_type
tex_entry.name = tex_name
def update_material(self, context):
for area in bpy.context.screen.areas:
if area.ui_type == 'VIEW_3D':
area.tag_redraw()
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",
update=update_material
)
texture_inputs: CollectionProperty(type=TextureEntry)
Основные изменения:
Метод update_material перебирает все области (areas) на текущем экране (bpy.context.screen.areas).
Он вызывает tag_redraw() только для областей, соответствующих типу 'VIEW_3D'.
Этот подход должен более надежно обновлять UI в необходимой панели. Попробуйте сделать ресайз панели, чтобы проверить, будет ли обновляться превью при выборе материала в списке.
User
Дай полный код аддонга
Assistant
Конечно, вот полный код аддона с последними изменениями для обновления превью при выборе материала:
python
User
Не работает... Привяжи его к тому, чтобы когда был выбор материала в селекторе, вот этот экшн - делалось тоже самое, что происходит при ресайзе изображения, свяжи их как бы, может так сработает
Assistant
Прости за неудобства. Давайте попробуем другой способ, чтобы обеспечить обновление эскиза при выборе материала в селекторе. Идея в том, чтобы использовать так называемые "заготовки" (dummy properties) и обновить их принудительно, что бы вызвало пересчет и обновление интерфейса.
Мы попробуем использовать оператор bpy.ops.ed.undo_push() для обновления истории изменений, чтобы эскиз обновился. Это немного хитро, но может помочь заставить Blender обновить интерфейс:
python
User
Не работает. Ты меня слышишь? Вот когда я делаю ресайз - сразу же картинка обновляется на нужную, но когда я выбираю материал в выпадающем списке материалов в этом аддоне - превью не обновляется, и даже если кликать на иконки типа меша в превью он тоже не обновляется.Учти что это блендер 3.3.0. Свяжи ту функцию, которая обновляет превью на ресайзе, с выбором материала в селекторе и заодно выбора модели меша превью. Если надо уточнить в чем дело, спрашивай
Assistant
Извините за недоразумения, давайте попробуем другое решение. Если привязка обновления превью к выбору материала в списке работает на других кабинетах, таких как масштабирование окна, это может означать, что принудительная перерисовка самого виджета превью не работает. Blender, к сожалению, не предоставляет явного метода для обновления превью.
Мы можем попробовать другие известные нам способы принудительного обновления интерфейса через динамические изменения сценария или PropertyGroup. Одним из таких обходных путей является добавление фиктивного свойства, которое обновляет интерфейс, когда мы взаимодействуем с виджетом.
Попробуем использовать bpy.context.area.tag_redraw() совместно с изменением фиктивного свойства:
python
User
Не работает... :) Есть костыльная идея, сделай так, чтобы когда мы выбирали материал в селекторе, происходил невидимый ресайз на 0пикселей (если это не считается, то на 1 пиксель вперед и на 1 пиксель назад сразу же). Это позволит превьюшке обновится
Assistant
Понятно, давайте попробуем этот костыльный метод. Мы можем использовать Python для изменения размеров UILayout области, в которой находится превью материалов. Это не самое элегантное решение, но может быть полезно для принудительного обновления.
К сожалению, нет прямого API для изменения размеров через скрипты. Однако, вот идея, которую можно использовать: менять размеры окна оператора, например, на 1 пиксель вперед и назад, но через изменение высоты (или ширины).
Мы можем попытаться вмешаться в интерфейсную часть кода, связав изменение UI с переключением материала:
python
Not yet included in a published release.
Что здесь сделано:
Мы используем material_row = box.row(align=True) для создания строки, где будет располагаться превью и селектор материала.
Используем if material: для получения материала с указанным material_id. Если такой материал существует, используется material_row.template_preview(material, show_buttons=False, scale=2) для отображения превью.
Затем рядом с превью добавляется prop_search для выбора материала.
Таким образом, вы добавляете превью материала размером 40 на 40 пикселей (хотя точное масштабирование может немного отличаться), не затрагивая основное поведение аддона.
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
from bpy.types import Panel, Operator, PropertyGroup
import xml.etree.ElementTree as ET
from io import BytesIO
# Configuration ShaderGroup
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"),
]
},
}
# Property Group for blocks and textures
class TextureEntry(PropertyGroup):
parameter_id: StringProperty(name="Parameter ID")
type: StringProperty(name="Type", default="texture")
name: StringProperty(name="Texture Name", 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]
tex_entry = self.texture_inputs.add()
tex_entry.parameter_id = param_id
tex_entry.type = tex_type
tex_entry.name = 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)
# UI Panel
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 block in scene.material_blocks:
box = layout.box()
box.prop(block, "shader_group")
material = bpy.data.materials.get(block.material_id)
# Добавляем новый столбец для превью и селектора материала
material_row = box.row(align=True)
# Отображаем превью материала
if material:
material_row.template_preview(material, show_buttons=False, scale=2)
# Селектор материалов
material_row.prop_search(block, "material_id", bpy.data, "materials", text="Material")
select_op = box.operator("f1_material.select_material", text="Make Active", icon='CHECKMARK')
select_op.material_name = block.material_id
for tex_input in block.texture_inputs:
row = box.row()
row.prop(tex_input, "name", text=f"TextureID ({tex_input.parameter_id})")
import_op = row.operator("f1_material.import_image", text="", icon="IMPORT", emboss=True)
import_op.target_texture = tex_input.name
box.operator("f1_material.remove_block", text="Remove Block")
layout.operator("f1_material.add_block", text="Add Material Block")
# Operators
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 = corresponding_input.name 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}")
print("Export Succeed")
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 Already Image"
filepath: StringProperty(subtype='FILE_PATH')
target_texture: StringProperty()
def execute(self, context):
new_name = os.path.splitext(os.path.basename(self.filepath))[0]
for block in context.scene.material_blocks:
for tex_input in block.texture_inputs:
if tex_input.name == self.target_texture:
tex_input.name = f"#{new_name}.tga"
print(f"Updated texture name to '{new_name}'")
return {'FINISHED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class SelectMaterialOperator(Operator):
bl_idname = "f1_material.select_material"
bl_label = "Select Active Material"
material_name: StringProperty()
def execute(self, context):
if self.material_name in bpy.data.materials:
context.object.active_material = bpy.data.materials[self.material_name]
bpy.context.view_layer.objects.active.active_material = bpy.data.materials[self.material_name]
self.report({'INFO'}, f"Material '{self.material_name}' selected")
else:
self.report({'ERROR'}, f"Material '{self.material_name}' not found!")
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'}
# Registration
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(SelectMaterialOperator)
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(SelectMaterialOperator)
bpy.utils.unregister_class(AddBlockOperator)
bpy.utils.unregister_class(RemoveBlockOperator)
if __name__ == "__main__":
register()
Эта доработка добавляет превью для выбранного материала в боксе вместе с селектором, не влияя на остальную функциональность аддона.
Основные изменения:
Заменили template_preview на template_ID_preview, который лучше подходит для данного случая, отображая список материалов и активный материал.
Использовали метод template_ID_preview для отображения предварительного просмотра материала. Обратите внимание, что это делает выбранный материал активным, что может подходить тоньше вашей целевой функциональности. Если это не тот результат, который вы ожидали, возможно, есть нюансы или ограничения в Blender API для конкретного вида предварительного просмотра.
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
from bpy.types import Panel, Operator, PropertyGroup
import xml.etree.ElementTree as ET
from io import BytesIO
# Configuration ShaderGroup
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"),
]
},
}
# Property Group for blocks and textures
class TextureEntry(PropertyGroup):
parameter_id: StringProperty(name="Parameter ID")
type: StringProperty(name="Type", default="texture")
name: StringProperty(name="Texture Name", 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]
tex_entry = self.texture_inputs.add()
tex_entry.parameter_id = param_id
tex_entry.type = tex_type
tex_entry.name = 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)
# UI Panel
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 block in scene.material_blocks:
box = layout.box()
box.prop(block, "shader_group")
material = bpy.data.materials.get(block.material_id)
# Добавляем новый столбец для превью и селектора материала
material_row = box.row(align=True)
# Отображаем превью материала
if material:
material_row.template_ID_preview(context.object, "active_material", new="material.new", rows=3, cols=8)
# Селектор материалов
material_row.prop_search(block, "material_id", bpy.data, "materials", text="Material")
select_op = box.operator("f1_material.select_material", text="Make Active", icon='CHECKMARK')
select_op.material_name = block.material_id
for tex_input in block.texture_inputs:
row = box.row()
row.prop(tex_input, "name", text=f"TextureID ({tex_input.parameter_id})")
import_op = row.operator("f1_material.import_image", text="", icon="IMPORT", emboss=True)
import_op.target_texture = tex_input.name
box.operator("f1_material.remove_block", text="Remove Block")
layout.operator("f1_material.add_block", text="Add Material Block")
# Operators
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 = corresponding_input.name 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}")
print("Export Succeed")
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 Already Image"
filepath: StringProperty(subtype='FILE_PATH')
target_texture: StringProperty()
def execute(self, context):
new_name = os.path.splitext(os.path.basename(self.filepath))[0]
for block in context.scene.material_blocks:
for tex_input in block.texture_inputs:
if tex_input.name == self.target_texture:
tex_input.name = f"#{new_name}.tga"
print(f"Updated texture name to '{new_name}'")
return {'FINISHED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class SelectMaterialOperator(Operator):
bl_idname = "f1_material.select_material"
bl_label = "Select Active Material"
material_name: StringProperty()
def execute(self, context):
if self.material_name in bpy.data.materials:
context.object.active_material = bpy.data.materials[self.material_name]
bpy.context.view_layer.objects.active.active_material = bpy.data.materials[self.material_name]
self.report({'INFO'}, f"Material '{self.material_name}' selected")
else:
self.report({'ERROR'}, f"Material '{self.material_name}' not found!")
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'}
# Registration
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(SelectMaterialOperator)
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(SelectMaterialOperator)
bpy.utils.unregister_class(AddBlockOperator)
bpy.utils.unregister_class(RemoveBlockOperator)
if __name__ == "__main__":
register()
Если возникли еще какие-то ошибки или проблемы, пожалуйста, дай знать, и я постараюсь помочь исправить их!
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
from bpy.types import Panel, Operator, PropertyGroup
import xml.etree.ElementTree as ET
from io import BytesIO
# Configuration ShaderGroup
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"),
]
},
}
# Property Group for blocks and textures
class TextureEntry(PropertyGroup):
parameter_id: StringProperty(name="Parameter ID")
type: StringProperty(name="Type", default="texture")
name: StringProperty(name="Texture Name", 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]
tex_entry = self.texture_inputs.add()
tex_entry.parameter_id = param_id
tex_entry.type = tex_type
tex_entry.name = 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)
# UI Panel
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 block in scene.material_blocks:
box = layout.box()
box.prop(block, "shader_group")
# Получаем указанный в блоке материал по его имени
material = bpy.data.materials.get(block.material_id)
# Строка для превью и выбора материала
material_row = box.row(align=True)
# Проверяем, существует ли материал, и отображаем его превью
if material:
material_row.template_preview(material)
# Селектор материалов
material_row.prop_search(block, "material_id", bpy.data, "materials", text="Material")
select_op = box.operator("f1_material.select_material", text="Make Active", icon='CHECKMARK')
select_op.material_name = block.material_id
for tex_input in block.texture_inputs:
row = box.row()
row.prop(tex_input, "name", text=f"TextureID ({tex_input.parameter_id})")
import_op = row.operator("f1_material.import_image", text="", icon="IMPORT", emboss=True)
import_op.target_texture = tex_input.name
box.operator("f1_material.remove_block", text="Remove Block")
layout.operator("f1_material.add_block", text="Add Material Block")
# Operators
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 = corresponding_input.name 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}")
print("Export Succeed")
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 Already Image"
filepath: StringProperty(subtype='FILE_PATH')
target_texture: StringProperty()
def execute(self, context):
new_name = os.path.splitext(os.path.basename(self.filepath))[0]
for block in context.scene.material_blocks:
for tex_input in block.texture_inputs:
if tex_input.name == self.target_texture:
tex_input.name = f"#{new_name}.tga"
print(f"Updated texture name to '{new_name}'")
return {'FINISHED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class SelectMaterialOperator(Operator):
bl_idname = "f1_material.select_material"
bl_label = "Select Active Material"
material_name: StringProperty()
def execute(self, context):
if self.material_name in bpy.data.materials:
context.object.active_material = bpy.data.materials[self.material_name]
bpy.context.view_layer.objects.active.active_material = bpy.data.materials[self.material_name]
self.report({'INFO'}, f"Material '{self.material_name}' selected")
else:
self.report({'ERROR'}, f"Material '{self.material_name}' not found!")
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'}
# Registration
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(SelectMaterialOperator)
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(SelectMaterialOperator)
bpy.utils.unregister_class(AddBlockOperator)
bpy.utils.unregister_class(RemoveBlockOperator)
if __name__ == "__main__":
register()
Теперь панель должна корректно показывать превью материала, который выбран в селекторе. Если возникнут дополнительные вопросы или проблемы, дайте знать!
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
from bpy.types import Panel, Operator, PropertyGroup
import xml.etree.ElementTree as ET
from io import BytesIO
# Configuration ShaderGroup
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"),
]
},
}
# Property Group for blocks and textures
class TextureEntry(PropertyGroup):
parameter_id: StringProperty(name="Parameter ID")
type: StringProperty(name="Type", default="texture")
name: StringProperty(name="Texture Name", 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]
tex_entry = self.texture_inputs.add()
tex_entry.parameter_id = param_id
tex_entry.type = tex_type
tex_entry.name = tex_name
def update_material(self, context):
context.area.tag_redraw()
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",
update=update_material
)
texture_inputs: CollectionProperty(type=TextureEntry)
# UI Panel
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 block in scene.material_blocks:
box = layout.box()
box.prop(block, "shader_group")
# Получаем указанный в блоке материал по его имени
material = bpy.data.materials.get(block.material_id)
# Строка для превью и выбора материала
material_row = box.row(align=True)
# Проверяем, существует ли материал, и отображаем его превью
if material:
material_row.template_preview(material)
# Селектор материалов
material_row.prop_search(block, "material_id", bpy.data, "materials", text="Material")
select_op = box.operator("f1_material.select_material", text="Make Active", icon='CHECKMARK')
select_op.material_name = block.material_id
for tex_input in block.texture_inputs:
row = box.row()
row.prop(tex_input, "name", text=f"TextureID ({tex_input.parameter_id})")
import_op = row.operator("f1_material.import_image", text="", icon="IMPORT", emboss=True)
import_op.target_texture = tex_input.name
box.operator("f1_material.remove_block", text="Remove Block")
layout.operator("f1_material.add_block", text="Add Material Block")
# Operators
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 = corresponding_input.name 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}")
print("Export Succeed")
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 Already Image"
filepath: StringProperty(subtype='FILE_PATH')
target_texture: StringProperty()
def execute(self, context):
new_name = os.path.splitext(os.path.basename(self.filepath))[0]
for block in context.scene.material_blocks:
for tex_input in block.texture_inputs:
if tex_input.name == self.target_texture:
tex_input.name = f"#{new_name}.tga"
print(f"Updated texture name to '{new_name}'")
return {'FINISHED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class SelectMaterialOperator(Operator):
bl_idname = "f1_material.select_material"
bl_label = "Select Active Material"
material_name: StringProperty()
def execute(self, context):
if self.material_name in bpy.data.materials:
context.object.active_material = bpy.data.materials[self.material_name]
bpy.context.view_layer.objects.active.active_material = bpy.data.materials[self.material_name]
self.report({'INFO'}, f"Material '{self.material_name}' selected")
else:
self.report({'ERROR'}, f"Material '{self.material_name}' not found!")
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'}
# Registration
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(SelectMaterialOperator)
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(SelectMaterialOperator)
bpy.utils.unregister_class(AddBlockOperator)
bpy.utils.unregister_class(RemoveBlockOperator)
if __name__ == "__main__":
register()
Что изменено:
В MaterialBlock добавлен метод update_material, который вызывает context.area.tag_redraw(). Этот метод заставляет область интерфейса обновляться, что решает проблему с не обновляемым превью после выбора материала.
В свойстве material_id добавлен этот метод в качестве callback при изменении.
Попробуйте эту версию, чтобы увидеть, как превью будет обновляться при выборе материала в списке.
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
from bpy.types import Panel, Operator, PropertyGroup
import xml.etree.ElementTree as ET
from io import BytesIO
# Configuration ShaderGroup
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"),
]
},
}
# Property Group for blocks and textures
class TextureEntry(PropertyGroup):
parameter_id: StringProperty(name="Parameter ID")
type: StringProperty(name="Type", default="texture")
name: StringProperty(name="Texture Name", 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]
tex_entry = self.texture_inputs.add()
tex_entry.parameter_id = param_id
tex_entry.type = tex_type
tex_entry.name = tex_name
def update_material(self, context):
for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D' and area.ui_type == 'VIEW_3D':
area.tag_redraw()
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",
update=update_material
)
texture_inputs: CollectionProperty(type=TextureEntry)
# UI Panel
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 block in scene.material_blocks:
box = layout.box()
box.prop(block, "shader_group")
# Получаем указанный в блоке материал по его имени
material = bpy.data.materials.get(block.material_id)
# Строка для превью и выбора материала
material_row = box.row(align=True)
# Проверяем, существует ли материал, и отображаем его превью
if material:
material_row.template_preview(material)
# Селектор материалов
material_row.prop_search(block, "material_id", bpy.data, "materials", text="Material")
select_op = box.operator("f1_material.select_material", text="Make Active", icon='CHECKMARK')
select_op.material_name = block.material_id
for tex_input in block.texture_inputs:
row = box.row()
row.prop(tex_input, "name", text=f"TextureID ({tex_input.parameter_id})")
import_op = row.operator("f1_material.import_image", text="", icon="IMPORT", emboss=True)
import_op.target_texture = tex_input.name
box.operator("f1_material.remove_block", text="Remove Block")
layout.operator("f1_material.add_block", text="Add Material Block")
# Operators
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 = corresponding_input.name 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}")
print("Export Succeed")
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 Already Image"
filepath: StringProperty(subtype='FILE_PATH')
target_texture: StringProperty()
def execute(self, context):
new_name = os.path.splitext(os.path.basename(self.filepath))[0]
for block in context.scene.material_blocks:
for tex_input in block.texture_inputs:
if tex_input.name == self.target_texture:
tex_input.name = f"#{new_name}.tga"
print(f"Updated texture name to '{new_name}'")
return {'FINISHED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class SelectMaterialOperator(Operator):
bl_idname = "f1_material.select_material"
bl_label = "Select Active Material"
material_name: StringProperty()
def execute(self, context):
if self.material_name in bpy.data.materials:
context.object.active_material = bpy.data.materials[self.material_name]
bpy.context.view_layer.objects.active.active_material = bpy.data.materials[self.material_name]
self.report({'INFO'}, f"Material '{self.material_name}' selected")
else:
self.report({'ERROR'}, f"Material '{self.material_name}' not found!")
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'}
# Registration
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(SelectMaterialOperator)
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(SelectMaterialOperator)
bpy.utils.unregister_class(AddBlockOperator)
bpy.utils.unregister_class(RemoveBlockOperator)
if __name__ == "__main__":
register()
Обновления:
Используем метод update_material для обновления всех областей VIEW_3D, вызывая метод tag_redraw() для каждой из них. Это должно гарантировать, что интерфейс перерисовывается своевременно.
Пожалуйста, протестируйте это и дайте знать, если будут какие-либо проблемы.
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
from bpy.types import Panel, Operator, PropertyGroup
import xml.etree.ElementTree as ET
from io import BytesIO
# Configuration ShaderGroup
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"),
]
},
}
# Property Group for blocks and textures
class TextureEntry(PropertyGroup):
parameter_id: StringProperty(name="Parameter ID")
type: StringProperty(name="Type", default="texture")
name: StringProperty(name="Texture Name", 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]
tex_entry = self.texture_inputs.add()
tex_entry.parameter_id = param_id
tex_entry.type = tex_type
tex_entry.name = tex_name
def update_material(self, context):
bpy.ops.ed.undo_push(message="Update Material")
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",
update=update_material
)
texture_inputs: CollectionProperty(type=TextureEntry)
# UI Panel
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 block in scene.material_blocks:
box = layout.box()
box.prop(block, "shader_group")
# Получаем указанный в блоке материал по его имени
material = bpy.data.materials.get(block.material_id)
# Строка для превью и выбора материала
material_row = box.row(align=True)
# Проверяем, существует ли материал, и отображаем его превью
if material:
material_row.template_preview(material)
# Селектор материалов
material_row.prop_search(block, "material_id", bpy.data, "materials", text="Material")
select_op = box.operator("f1_material.select_material", text="Make Active", icon='CHECKMARK')
select_op.material_name = block.material_id
for tex_input in block.texture_inputs:
row = box.row()
row.prop(tex_input, "name", text=f"TextureID ({tex_input.parameter_id})")
import_op = row.operator("f1_material.import_image", text="", icon="IMPORT", emboss=True)
import_op.target_texture = tex_input.name
box.operator("f1_material.remove_block", text="Remove Block")
layout.operator("f1_material.add_block", text="Add Material Block")
# Operators
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 = corresponding_input.name 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}")
print("Export Succeed")
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 Already Image"
filepath: StringProperty(subtype='FILE_PATH')
target_texture: StringProperty()
def execute(self, context):
new_name = os.path.splitext(os.path.basename(self.filepath))[0]
for block in context.scene.material_blocks:
for tex_input in block.texture_inputs:
if tex_input.name == self.target_texture:
tex_input.name = f"#{new_name}.tga"
print(f"Updated texture name to '{new_name}'")
return {'FINISHED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class SelectMaterialOperator(Operator):
bl_idname = "f1_material.select_material"
bl_label = "Select Active Material"
material_name: StringProperty()
def execute(self, context):
if self.material_name in bpy.data.materials:
context.object.active_material = bpy.data.materials[self.material_name]
bpy.context.view_layer.objects.active.active_material = bpy.data.materials[self.material_name]
self.report({'INFO'}, f"Material '{self.material_name}' selected")
else:
self.report({'ERROR'}, f"Material '{self.material_name}' not found!")
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'}
# Registration
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(SelectMaterialOperator)
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(SelectMaterialOperator)
bpy.utils.unregister_class(AddBlockOperator)
bpy.utils.unregister_class(RemoveBlockOperator)
if __name__ == "__main__":
register()
Что изменилось:
В метод update_material добавлен вызов bpy.ops.ed.undo_push() с целью заставить Blender обновить интерфейс и освежить превью.
Дайте знать, если это работает или если потребуется дальнейшая помощь!
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
# Configuration ShaderGroup
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"),
]
},
}
# Property Group for blocks and textures
class TextureEntry(PropertyGroup):
parameter_id: StringProperty(name="Parameter ID")
type: StringProperty(name="Type", default="texture")
name: StringProperty(name="Texture Name", 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]
tex_entry = self.texture_inputs.add()
tex_entry.parameter_id = param_id
tex_entry.type = tex_type
tex_entry.name = tex_name
def update_material(self, context):
# Меняем фиктивное свойство, чтобы заставить перерисовку
self.dummy_prop += 1
if bpy.context.area:
bpy.context.area.tag_redraw()
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",
update=update_material
)
texture_inputs: CollectionProperty(type=TextureEntry)
dummy_prop: IntProperty(default=0)
# UI Panel
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 block in scene.material_blocks:
box = layout.box()
box.prop(block, "shader_group")
# Получаем указанный в блоке материал по его имени
material = bpy.data.materials.get(block.material_id)
# Строка для превью и выбора материала
material_row = box.row(align=True)
# Проверяем, существует ли материал, и отображаем его превью
if material:
material_row.template_preview(material)
# Селектор материалов
material_row.prop_search(block, "material_id", bpy.data, "materials", text="Material")
select_op = box.operator("f1_material.select_material", text="Make Active", icon='CHECKMARK')
select_op.material_name = block.material_id
for tex_input in block.texture_inputs:
row = box.row()
row.prop(tex_input, "name", text=f"TextureID ({tex_input.parameter_id})")
import_op = row.operator("f1_material.import_image", text="", icon="IMPORT", emboss=True)
import_op.target_texture = tex_input.name
box.operator("f1_material.remove_block", text="Remove Block")
layout.operator("f1_material.add_block", text="Add Material Block")
# Operators
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 = corresponding_input.name 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}")
print("Export Succeed")
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 Already Image"
filepath: StringProperty(subtype='FILE_PATH')
target_texture: StringProperty()
def execute(self, context):
new_name = os.path.splitext(os.path.basename(self.filepath))[0]
for block in context.scene.material_blocks:
for tex_input in block.texture_inputs:
if tex_input.name == self.target_texture:
tex_input.name = f"#{new_name}.tga"
print(f"Updated texture name to '{new_name}'")
return {'FINISHED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class SelectMaterialOperator(Operator):
bl_idname = "f1_material.select_material"
bl_label = "Select Active Material"
material_name: StringProperty()
def execute(self, context):
if self.material_name in bpy.data.materials:
context.object.active_material = bpy.data.materials[self.material_name]
bpy.context.view_layer.objects.active.active_material = bpy.data.materials[self.material_name]
self.report({'INFO'}, f"Material '{self.material_name}' selected")
else:
self.report({'ERROR'}, f"Material '{self.material_name}' not found!")
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'}
# Registration
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(SelectMaterialOperator)
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(SelectMaterialOperator)
bpy.utils.unregister_class(AddBlockOperator)
bpy.utils.unregister_class(RemoveBlockOperator)
if __name__ == "__main__":
register()
Что мы сделали:
Добавили фиктивное свойство (dummy_prop), которое увеличивается при каждом изменении материала. Это может заставить Blender пересчитать и обновить интерфейс.
Проверяется наличие активной области и вызывается tag_redraw() для обновления интерфейса.
Пожалуйста, протестируйте это решение и посмотрите, улучшает ли это ситуацию с обновлением превью.
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
# Configuration ShaderGroup
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"),
]
},
}
# Property Group for blocks and textures
class TextureEntry(PropertyGroup):
parameter_id: StringProperty(name="Parameter ID")
type: StringProperty(name="Type", default="texture")
name: StringProperty(name="Texture Name", 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]
tex_entry = self.texture_inputs.add()
tex_entry.parameter_id = param_id
tex_entry.type = tex_type
tex_entry.name = tex_name
def update_material(self, context):
# Костыль: изменение размеров области
area = context.area
if area:
initial_width = area.width
area.width += 1 # Увеличиваем на 1 пиксель
area.width = initial_width # Возвращаем обратно
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",
update=update_material
)
texture_inputs: CollectionProperty(type=TextureEntry)
# UI Panel
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 block in scene.material_blocks:
box = layout.box()
box.prop(block, "shader_group")
# Получаем указанный в блоке материал по его имени
material = bpy.data.materials.get(block.material_id)
# Строка для превью и выбора материала
material_row = box.row(align=True)
# Проверяем, существует ли материал, и отображаем его превью
if material:
material_row.template_preview(material)
# Селектор материалов
material_row.prop_search(block, "material_id", bpy.data, "materials", text="Material")
select_op = box.operator("f1_material.select_material", text="Make Active", icon='CHECKMARK')
select_op.material_name = block.material_id
for tex_input in block.texture_inputs:
row = box.row()
row.prop(tex_input, "name", text=f"TextureID ({tex_input.parameter_id})")
import_op = row.operator("f1_material.import_image", text="", icon="IMPORT", emboss=True)
import_op.target_texture = tex_input.name
box.operator("f1_material.remove_block", text="Remove Block")
layout.operator("f1_material.add_block", text="Add Material Block")
# Operators
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 = corresponding_input.name 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}")
print("Export Succeed")
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 Already Image"
filepath: StringProperty(subtype='FILE_PATH')
target_texture: StringProperty()
def execute(self, context):
new_name = os.path.splitext(os.path.basename(self.filepath))[0]
for block in context.scene.material_blocks:
for tex_input in block.texture_inputs:
if tex_input.name == self.target_texture:
tex_input.name = f"#{new_name}.tga"
print(f"Updated texture name to '{new_name}'")
return {'FINISHED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class SelectMaterialOperator(Operator):
bl_idname = "f1_material.select_material"
bl_label = "Select Active Material"
material_name: StringProperty()
def execute(self, context):
if self.material_name in bpy.data.materials:
context.object.active_material = bpy.data.materials[self.material_name]
bpy.context.view_layer.objects.active.active_material = bpy.data.materials[self.material_name]
self.report({'INFO'}, f"Material '{self.material_name}' selected")
else:
self.report({'ERROR'}, f"Material '{self.material_name}' not found!")
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'}
# Registration
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(SelectMaterialOperator)
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(SelectMaterialOperator)
bpy.utils.unregister_class(AddBlockOperator)
bpy.utils.unregister_class(RemoveBlockOperator)
if __name__ == "__main__":
register()
Этим способом попытка симулировать изменение размеров области может заставить Blender обновить и изменить содержимое UI. Обратите внимание, что такой подход может работать или может не сработать, в зависимости от специфики вашей конфигурации Blender и элементов интерфейса. Это действительно костыльное решение, но стоит попробовать.