【Blender】ハイポリのシェイプキーをローポリに複製する

投稿者: | 2024-04-09

ハイポリメッシュのシェイプキーをローポリメッシュに複製してみました。アドオンをインストールして使用します。

概要

ローポリメッシュの頂点を走査し、指定の範囲内にあるハイポリメッシュの頂点リストを記憶します。ハイポリメッシュをシェイプキーで変形した後の頂点の平均値を新しい頂点位置として、ローポリメッシュにシェイプキーを作成します。

スクリプト

__init__.py

  1. # -*- coding: utf-8 -*-
  2.  
  3. bl_info = {
  4. "name": "ShapeKey Transmuter",
  5. "description": "Transfers shape keys between meshes based on vertex proximity.",
  6. "author": "Your Name",
  7. "version": (1, 0),
  8. "blender": (2, 93, 0),
  9. "location": "View3D > Sidebar > Tools Tab",
  10. "category": "Object"
  11. }
  12.  
  13.  
  14. import bpy
  15. from .main_logic import perform_action
  16.  
  17. def get_vertex_groups(self, context):
  18. items = [('NONE', "None", "")]
  19. if self.target_object:
  20. items.extend([(vg.name, vg.name, "") for vg in self.target_object.vertex_groups])
  21. return items
  22.  
  23. def get_shape_keys(self, context):
  24. items = []
  25. if self.source_object and self.source_object.data.shape_keys:
  26. for key in self.source_object.data.shape_keys.key_blocks:
  27. items.append((key.name, key.name, ""))
  28. return items
  29.  
  30. class ShapeKeyToolProperties(bpy.types.PropertyGroup):
  31. radius: bpy.props.FloatProperty(name="Radius")
  32. source_object : bpy.props.PointerProperty(
  33. name="Source Object",
  34. type=bpy.types.Object,
  35. poll=lambda self, object: object.type == 'MESH'
  36. )
  37. target_object : bpy.props.PointerProperty(
  38. name="Target Object",
  39. type=bpy.types.Object,
  40. poll=lambda self, object: object.type == 'MESH'
  41. )
  42. vertex_group: bpy.props.EnumProperty(name="Vertex Group", items=get_vertex_groups)
  43. shape_key: bpy.props.EnumProperty(name="Shape Key", items=get_shape_keys)
  44.  
  45.  
  46. class SKT_ShapeKeyOperator(bpy.types.Operator):
  47. bl_idname = "object.skt_shape_key_operator"
  48. bl_label = "Apply Shape Key"
  49.  
  50. @classmethod
  51. def poll(cls, context):
  52. props = context.scene.shape_key_tool_props
  53. # オブジェクト、シェイプキー、頂点グループが適切に選択されていることを確認
  54. return props.source_object and props.target_object and props.shape_key and props.vertex_group
  55.  
  56. def execute(self, context):
  57. perform_action(context)
  58. return {'FINISHED'}
  59.  
  60.  
  61. class SKT_SimplePanel(bpy.types.Panel):
  62. bl_label = "ShapeKey Transmuter Panel"
  63. bl_idname = "OBJECT_PT_custom"
  64. bl_space_type = 'VIEW_3D'
  65. bl_region_type = 'UI'
  66. bl_category = 'Tools'
  67.  
  68. def draw(self, context):
  69. layout = self.layout
  70. tool_props = context.scene.shape_key_tool_props
  71. layout.prop(tool_props, "source_object")
  72. if tool_props.source_object:
  73. layout.prop(tool_props, "shape_key")
  74. layout.prop(tool_props, "target_object")
  75. if tool_props.target_object:
  76. layout.prop(tool_props, "vertex_group")
  77. layout.prop(tool_props, "radius")
  78. layout.operator("object.skt_shape_key_operator")
  79.  
  80. # カスタムプロパティをシーンに追加
  81. def register():
  82. bpy.utils.register_class(ShapeKeyToolProperties)
  83. bpy.types.Scene.shape_key_tool_props = bpy.props.PointerProperty(type=ShapeKeyToolProperties)
  84. bpy.utils.register_class(SKT_SimplePanel)
  85. bpy.utils.register_class(SKT_ShapeKeyOperator)
  86. # その他の登録処理
  87.  
  88. def unregister():
  89. del bpy.types.Scene.shape_key_tool_props
  90. bpy.utils.unregister_class(ShapeKeyToolProperties)
  91. bpy.utils.unregister_class(SKT_SimplePanel)
  92. bpy.utils.unregister_class(SKT_ShapeKeyOperator)
  93. # その他の解除処理
  94.  
  95. if __name__ == "__main__":
  96. register()

