Blenderでモデリングを行う上でアドオンを利用することで手間と時間を大幅に短縮できます。

bpyを用いてテキストベースでモデリングを行う上でも同様に使用できるように、アドオンの基本情報の入力だけで容易にアドオンのインストールと有効化を行うことができるようにしたのでまとめます。


 動作確認環境 : Blender 4.2


bpyによるadd-onのインストールと有効化

  • アドオンのインストールURL
  • アドオン名
  • アドオンの格納先
を指定することで、自動的にインストールおよび有効化を行えるようにしておきます。

Python :
def install_and_enable_addon(
        addon_directory                         # 格納ディレクトリ
    ,   url                                     # ダウンロードURL
    ,   addon_name                              # アドオン名
    ,   addon_name_head="bl_ext.blender_org."   # アドオン名接頭辞
    ):
    # 保存先ZIPファイルのパス
    local_zip_path = os.path.join(addon_directory, 'addon.zip')
    # アドオンのインストール先パス
    addon_path = os.path.join(addon_directory, addon_name)
    # アドオンがすでにインストールされている場合
    if os.path.exists(addon_path):
        print(f"Addon '{addon_name}' already exists. Skipping download and installation.")
        # アドオン有効化
        addon_name = addon_name_head + addon_name
        if addon_name in bpy.context.preferences.addons:
            print(f"Addon '{addon_name}' is already enabled.")
        else:
            try:
                # アドオン有効化
                bpy.ops.preferences.addon_enable(module=addon_name)
                print(f"Addon '{addon_name}' enabled successfully.")
            except RuntimeError as e:
                print(f"Failed to enable addon '{addon_name}': {e}")
        return
    else:
        # URLからZIPファイルダウンロード
        try:
            response = requests.get(url, stream=True)
            response.raise_for_status()  # HTTPエラーチェック
            with open(local_zip_path, 'wb') as file:
                for chunk in response.iter_content(chunk_size=8192):
                    file.write(chunk)
            print("Download completed.")
        except requests.exceptions.RequestException as e:
            print(f"Failed to download file: {e}")
            return
        # ZIPファイル解凍
        try:
            with zipfile.ZipFile(local_zip_path, 'r') as zip_ref:
                zip_ref.extractall(addon_directory+"/"+addon_name)
            print("Extraction completed.")
        except zipfile.BadZipFile as e:
            print(f"Failed to extract ZIP file: {e}")
            return
        # ZIPファイルを削除
        os.remove(local_zip_path)
        # アドオン有効化
        addon_name = addon_name_head + addon_name
        if addon_name not in bpy.context.preferences.addons:
            try:
                bpy.ops.preferences.addon_enable(module=addon_name)
                print(f"Addon '{addon_name}' enabled successfully.")
            except RuntimeError as e:
                print(f"Failed to enable addon '{addon_name}': {e}")
        else:
            print(f"Addon '{addon_name}' is already enabled.")

12行目 :
アドオンがすでにインストールされている場合、アドオンの有効化だけを行います。

26行目 :
  • アドオンがインストールされていない場合、
  • URLからファイルをダウンロード
  • ZIPファイルを解凍
  • ZIPファイルを削除
  • アドオンの有効化
までを行います。


bpyによるadd-on使用例

 アドオンの"sapling-tree-gen"を使用して、以下のような植物を生成するコードを例にあげて使い方を示します。

Python :
# Extensions Download Directry
addon_directory = "C:/Users/Username/AppData/Roaming/Blender Foundation/Blender/4.2/extensions/blender_org"

