
[Blender][script]Grease Pencil v3用のオニオンスキン代替
下の記事にある様に、Blender4.3以降、Grease Pencil v3になってスクリーンスペースで太さを一定に保てなくなった結果、ジオメトリノードを使わざるを得なくなってしまいました。
その際に一番困るのが、オニオンスキンです。
標準のオニオンスキンはモディファイアを反映しないので、下記の様にグリースペンシルオブジェクトとカメラの距離によっては全く使い物にならなくなってしまいました。
#blender #b3d #greasepencil
— 大串映二 (@e_ohkushi) February 27, 2026
Grease Pencil v3のオニオンスキンにジオメトリノード「Screen Space Thickness」が反映されない問題。
グリースペンシルオブジェクトがカメラに近い場合こうなる。
カーソルがデカくなるのも地味にきつい。 https://t.co/f6W1oBIM9a pic.twitter.com/c12C32k1aa
もう標準のオニオンスキンの代替を作りました。
#blender #b3d #greasepencil
— 大串映二 (@e_ohkushi) February 27, 2026
GPTにつくってもらったオニオンスキンツール
「Screen Space Thickness」
「TimeOffset」
「Tint」
「Opacity」
「ChildOf」
を一発で仕込んでくれる
→ https://t.co/f6W1oBIM9a pic.twitter.com/MqNtL2uMHl
import os
import bpy
from bpy.props import (
StringProperty,
IntProperty,
FloatProperty,
FloatVectorProperty,
BoolProperty,
EnumProperty,
)
# -------------------------
# Utilities (general)
# -------------------------
def ensure_collection(name: str) -> bpy.types.Collection:
col = bpy.data.collections.get(name)
if col is None:
col = bpy.data.collections.new(name)
bpy.context.scene.collection.children.link(col)
return col
def link_object_to_collection(obj: bpy.types.Object, col: bpy.types.Collection):
# Unlink from other collections to keep things tidy
for c in list(obj.users_collection):
try:
c.objects.unlink(obj)
except RuntimeError:
pass
if obj.name not in col.objects:
col.objects.link(obj)
def find_modifier_type_id(substrs):
"""Find a modifier type enum identifier that matches all substrings (case-insensitive)."""
enum_items = bpy.types.Modifier.bl_rna.properties["type"].enum_items
for it in enum_items:
ident = it.identifier
low = ident.lower()
if all(s.lower() in low for s in substrs):
return ident
return None
def add_gp_modifier(obj: bpy.types.Object, name: str, type_id: str):
m = obj.modifiers.get(name)
if m and m.type == type_id:
return m
if m:
obj.modifiers.remove(m)
return obj.modifiers.new(name=name, type=type_id)
def set_first_attr(mod, candidates, value) -> bool:
"""Set first existing attribute on modifier from candidates; return True if set."""
for a in candidates:
if hasattr(mod, a):
try:
setattr(mod, a, value)
return True
except Exception:
pass
# fallback to IDProperty
for a in candidates:
try:
mod[a] = value
return True
except Exception:
pass
return False
def ensure_geometry_nodes_modifier(obj: bpy.types.Object, mod_name: str, node_group: bpy.types.NodeTree):
m = obj.modifiers.get(mod_name)
if m and m.type == "NODES":
m.node_group = node_group
return m
if m:
obj.modifiers.remove(m)
m = obj.modifiers.new(mod_name, "NODES")
m.node_group = node_group
return m
def set_object_safe_flags(obj: bpy.types.Object, selectable: bool, renderable: bool):
obj.hide_render = not renderable
obj.hide_select = not selectable
def build_opacity_steps(offsets, base=0.35, falloff=0.6):
res = {}
for off in offsets:
a = abs(off)
if a <= 0:
res[off] = 1.0
else:
res[off] = max(0.0, base * (falloff ** (a - 1)))
return res
def purge_collection_objects(col: bpy.types.Collection):
for obj in list(col.objects):
bpy.data.objects.remove(obj, do_unlink=True)
def purge_prefix_objects(prefix: str):
if not prefix:
return
for obj in list(bpy.data.objects):
if obj.name.startswith(prefix):
bpy.data.objects.remove(obj, do_unlink=True)
def set_timeoffset_keep_loop_off(time_mod):
candidates = ["keep_loop", "use_keep_loop", "keep_looping", "use_loop", "use_keep_looping"]
for a in candidates:
if hasattr(time_mod, a):
try:
setattr(time_mod, a, False)
return True
except Exception:
pass
for a in candidates:
try:
time_mod[a] = False
return True
except Exception:
pass
return False
# -------------------------
# Constraint helpers (Child Of)
# -------------------------
def add_childof_constraint_follow(ghost: bpy.types.Object, target: bpy.types.Object, name="OS_ChildOf"):
"""
Add Child Of constraint so ghost follows target transforms.
Uses Set Inverse to keep current visual transform while making it follow.
"""
c = ghost.constraints.get(name)
if c and c.type != "CHILD_OF":
ghost.constraints.remove(c)
c = None
if c is None:
c = ghost.constraints.new("CHILD_OF")
c.name = name
c.target = target
c.influence = 1.0
view_layer = bpy.context.view_layer
prev_active = view_layer.objects.active
prev_sel = [o for o in view_layer.objects if o.select_get()]
try:
for o in prev_sel:
o.select_set(False)
ghost.select_set(True)
view_layer.objects.active = ghost
bpy.ops.constraint.childof_set_inverse(constraint=c.name, owner="OBJECT")
except Exception:
pass
finally:
for o in prev_sel:
try:
o.select_set(True)
except Exception:
pass
view_layer.objects.active = prev_active
return c
# -------------------------
# Draw order helpers (Original on top)
# -------------------------
def set_in_front_safe(obj: bpy.types.Object, value: bool):
"""
Try to set viewport 'In Front' flag.
Property name differs by version/type; ignore if unavailable.
"""
# Common Blender prop
if hasattr(obj, "show_in_front"):
try:
obj.show_in_front = value
return True
except Exception:
pass
# Some builds expose it differently; try IDProperty fallback
try:
obj["show_in_front"] = bool(value)
return True
except Exception:
return False
def relink_object_last_in_its_collections(obj: bpy.types.Object):
"""
Unlink and link back to all its collections to push it later in link order.
This often makes it evaluated/drawn later (on top) when sharing same GP data.
"""
try:
cols = list(obj.users_collection)
if not cols:
return False
for c in cols:
if obj.name in c.objects:
c.objects.unlink(obj)
for c in cols:
c.objects.link(obj)
bpy.context.view_layer.update()
return True
except Exception:
return False
# -------------------------
# Nodegroup loading (stable)
# -------------------------
def _score_sst_name(name: str) -> int:
n = name.lower()
s = 0
if "screen" in n:
s += 10
if "space" in n:
s += 5
if "thickness" in n:
s += 10
if "grease" in n or "gp" in n:
s += 2
return s
def get_or_load_sst_nodegroup(filepath: str):
if not filepath:
raise FileNotFoundError("Nodegroup .blend path is empty.")
abs_path = bpy.path.abspath(filepath)
if not os.path.isfile(abs_path):
raise FileNotFoundError(f"Nodegroup .blend not found: {abs_path}")
with bpy.data.libraries.load(abs_path, link=False) as (data_from, data_to):
names = list(data_from.node_groups)
if not names:
return None
best_name = max(names, key=_score_sst_name)
existing = bpy.data.node_groups.get(best_name)
if existing is not None:
return existing
with bpy.data.libraries.load(abs_path, link=False) as (data_from, data_to):
data_to.node_groups = [best_name]
return bpy.data.node_groups.get(best_name)
# -------------------------
# Driver helpers (SST auto wiring)
# -------------------------
def _normalize_name(s: str) -> str:
return "".join(ch for ch in s.lower() if ch.isalnum())
def _match_sst_socket(name: str):
n = _normalize_name(name).replace("sesor", "sensor")
if n == "resolutionx" or ("resolution" in n and n.endswith("x")):
return "res_x"
if n == "resolutiony" or ("resolution" in n and n.endswith("y")):
return "res_y"
if ("focal" in n and "length" in n) or ("lens" in n):
return "focal"
if "sensor" in n and "fit" in n:
return "sensor_fit"
if "sensor" in n and "size" in n:
return "sensor_size"
return None
def _ensure_idprop_for_socket(mod: bpy.types.Modifier, ident: str, socket_type: str):
try:
_ = mod[ident]
return
except Exception:
pass
if socket_type == "NodeSocketVector":
mod[ident] = (0.0, 0.0, 0.0)
elif socket_type == "NodeSocketInt":
mod[ident] = 0
elif socket_type == "NodeSocketBool":
mod[ident] = False
else:
mod[ident] = 0.0
def _clear_driver_vars(drv):
while drv.variables:
drv.variables.remove(drv.variables[0])
def _add_driver(obj: bpy.types.Object, data_path: str, expression: str, vars_def: list, index=None):
try:
if index is None:
obj.driver_remove(data_path)
else:
obj.driver_remove(data_path, index)
except Exception:
pass
if index is None:
fcu = obj.driver_add(data_path)
else:
fcu = obj.driver_add(data_path, index)
drv = fcu.driver
drv.type = "SCRIPTED"
_clear_driver_vars(drv)
for v in vars_def:
var = drv.variables.new()
var.name = v["name"]
var.type = "SINGLE_PROP"
targ = var.targets[0]
targ.id_type = v["id_type"]
targ.id = v["id"]
targ.data_path = v["data_path"]
drv.expression = expression
return fcu
def connect_sst_inputs_with_drivers(obj: bpy.types.Object, gn_mod: bpy.types.Modifier, scene: bpy.types.Scene):
"""
Focal Length / Sensor Size are multiplied by 0.001 (mm -> m).
Camera is taken from scene.camera (active camera).
"""
ng = getattr(gn_mod, "node_group", None)
if ng is None or getattr(ng, "interface", None) is None:
return
try:
items = ng.interface.items_tree
except Exception:
items = []
sockets = []
for item in items:
if getattr(item, "item_type", None) != "SOCKET":
continue
if getattr(item, "in_out", None) != "INPUT":
continue
sockets.append(item)
if not sockets:
return
mod_name = gn_mod.name
scene_id = scene
found = {}
for s in sockets:
key = _match_sst_socket(getattr(s, "name", ""))
if key:
found[key] = s
if "res_x" in found:
s = found["res_x"]
ident = s.identifier
_ensure_idprop_for_socket(gn_mod, ident, s.socket_type)
path = f'modifiers["{mod_name}"]["{ident}"]'
_add_driver(
obj,
path,
expression="rx*p/100.0",
vars_def=[
{"name": "rx", "id_type": "SCENE", "id": scene_id, "data_path": "render.resolution_x"},
{"name": "p", "id_type": "SCENE", "id": scene_id, "data_path": "render.resolution_percentage"},
],
)
if "res_y" in found:
s = found["res_y"]
ident = s.identifier
_ensure_idprop_for_socket(gn_mod, ident, s.socket_type)
path = f'modifiers["{mod_name}"]["{ident}"]'
_add_driver(
obj,
path,
expression="ry*p/100.0",
vars_def=[
{"name": "ry", "id_type": "SCENE", "id": scene_id, "data_path": "render.resolution_y"},
{"name": "p", "id_type": "SCENE", "id": scene_id, "data_path": "render.resolution_percentage"},
],
)
if "focal" in found:
s = found["focal"]
ident = s.identifier
_ensure_idprop_for_socket(gn_mod, ident, s.socket_type)
path = f'modifiers["{mod_name}"]["{ident}"]'
_add_driver(
obj,
path,
expression="lens*0.001",
vars_def=[
{"name": "lens", "id_type": "SCENE", "id": scene_id, "data_path": "camera.data.lens"},
],
)
if "sensor_fit" in found:
s = found["sensor_fit"]
ident = s.identifier
_ensure_idprop_for_socket(gn_mod, ident, s.socket_type)
path = f'modifiers["{mod_name}"]["{ident}"]'
_add_driver(
obj,
path,
expression="fit",
vars_def=[
{"name": "fit", "id_type": "SCENE", "id": scene_id, "data_path": "camera.data.sensor_fit"},
],
)
if "sensor_size" in found:
s = found["sensor_size"]
ident = s.identifier
_ensure_idprop_for_socket(gn_mod, ident, s.socket_type)
base_path = f'modifiers["{mod_name}"]["{ident}"]'
if s.socket_type == "NodeSocketVector":
try:
v = gn_mod[ident]
if isinstance(v, (list, tuple)) and len(v) >= 3:
gn_mod[ident] = (v[0], v[1], 0.0)
except Exception:
pass
_add_driver(
obj,
base_path,
index=0,
expression="sw*0.001",
vars_def=[
{"name": "sw", "id_type": "SCENE", "id": scene_id, "data_path": "camera.data.sensor_width"},
],
)
_add_driver(
obj,
base_path,
index=1,
expression="sh*0.001",
vars_def=[
{"name": "sh", "id_type": "SCENE", "id": scene_id, "data_path": "camera.data.sensor_height"},
],
)
else:
expr = (
"0.001*("
"sw if ("
"(fit if fit!=0 else (1 if ((rx*p/100.0)*pax) >= ((ry*p/100.0)*pay) else 2))"
"==1) else sh"
")"
)
_add_driver(
obj,
base_path,
expression=expr,
vars_def=[
{"name": "sw", "id_type": "SCENE", "id": scene_id, "data_path": "camera.data.sensor_width"},
{"name": "sh", "id_type": "SCENE", "id": scene_id, "data_path": "camera.data.sensor_height"},
{"name": "fit", "id_type": "SCENE", "id": scene_id, "data_path": "camera.data.sensor_fit"},
{"name": "rx", "id_type": "SCENE", "id": scene_id, "data_path": "render.resolution_x"},
{"name": "ry", "id_type": "SCENE", "id": scene_id, "data_path": "render.resolution_y"},
{"name": "p", "id_type": "SCENE", "id": scene_id, "data_path": "render.resolution_percentage"},
{"name": "pax", "id_type": "SCENE", "id": scene_id, "data_path": "render.pixel_aspect_x"},
{"name": "pay", "id_type": "SCENE", "id": scene_id, "data_path": "render.pixel_aspect_y"},
],
)
def find_existing_sst_gn_modifier(obj: bpy.types.Object, sst_group: bpy.types.NodeTree):
for m in obj.modifiers:
if m.type == "NODES" and getattr(m, "node_group", None) == sst_group:
return m
return None
def ensure_sst_on_object(obj: bpy.types.Object, sst_group: bpy.types.NodeTree, scene: bpy.types.Scene, mod_name_fallback: str):
m = find_existing_sst_gn_modifier(obj, sst_group)
if m is None:
m = ensure_geometry_nodes_modifier(obj, mod_name_fallback, sst_group)
connect_sst_inputs_with_drivers(obj, m, scene)
return m
# -------------------------
# Operator
# -------------------------
class GPONION_OT_build(bpy.types.Operator):
bl_idname = "gponion.build_onion_sst"
bl_label = "Create / Rebuild Onion Ghosts"
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
scn = context.scene
settings = scn.gp_onion_sst
src = context.active_object
if not src or src.type != "GREASEPENCIL":
self.report({"ERROR"}, "Active object must be a Grease Pencil v3 object (type=GREASEPENCIL).")
return {"CANCELLED"}
try:
sst_group = get_or_load_sst_nodegroup(settings.nodegroup_blend_path)
except Exception as e:
self.report({"ERROR"}, f"Failed to load nodegroup: {e}")
return {"CANCELLED"}
if not sst_group:
self.report({"ERROR"}, "Could not find a Screen Space Thickness node group in the specified .blend.")
return {"CANCELLED"}
# Ensure SST + drivers on SOURCE object
ensure_sst_on_object(src, sst_group, scn, mod_name_fallback="SST_ScreenSpaceThickness")
# Force original on top if possible
if settings.force_original_in_front:
set_in_front_safe(src, True)
# Ensure collection
col = ensure_collection(settings.collection_name)
# Remove existing ghosts
if settings.remove_existing:
if settings.delete_mode == "COLLECTION":
purge_collection_objects(col)
elif settings.delete_mode == "PREFIX":
purge_prefix_objects(settings.ghost_prefix or "GP_OS")
type_time = find_modifier_type_id(["grease", "pencil", "time"])
type_tint = find_modifier_type_id(["grease", "pencil", "tint"])
type_opac = find_modifier_type_id(["grease", "pencil", "opacity"])
if not type_time or not type_tint or not type_opac:
self.report({"ERROR"}, "Could not find Grease Pencil modifier types in this Blender build.")
return {"CANCELLED"}
offsets = list(range(-settings.past_count, 0)) + list(range(1, settings.future_count + 1))
if not offsets:
self.report({"WARNING"}, "No offsets requested (past=0 and future=0). Nothing to do.")
return {"CANCELLED"}
opacity_map = build_opacity_steps(
offsets,
base=settings.opacity_base_abs1,
falloff=settings.opacity_falloff,
)
prefix = settings.ghost_prefix or "GP_OS"
base_name = src.name
created = []
for off in offsets:
sign = "m" if off < 0 else "p"
idx = abs(off)
ghost_name = f"{prefix}_{base_name}_{sign}{idx:02d}"
ghost = src.copy()
ghost.data = src.data
ghost.animation_data_clear()
ghost.name = ghost_name
link_object_to_collection(ghost, col)
set_object_safe_flags(ghost, selectable=False, renderable=False)
# Keep ghosts behind if possible
if settings.force_original_in_front:
set_in_front_safe(ghost, False)
# Optional tiny Z offset to avoid exact overlap flicker (visual aid)
if settings.ghost_z_offset != 0.0:
ghost.location.z += settings.ghost_z_offset
# Follow source transforms
add_childof_constraint_follow(ghost, src, name="OS_ChildOf")
# Time Offset
m_time = add_gp_modifier(ghost, "OS_TimeOffset", type_time)
set_first_attr(m_time, ["offset", "frame_offset"], off)
set_timeoffset_keep_loop_off(m_time)
# SST GN + drivers
ensure_sst_on_object(ghost, sst_group, scn, mod_name_fallback="OS_ScreenSpaceThickness")
# Tint
m_tint = add_gp_modifier(ghost, "OS_Tint", type_tint)
if hasattr(m_tint, "color"):
m_tint.color = settings.tint_color_past if off < 0 else settings.tint_color_future
set_first_attr(m_tint, ["factor", "strength"], settings.tint_strength)
# Opacity
m_op = add_gp_modifier(ghost, "OS_Opacity", type_opac)
op_val = opacity_map.get(off, 0.2)
set_first_attr(m_op, ["color_factor", "factor", "opacity"], op_val)
created.append(ghost)
# Try to push original later in collection link order (often draws on top)
if settings.force_original_on_top_by_relink:
relink_object_last_in_its_collections(src)
if scn.camera is None:
self.report({"WARNING"}, "Scene has no active camera (scene.camera is None). SST drivers referencing camera may show errors until you set an active camera.")
self.report({"INFO"}, f"Created {len(created)} onion ghosts. Original-on-top={settings.force_original_in_front or settings.force_original_on_top_by_relink}.")
return {"FINISHED"}
# -------------------------
# UI
# -------------------------
class GPOnionSSTSettings(bpy.types.PropertyGroup):
nodegroup_blend_path: StringProperty(
name="Nodegroup .blend",
description="Path to .blend that contains the Screen Space Thickness node group",
subtype="FILE_PATH",
default="",
)
collection_name: StringProperty(name="Collection", default="_ONION")
ghost_prefix: StringProperty(name="Ghost Prefix", default="GP_OS")
past_count: IntProperty(name="Past Frames", default=3, min=0, max=24)
future_count: IntProperty(name="Future Frames", default=2, min=0, max=24)
remove_existing: BoolProperty(name="Remove Existing", default=True)
delete_mode: EnumProperty(
name="Delete Mode",
items=[
("COLLECTION", "Collection", "Delete ALL objects in the target collection (safest)"),
("PREFIX", "Prefix Only", "Delete objects whose name starts with Ghost Prefix (global)"),
],
default="COLLECTION",
)
tint_color_past: FloatVectorProperty(name="Past Tint", subtype="COLOR", size=3, min=0.0, max=1.0, default=(1.0, 0.2, 0.2))
tint_color_future: FloatVectorProperty(name="Future Tint", subtype="COLOR", size=3, min=0.0, max=1.0, default=(0.2, 1.0, 0.2))
tint_strength: FloatProperty(name="Tint Strength", default=0.8, min=0.0, max=2.0)
opacity_base_abs1: FloatProperty(name="Opacity @1", default=0.35, min=0.0, max=2.0)
opacity_falloff: FloatProperty(name="Opacity Falloff", default=0.6, min=0.0, max=1.0)
# Original-on-top options
force_original_in_front: BoolProperty(
name="Original In Front",
description="Try to force original object to draw in front (uses show_in_front when available).",
default=True,
)
force_original_on_top_by_relink: BoolProperty(
name="Relink Original Last",
description="Unlink+relink original in its collections to push it later in link order (often draws on top).",
default=True,
)
ghost_z_offset: FloatProperty(
name="Ghost Z Offset",
description="Optional tiny Z offset for ghosts (visual aid to avoid perfect overlap). Use very small value like -0.0001. 0 disables.",
default=0.0,
soft_min=-0.01,
soft_max=0.01,
precision=6,
)
class GPONION_PT_panel(bpy.types.Panel):
bl_label = "GP Onion SST"
bl_idname = "GPONION_PT_panel"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = "GP Onion SST"
def draw(self, context):
layout = self.layout
s = context.scene.gp_onion_sst
layout.prop(s, "nodegroup_blend_path")
layout.prop(s, "collection_name")
layout.prop(s, "ghost_prefix")
col = layout.column(align=True)
col.label(text="Frames")
row = col.row(align=True)
row.prop(s, "past_count")
row.prop(s, "future_count")
col = layout.column(align=True)
col.label(text="Tint")
row = col.row(align=True)
row.prop(s, "tint_color_past")
row.prop(s, "tint_color_future")
col.prop(s, "tint_strength")
col = layout.column(align=True)
col.label(text="Opacity")
col.prop(s, "opacity_base_abs1")
col.prop(s, "opacity_falloff")
layout.separator()
layout.label(text="Original on Top")
layout.prop(s, "force_original_in_front")
layout.prop(s, "force_original_on_top_by_relink")
layout.prop(s, "ghost_z_offset")
layout.separator()
layout.prop(s, "remove_existing")
row = layout.row()
row.enabled = s.remove_existing
row.prop(s, "delete_mode")
layout.operator(GPONION_OT_build.bl_idname, icon="OUTLINER_OB_GREASEPENCIL")
classes = (
GPOnionSSTSettings,
GPONION_OT_build,
GPONION_PT_panel,
)
def register():
for c in classes:
bpy.utils.register_class(c)
bpy.types.Scene.gp_onion_sst = bpy.props.PointerProperty(type=GPOnionSSTSettings)
def unregister():
del bpy.types.Scene.gp_onion_sst
for c in reversed(classes):
bpy.utils.unregister_class(c)
if __name__ == "__main__":
register()chatGPT製です