main_logic.py

  1. import bpy
  2. import bmesh
  3. from mathutils import Vector
  4. import numpy as np
  5.  
  6. def perform_action(context):
  7. # シェイプキー名をプロパティから取得
  8. shape_key_name = context.scene.shape_key_tool_props.shape_key
  9.  
  10. if not shape_key_name:
  11. # 適切なシェイプキーが設定されていない場合のエラー処理
  12. raise Exception("シェイプキーが設定されていません。")
  13.  
  14. # ターゲットメッシュ(変更対象)とソースメッシュ(変更元)を決定
  15. target_mesh = context.scene.shape_key_tool_props.target_object
  16. source_mesh = context.scene.shape_key_tool_props.source_object
  17.  
  18. if not target_mesh or target_mesh.type != 'MESH':
  19. raise Exception("ターゲットオブジェクトが適切に設定されていないか、メッシュタイプではありません。")
  20.  
  21. if not source_mesh or source_mesh.type != 'MESH':
  22. raise Exception("ソースオブジェクトが適切に設定されていないか、メッシュタイプではありません。")
  23.  
  24.  
  25. # メッシュデータを取得
  26. target_bmesh = bmesh.new()
  27. target_bmesh.from_mesh(target_mesh.data)
  28. source_bmesh = bmesh.new()
  29. source_bmesh.from_mesh(source_mesh.data)
  30.  
  31. # 頂点の影響範囲を定義
  32. radius = context.scene.shape_key_tool_props.radius
  33.  
  34. # 頂点グループを取得
  35. vertex_group_name = context.scene.shape_key_tool_props.vertex_group
  36.  
  37. # 頂点グループが設定されていることを確認
  38. if not vertex_group_name:
  39. raise Exception("頂点グループが設定されていません。")
  40.  
  41. # ユーザーが「None」を選択した場合は全頂点を対象とする
  42. if vertex_group_name != 'NONE':
  43. vertex_group = target_mesh.vertex_groups.get(vertex_group_name)
  44. if vertex_group:
  45. vgroup_indices = {v.index for v in target_mesh.data.vertices if vertex_group.index in [g.group for g in v.groups]}
  46. else:
  47. vgroup_indices = set(range(len(target_mesh.data.vertices)))
  48.  
  49.  
  50. # 全てのシェイプキーを0に設定
  51. for key_block in source_mesh.data.shape_keys.key_blocks:
  52. key_block.value = 0.0
  53. # 頂点グループを考慮して半径内の対応する頂点を探す
  54. vertex_groups = [[] for _ in range(len(target_bmesh.verts))]
  55. for i, target_vert in enumerate(target_bmesh.verts):
  56. if target_vert.index in vgroup_indices:
  57. closest_vert = None
  58. min_dist = float('inf')
  59. for source_vert in source_bmesh.verts:
  60. dist = (target_vert.co - source_vert.co).length
  61. if dist <= radius:
  62. vertex_groups[i].append(source_vert.index)
  63. elif dist < min_dist:
  64. min_dist = dist
  65. closest_vert = source_vert
  66. if not vertex_groups[i]:
  67. vertex_groups[i].append(closest_vert.index)
  68.  
  69. # 指定されたシェイプキーのみを1に設定
  70. source_mesh.data.shape_keys.key_blocks[shape_key_name].value = 1.0
  71. source_mesh.data.update()
  72.  
  73. # 新しい頂点位置を計算
  74. new_vertex_positions = [None] * len(target_bmesh.verts)
  75. for target_vert, group in zip(target_bmesh.verts, vertex_groups):
  76. if target_vert.index in vgroup_indices and group:
  77. total_position = Vector((0.0, 0.0, 0.0))
  78. for vert_idx in group:
  79. shaped_vert = source_mesh.data.shape_keys.key_blocks[shape_key_name].data[vert_idx].co
  80. total_position += shaped_vert
  81. average_position = total_position / len(group)
  82. new_position = average_position
  83. new_vertex_positions[target_vert.index] = new_position
  84. elif target_vert.index in vgroup_indices:
  85. new_vertex_positions[target_vert.index] = target_vert.co
  86.  
  87. # ターゲットメッシュのシェイプキーデータを確認し、必要に応じてBasisキーを作成
  88. if not target_mesh.data.shape_keys:
  89. target_mesh.shape_key_add(name='Basis')
  90.  
  91. # 新しいシェイプキーを追加
  92. new_shape_key = target_mesh.shape_key_add(name=shape_key_name)
  93.  
  94.  
  95. # 新規シェイプキーに頂点位置を適用
  96. for vert_idx, new_pos in enumerate(new_vertex_positions):
  97. if new_pos:
  98. new_shape_key.data[vert_idx].co = new_pos
  99.  
  100. # ソースメッシュのシェイプキーの値を0に設定
  101. source_mesh.data.shape_keys.key_blocks[shape_key_name].value = 0.0
  102. source_mesh.data.update()
  103.  
  104. # 解放処理
  105. target_bmesh.free()
  106. source_bmesh.free()
  107.  
  108. # すべてのオブジェクトの選択を解除
  109. bpy.ops.object.select_all(action='DESELECT')
  110.  
  111. # ターゲットメッシュだけを選択
  112. target_mesh.select_set(True)
  113. context.view_layer.objects.active = target_mesh
  114.  
  115.  