def Base_create():
    bpy.ops.object.mode_set(mode='OBJECT')

    # Extensions(アドオン)追加
    addon_url = "https://extensions.blender.org/download/sha256:49a1c484cd1cf535901f65f1425f06812bbef6c329a6cb1eb741b35c8ea17c06/add-on-sapling-tree-gen-v0.3.6.zip"
    addon_name = "sapling_tree_gen"
    install_and_enable_addon(
        addon_directory # 格納ディレクトリ
    ,   addon_url       # ダウンロードURL
    ,   addon_name      # アドオン名(ディレクトリ名)
    )

    # Tree 追加
    bpy.ops.curve.tree_add(
        do_update=True
    ,   bevel=True
    ,   prune=False
    ,   showLeaves=True
    ,   useArm=False
    ,   seed=0
    ,   handleType='0'
    ,   levels=1
    ,   length=(0.7, 0.6, 0.5, 0.1)
    ,   lengthV=(0, 0.1, 0, 0)
    ,   taperCrown=0.5
    ,   branches=(0, 55, 10, 1)
    ,   curveRes=(8, 5, 3, 1)
    ,   curve=(0, -15, 0, 0)
    ,   curveV=(20, 50, 75, 0)
    ,   curveBack=(0, 0, 0, 0)
    ,   baseSplits=2
    ,   segSplits=(0.1, 0.5, 0.2, 0)
    ,   splitByLen=True
    ,   rMode='rotate'
    ,   splitAngle=(30, 30, 22, 0)
    ,   splitAngleV=(5, 5, 5, 0)
    ,   scale=0.1
    ,   scaleV=1.1
    ,   attractUp=(3.5, -1.89984, 0, 0)
    ,   attractOut=(0, 0.8, 0, 0)
    ,   shape='7'
    ,   shapeS='10'
    ,   customShape=(0.5, 1, 0.3, 0.5)
    ,   branchDist=1.5
    ,   nrings=0
    ,   baseSize=0.3
    ,   baseSize_s=0.16
    ,   splitHeight=0.2
    ,   splitBias=0.55
    ,   ratio=0.015
    ,   minRadius=0.0015
    ,   closeTip=False
    ,   rootFlare=1
    ,   autoTaper=True
    ,   taper=(1, 1, 1, 1)
    ,   radiusTweak=(1, 1, 1, 1)
    ,   ratioPower=1.2
    ,   downAngle=(0, 26.21, 52.56, 30)
    ,   downAngleV=(0, 10, 10, 10)
    ,   useOldDownAngle=True
    ,   useParentAngle=True
    ,   rotate=(99.5, 137.5, 137.5, 137.5)
    ,   rotateV=(15, 0, 0, 0)
    ,   scale0=1
    ,   scaleV0=0.1
    ,   pruneWidth=0.34
    ,   pruneBase=0.12
    ,   pruneWidthPeak=0.5
    ,   prunePowerHigh=0.5
    ,   prunePowerLow=0.001
    ,   pruneRatio=0.75
    ,   leaves=15
    ,   leafDownAngle=45
    ,   leafDownAngleV=-10
    ,   leafRotate=137.5
    ,   leafRotateV=15
    ,   leafScale=0.1
    ,   leafScaleX=0.2
    ,   leafScaleT=0.1
    ,   leafScaleV=0.15
    ,   leafShape='hex'
    ,   bend=0
    ,   leafangle=-45
    ,   horzLeaves=True
    ,   leafDist='6'
    ,   bevelRes=1
    ,   resU=4
    ,   armAnim=False
    ,   previewArm=False
    ,   leafAnim=False
    ,   frameRate=1
    ,   loopFrames=0
    ,   wind=1
    ,   gust=1
    ,   gustF=0.075
    ,   af1=1
    ,   af2=1
    ,   af3=4
    ,   makeMesh=False
    ,   armLevels=2
    ,   boneStep=(1, 1, 1, 1)
    )

Base_create()

2行目 :
アドオンを保存しているディレクトリを指定します。

8行目 :
アドオンの公式ページのURLを指定します

9行目 :
アドオンの名前を指定します。

17行目 :
インストールおよび、有効化したアドオンを使用して植物を生成します。

以上

このエントリーをはてなブックマークに追加
コメントを閉じる

コメント

コメントフォーム
記事の評価
  • リセット
  • リセット