layout.label(text="Convert Track_Line from ai_track.xml to 2DMAP_SPLINE (track map)")
layout.label(text="1. Import progress_track.xml")
layout.label(text="2. Import ai_track.xml")
row = layout.row(align=True)
Привет, слушай, а мы можем сделать такую вещь, чтобы была надпись Tutorial слева значок INFO, а при нажатии на него сворачивался и разворачивался туториал, где мы могли бы вписать туториал текстом?
Assistant
Привет! Да, можно реализовать подобный функционал в пользовательском интерфейсе Blender, используя Python и API Blender. Вы можете создать панель с кнопкой "INFO", которая будет сворачивать и разворачивать текст туториала. Вот пример, как это можно сделать:
def draw(self, context):
layout = self.layout
scene = context.scene
layout.label(text="Progress Track Editor", icon='TEMP')
layout.operator(IMPORT_OT_ai_progress_track_maker.bl_idname, text="Import Track Progress", icon='IMPORT')
layout.operator(EXPORT_OT_ai_progress_track_maker.bl_idname, text="Export Track Progress", icon='EXPORT')
# Раздел для переноса формы сплайна
layout.label(text="Progress Spline Shape Transfer", icon='MOD_REMESH')
layout.label(text="Convert Track_Line from ai_track.xml to 2DMAP_SPLINE (track map)")
layout.label(text="1. Import progress_track.xml")
layout.label(text="2. Import ai_track.xml")
row = layout.row(align=True)
Assistant
User
Assistant
python
import bpy
class TutorialPanel(bpy.types.Panel):
"""Tutorial Panel"""
bl_label = "Tutorial"
bl_idname = "PT_Tutorial"
bl_space_type = 'TEXT_EDITOR' # Можно выбрать другой тип пространства
bl_region_type = 'UI'
bl_category = "Tutorial"
def draw(self, context):
layout = self.layout
# Переменная для сохранения состояния сворачивания/разворачивания
tutorial_props = context.scene.tutorial_props
row = layout.row()
row.prop(tutorial_props, "expand", text="Tutorial", icon='INFO', emboss=True)
# Проверяем состояние сворачивания/разворачивания
if tutorial_props.expand:
layout.label(text="Convert Track_Line from ai_track.xml to 2DMAP_SPLINE (track map)")
layout.label(text="1. Import progress_track.xml")
layout.label(text="2. Import ai_track.xml")
# Здесь можете добавить дополнительный текст туториала
class TutorialProperties(bpy.types.PropertyGroup):
expand: bpy.props.BoolProperty(name="Expand", default=False)
def register():
bpy.utils.register_class(TutorialPanel)
bpy.utils.register_class(TutorialProperties)
bpy.types.Scene.tutorial_props = bpy.props.PointerProperty(type=TutorialProperties)
def unregister():
bpy.utils.unregister_class(TutorialPanel)
bpy.utils.unregister_class(TutorialProperties)
del bpy.types.Scene.tutorial_props
if __name__ == "__main__":
register()
Этот код создаёт панель с надписью "Tutorial" и значком INFO. При нажатии на значок, туториал будет сворачиваться и разворачиваться. Вы также можете добавлять дополнительные инструкции или объяснения в соответствующем месте.
Не забудьте сохранить этот код в текстовом редакторе Blender и выполнить его для регистрации панельки. После этого панель появится в выбранном пространстве (в данном случае в текстовом редакторе). Если эти настройки вам не подходят, просто измените bl_space_type на необходимый.
уже есть оператор, вшей сюда плиз
Конечно! Чтобы добавить возможность сворачивания и разворачивания текста туториала без создания дополнительной панели, вы можете использовать свойство BoolProperty для отслеживания состояния сворачивания. Давайте интегрируем это в ваш существующий код.
Вот пример, модифицированный под ваш класс VIEW3D_PT_ai_progress_track_maker_panel:
python
import bpy
class VIEW3D_PT_ai_progress_track_maker_panel(bpy.types.Panel):
bl_label = "F1 Track AI Progress Maker"
bl_idname = "VIEW3D_PT_ai_progress_track_maker"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'F1 Track Builder Toolkit'
@classmethod
def poll(cls, context):
return context.scene is not None
def draw(self, context):
layout = self.layout
scene = context.scene
# Добавляем кнопку для сворачивания/разворачивания туториала
layout.label(text="Progress Track Editor", icon='TEMP')
layout.operator(IMPORT_OT_ai_progress_track_maker.bl_idname, text="Import Track Progress", icon='IMPORT')
layout.operator(EXPORT_OT_ai_progress_track_maker.bl_idname, text="Export Track Progress", icon='EXPORT')
# Раздел для переноса формы сплайна
layout.label(text="Progress Spline Shape Transfer", icon='MOD_REMESH')
# Свойство для сворачивания/разворачивания туториала
layout.prop(scene, "tutorial_expanded", text="Tutorial", icon='INFO', emboss=True)
# Если свойство расширено, показываем текст туториала
if scene.tutorial_expanded:
layout.label(text="Convert Track_Line from ai_track.xml to 2DMAP_SPLINE (track map)")
layout.label(text="1. Import progress_track.xml")
layout.label(text="2. Import ai_track.xml")
row = layout.row(align=True)
# Регистрация свойства
def register():
bpy.utils.register_class(VIEW3D_PT_ai_progress_track_maker_panel)
bpy.types.Scene.tutorial_expanded = bpy.props.BoolProperty(name="Tutorial Expanded", default=False)
def unregister():
bpy.utils.unregister_class(VIEW3D_PT_ai_progress_track_maker_panel)
del bpy.types.Scene.tutorial_expanded
if __name__ == "__main__":
register()
В этом коде мы добавили:
Свойство tutorial_expanded: Это свойство для отслеживания, развернут ли туториал или свёрнут.
Метод layout.prop: Визуально добавляем кнопку с иконкой INFO, которая влияет на состояние tutorial_expanded.
Проверка состояния: Если tutorial_expanded истинно, отображается текст туториала.
Теперь, когда вы выполните этот код, в вашем интерфейсе Blender будет возможность развернуть и свернуть туториал, просто нажав на кнопку с иконкой INFO.
@classmethod
def poll(cls, context):
return context.scene is not None
def draw(self, context):
layout = self.layout
scene = context.scene
layout.label(text="Progress Track Editor", icon='TEMP')
layout.operator(IMPORT_OT_ai_progress_track_maker.bl_idname, text="Import Track Progress", icon='IMPORT')
layout.operator(EXPORT_OT_ai_progress_track_maker.bl_idname, text="Export Track Progress", icon='EXPORT')
# Раздел для переноса формы сплайна
layout.label(text="Progress Spline Shape Transfer", icon='MOD_REMESH')
layout.prop(scene, "tutorial_expanded", text="Tutorial", icon='INFO', emboss=True)
# Если свойство расширено, показываем текст туториала
if scene.tutorial_expanded:
layout.label(text="Convert Track_Line from ai_track.xml to 2DMAP_SPLINE (track map)")
layout.label(text="1. Import progress_track.xml")
layout.label(text="2. Import ai_track.xml")
row = layout.row(align=True)
row.prop_search(scene, "twodmap_spline_target", bpy.data, "objects", text="")
twodmap_transfer_op = row.operator(TransferShapeProgressOperator.bl_idname, text="Transfer", icon='ARROW_LEFTRIGHT')
twodmap_transfer_op.source_curve_name = "2DMAP_SPLINE"
twodmap_transfer_op.target_curve_name = scene.twodmap_spline_target
#layout.operator(CreateTargetProgress.bl_idname, text="Add New Target Spline", icon='MOD_LINEART')#
# Селектор для выбора нового меша
layout.label(text="Convert 2DMAP_SPLINE to PROGRESS_MODEL (3D MESH)")
row = layout.row(align=True)
row.prop_search(scene, "new_shape_target", bpy.data, "objects", text="")
transfer_operator = row.operator(TRANSFER_OT_progress_mesh_shape_transfer.bl_idname, text="Transfer", icon='ARROW_LEFTRIGHT')
layout.prop(scene, "track_width", text="Width Track")
# Кнопка Конверт
#layout.operator(CONVERT_OT_2dmap_to_mesh.bl_idname, text="Convert 2DMAP_SPLINE TO MESH", icon='ORIENTATION_NORMAL')
# Раздел для управления воротами
layout.label(text="Manage Gates", icon='NLA_PUSHDOWN')
box = layout.box()
box.prop(scene, "show_gates", icon="TRIA_DOWN" if scene.show_gates else "TRIA_RIGHT", emboss=False, text="Show Gates")
if scene.show_gates:
combined_mesh_object = bpy.context.scene.objects.get("PROGRESS_MODEL")
if combined_mesh_object:
vertices = combined_mesh_object.data.vertices
num_vertices = len(vertices)
# Генерация кнопок "Gate ID" в ряд по 4 кнопки в строке
for i in range(0, num_vertices, 4 * 2): # шаг 4*2, так как у нас пары вершин
row = layout.row(align=True) # Каждая новая строка
for j in range(4):
index = i + j * 2 # Каждый гейт соответствует паре вершин
if index < num_vertices:
gate_op = row.operator("spline.select_gate", text=f"Gate {index // 2}")
gate_op.point_index = index // 2 # Индекс для ворот
# Прерываем, если дошли до конца
if index >= num_vertices - 1:
break
# Новый раздел для сплитов
box = layout.box()
box.label(text="Track Splits", icon='SNAP_PEEL_OBJECT')
temp_filepath = context.scene.get("temp_ai_progress_file", "")
if temp_filepath:
try:
tree = ET.parse(temp_filepath)
root = tree.getroot()
route_element = root.find('.//routes/route[@id="0"]')
if route_element:
for split_element in route_element.findall('.//split'):
split_id = split_element.get("id")
split_type = split_element.get("type").capitalize()
gate_id = split_element.get("gate")
row = box.row()
row.label(text=f"{split_id} {split_type} / Gate {gate_id}")
select_op = row.operator(SPLINE_OT_select_split_gate.bl_idname, text="Select Gate", icon='RESTRICT_SELECT_OFF')
select_op.split_gate_idx = int(gate_id)
new_gate_op = row.operator(SPLINE_OT_new_split_gate.bl_idname, text="New Gate", icon='FILE_REFRESH')
new_gate_op.split_idx = int(split_id)
except ET.ParseError:
box.label(text="Error reading XML file.")
Мне надо чтобы раскрывающаяся кнопка взяла в себя только часть с текстом туториала, а row.prop_search(scene, "twodmap_spline_target", bpy.data, "objects", text="")
twodmap_transfer_op = row.operator(TransferShapeProgressOperator.bl_idname, text="Transfer", icon='ARROW_LEFTRIGHT')
twodmap_transfer_op.source_curve_name = "2DMAP_SPLINE"
twodmap_transfer_op.target_curve_name = scene.twodmap_spline_target
и всё что ниже оставить раскрытым. пожалуйста
Конечно! Чтобы выделить часть с текстом туториала и сделать её сворачиваемой, вы можете использовать контейнер box для располагаемых элементов и оставшуюся часть интерфейса отдельно. Таким образом, сворачивающаяся секция будет только под текстом туториала, а остальная часть будет оставаться открытой.
Вот как можно изменить ваш код:
python
import bpy
class VIEW3D_PT_ai_progress_track_maker_panel(bpy.types.Panel):
bl_label = "F1 Track AI Progress Maker"
bl_idname = "VIEW3D_PT_ai_progress_track_maker"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'F1 Track Builder Toolkit'
@classmethod
def poll(cls, context):
return context.scene is not None
def draw(self, context):
layout = self.layout
scene = context.scene
layout.label(text="Progress Track Editor", icon='TEMP')
layout.operator(IMPORT_OT_ai_progress_track_maker.bl_idname, text="Import Track Progress", icon='IMPORT')
layout.operator(EXPORT_OT_ai_progress_track_maker.bl_idname, text="Export Track Progress", icon='EXPORT')
# Раздел для переноса формы сплайна
layout.label(text="Progress Spline Shape Transfer", icon='MOD_REMESH')
# Оборачиваем в box для туториала
box = layout.box()
layout.prop(scene, "tutorial_expanded", text="Tutorial", icon='INFO', emboss=True)
if scene.tutorial_expanded:
box.label(text="Convert Track_Line from ai_track.xml to 2DMAP_SPLINE (track map)")
box.label(text="1. Import progress_track.xml")
box.label(text="2. Import ai_track.xml")
row = layout.row(align=True)
row.prop_search(scene, "twodmap_spline_target", bpy.data, "objects", text="")
twodmap_transfer_op = row.operator(TransferShapeProgressOperator.bl_idname, text="Transfer", icon='ARROW_LEFTRIGHT')
twodmap_transfer_op.source_curve_name = "2DMAP_SPLINE"
twodmap_transfer_op.target_curve_name = scene.twodmap_spline_target
# Селектор для выбора нового меша
layout.label(text="Convert 2DMAP_SPLINE to PROGRESS_MODEL (3D MESH)")
row = layout.row(align=True)
row.prop_search(scene, "new_shape_target", bpy.data, "objects", text="")
transfer_operator = row.operator(TRANSFER_OT_progress_mesh_shape_transfer.bl_idname, text="Transfer", icon='ARROW_LEFTRIGHT')
layout.prop(scene, "track_width", text="Width Track")
# Раздел для управления воротами
layout.label(text="Manage Gates", icon='NLA_PUSHDOWN')
box = layout.box()
box.prop(scene, "show_gates", icon="TRIA_DOWN" if scene.show_gates else "TRIA_RIGHT", emboss=False, text="Show Gates")
if scene.show_gates:
combined_mesh_object = bpy.context.scene.objects.get("PROGRESS_MODEL")
if combined_mesh_object:
vertices = combined_mesh_object.data.vertices
num_vertices = len(vertices)
# Генерация кнопок "Gate ID" в ряд по 4 кнопки в строке
for i in range(0, num_vertices, 4 * 2): # шаг 4*2, так как у нас пары вершин
row = layout.row(align=True) # Каждая новая строка
for j in range(4):
index = i + j * 2 # Каждый гейт соответствует паре вершин
if index < num_vertices:
gate_op = row.operator("spline.select_gate", text=f"Gate {index // 2}")
gate_op.point_index = index // 2 # Индекс для ворот
# Прерываем, если дошли до конца
if index >= num_vertices - 1:
break
# Новый раздел для сплитов
box = layout.box()
box.label(text="Track Splits", icon='SNAP_PEEL_OBJECT')
temp_filepath = context.scene.get("temp_ai_progress_file", "")
if temp_filepath:
try:
tree = ET.parse(temp_filepath)
root = tree.getroot()
route_element = root.find('.//routes/route[@id="0"]')
if route_element:
for split_element in route_element.findall('.//split'):
split_id = split_element.get("id")
split_type = split_element.get("type").capitalize()
gate_id = split_element.get("gate")
row = box.row()
row.label(text=f"{split_id} {split_type} / Gate {gate_id}")
select_op = row.operator(SPLINE_OT_select_split_gate.bl_idname, text="Select Gate", icon='RESTRICT_SELECT_OFF')
select_op.split_gate_idx = int(gate_id)
new_gate_op = row.operator(SPLINE_OT_new_split_gate.bl_idname, text="New Gate", icon='FILE_REFRESH')
new_gate_op.split_idx = int(split_id)
except ET.ParseError:
box.label(text="Error reading XML file.")
def register():
bpy.utils.register_class(VIEW3D_PT_ai_progress_track_maker_panel)
bpy.types.Scene.tutorial_expanded = bpy.props.BoolProperty(name="Tutorial Expanded", default=False)
def unregister():
bpy.utils.unregister_class(VIEW3D_PT_ai_progress_track_maker_panel)
del bpy.types.Scene.tutorial_expanded
if __name__ == "__main__":
register()
Основные изменения:
Используйте box для текстов туториала, чтобы они были сворачиваемыми и отображались только при необходимости.
Всё, что идет после блока туториала, остаётся вне if scene.tutorial_expanded, чтобы оставшаяся часть интерфейса всегда оставалась открытой.
Теперь при сворачивании/разворачивании будет показываться только текст туториала, а всё остальное будет оставаться доступным в интерфейсе.