設定

上記のpyファイルのみを含んだフォルダを作ります。

フォルダを圧縮してzipファイルにします。

Blenderで、Edit > Preferences... を開きます。

Add-onsで「Install...」ボタンから、zipファイルをインストールします。

チェックボックスを入れてアドオンを有効化します。

横の▷をクリックするとアドオンの情報が開きます。「Remove」ボタンでアドオンを削除できます。

3Dビューポートのサイドバーの「Tools」タブにパネルが表示されます。

使い方

BlenderでMonkeyを2つ追加しました。

片方はDecimateモディファイアが適用されていて、ポリゴン数が減っています。

ハイポリメッシュにシェイプキーを追加して、表情を作ります。

パネルの「Source Object」にハイポリメッシュを設定し、「Target Object」にローポリメッシュを設定します。

「Shape Key」で、追加したシェイプキーを選択します。

「Radius」を設定して、Applyボタンを押します。

ローポリメッシュにシェイプキーが追加されます。

シェイプキーのValueを1にすると、ハイポリメッシュに設定した表情になりました。

ローポリ
ハイポリ

頂点グループを適用

ローポリメッシュに頂点グループを追加します。

編集モードで一部の頂点のみを選択します。

頂点グループにウェイト1で割り当てます。

パネルの「Vertex Group」でこの頂点グループを選択します。

Applyボタンを押すと、再度シェイプキーが追加されます。頂点グループに適用した部分のみが変形します。

Key 1.001
Key 1

これでハイポリメッシュからローポリメッシュへシェイプキーを複製できました。

プロパティ

パネルで設定するオブジェクト参照や各値はプロパティに設定されます。オブジェクトのプロパティはメッシュタイプのオブジェクトだけを受け入れます。

  1. class ShapeKeyToolProperties(bpy.types.PropertyGroup):
  2. radius: bpy.props.FloatProperty(name="Radius")
  3. source_object : bpy.props.PointerProperty(
  4. name="Source Object",
  5. type=bpy.types.Object,
  6. poll=lambda self, object: object.type == 'MESH'
  7. )
  8. target_object : bpy.props.PointerProperty(
  9. name="Target Object",
  10. type=bpy.types.Object,
  11. poll=lambda self, object: object.type == 'MESH'
  12. )
  13. vertex_group: bpy.props.EnumProperty(name="Vertex Group", items=get_vertex_groups)
  14. shape_key: bpy.props.EnumProperty(name="Shape Key", items=get_shape_keys)
  15.  
  16. # ...
  17.  
  18. def register():
  19. bpy.utils.register_class(ShapeKeyToolProperties)
  20. bpy.types.Scene.shape_key_tool_props = bpy.props.PointerProperty(type=ShapeKeyToolProperties)

現在のシーンのコンテキストを使用して、プロパティグループ内のプロパティの値を取得できます。

  1. target_mesh = context.scene.shape_key_tool_props.target_object
  2. source_mesh = context.scene.shape_key_tool_props.source_object

スクリプト

シェイプキーやオブジェクト、半径などのプロパティ値を取得します。オブジェクトからメッシュデータを作成します。

  1. import bpy
  2. import bmesh
  3. from mathutils import Vector
  4. import numpy as np
  5.  
  6. def perform_action(context):
  7. # シェイプキー名をプロパティから取得
  8. shape_key_name = context.scene.shape_key_tool_props.shape_key
  9.  
  10. if not shape_key_name:
  11. # 適切なシェイプキーが設定されていない場合のエラー処理
  12. raise Exception("シェイプキーが設定されていません。")
  13.  
  14. # ターゲットメッシュ(変更対象)とソースメッシュ(変更元)を決定
  15. target_mesh = context.scene.shape_key_tool_props.target_object
  16. source_mesh = context.scene.shape_key_tool_props.source_object
  17.  
  18. if not target_mesh or target_mesh.type != 'MESH':
  19. raise Exception("ターゲットオブジェクトが適切に設定されていないか、メッシュタイプではありません。")
  20.  
  21. if not source_mesh or source_mesh.type != 'MESH':
  22. raise Exception("ソースオブジェクトが適切に設定されていないか、メッシュタイプではありません。")
  23.  
  24.  
  25. # メッシュデータを取得
  26. target_bmesh = bmesh.new()
  27. target_bmesh.from_mesh(target_mesh.data)
  28. source_bmesh = bmesh.new()
  29. source_bmesh.from_mesh(source_mesh.data)
  30.  
  31. # 頂点の影響範囲を定義
  32. radius = context.scene.shape_key_tool_props.radius

頂点グループを取得します。パネルで「None」が選択されていると頂点グループを使用しません。

  1. # 頂点グループを取得
  2. vertex_group_name = context.scene.shape_key_tool_props.vertex_group
  3.  
  4. # 頂点グループが設定されていることを確認
  5. if not vertex_group_name:
  6. raise Exception("頂点グループが設定されていません。")
  7.  
  8. # ユーザーが「None」を選択した場合は全頂点を対象とする
  9. if vertex_group_name != 'NONE':
  10. vertex_group = target_mesh.vertex_groups.get(vertex_group_name)
  11. if vertex_group:
  12. vgroup_indices = {v.index for v in target_mesh.data.vertices if vertex_group.index in [g.group for g in v.groups]}
  13. else:
  14. vgroup_indices = set(range(len(target_mesh.data.vertices)))

ハイポリメッシュの全てのシェイプキーの値を0にします。

  1. # 全てのシェイプキーを0に設定
  2. for key_block in source_mesh.data.shape_keys.key_blocks:
  3. key_block.value = 0.0

ローポリメッシュの頂点ごとに頂点リストを保持します。ハイポリメッシュの頂点を走査し、距離が半径以下ならリストに追加します。範囲内になければもっとも近くの頂点を追加しています。シェイプキーでの変形を追跡できるようにインデックスを記憶しています。

  1. # 頂点グループを考慮して半径内の対応する頂点を探す
  2. vertex_groups = [[] for _ in range(len(target_bmesh.verts))]
  3. for i, target_vert in enumerate(target_bmesh.verts):
  4. if target_vert.index in vgroup_indices:
  5. closest_vert = None
  6. min_dist = float('inf')
  7. for source_vert in source_bmesh.verts:
  8. dist = (target_vert.co - source_vert.co).length
  9. if dist <= radius:
  10. vertex_groups[i].append(source_vert.index)
  11. elif dist < min_dist:
  12. min_dist = dist
  13. closest_vert = source_vert
  14. if not vertex_groups[i]:
  15. vertex_groups[i].append(closest_vert.index)

ハイポリメッシュのシェイプキーの値を1にします。シェイプキーはパネルで設定されています。

  1. # 指定されたシェイプキーのみを1に設定
  2. source_mesh.data.shape_keys.key_blocks[shape_key_name].value = 1.0
  3. source_mesh.data.update()

ローポリメッシュの頂点を一つずつ見ていって、リスト内の現在の頂点位置の平均値を新しい頂点位置にします。リスト内の頂点の位置はシェイプキーの値によって移動されています。

  1. # 新しい頂点位置を計算
  2. new_vertex_positions = [None] * len(target_bmesh.verts)
  3. for target_vert, group in zip(target_bmesh.verts, vertex_groups):
  4. if target_vert.index in vgroup_indices and group:
  5. total_position = Vector((0.0, 0.0, 0.0))
  6. for vert_idx in group:
  7. shaped_vert = source_mesh.data.shape_keys.key_blocks[shape_key_name].data[vert_idx].co
  8. total_position += shaped_vert
  9. average_position = total_position / len(group)
  10. new_position = average_position
  11. new_vertex_positions[target_vert.index] = new_position
  12. elif target_vert.index in vgroup_indices:
  13. new_vertex_positions[target_vert.index] = target_vert.co

ローポリメッシュに、指定のシェイプキーと同じ名前のシェイプキーを追加します。Basisがなければ作成します。

  1. # ターゲットメッシュのシェイプキーデータを確認し、必要に応じてBasisキーを作成
  2. if not target_mesh.data.shape_keys:
  3. target_mesh.shape_key_add(name='Basis')
  4.  
  5. # 新しいシェイプキーを追加
  6. new_shape_key = target_mesh.shape_key_add(name=shape_key_name)

作成した頂点をシェイプキーに適用します。

  1. # 新規シェイプキーに頂点位置を適用
  2. for vert_idx, new_pos in enumerate(new_vertex_positions):
  3. if new_pos:
  4. new_shape_key.data[vert_idx].co = new_pos

最後にシェイプキーの値を0に戻したり、メモリの解放、選択解除などを行っています。

  1. # ソースメッシュのシェイプキーの値を0に設定
  2. source_mesh.data.shape_keys.key_blocks[shape_key_name].value = 0.0
  3. source_mesh.data.update()
  4.  
  5. # 解放処理
  6. target_bmesh.free()
  7. source_bmesh.free()
  8.  
  9. # すべてのオブジェクトの選択を解除
  10. bpy.ops.object.select_all(action='DESELECT')
  11.  
  12. # ターゲットメッシュだけを選択
  13. target_mesh.select_set(True)
  14. context.view_layer.objects.active = target_mesh

コメントを残す

メールアドレスが公開されることはありません。