-
-
Save wakarase/dd95761ba00bb68932372ac834a75c09 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# BlenderユーザーのためのPython入門 | |
# 第24節 複数のキューブをsinで並べてグラデーションする | |
import colorsys | |
import bpy | |
import math | |
import random | |
def delete_all(): | |
"""既存のメッシュとマテリアルを削除します。""" | |
for mesh in bpy.data.meshes: | |
assert isinstance(mesh, bpy.types.Mesh) | |
bpy.data.meshes.remove(mesh) | |
for material in bpy.data.materials: | |
assert isinstance(material, bpy.types.Material) | |
bpy.data.materials.remove(material) | |
def make_sphere(x, y, z): | |
"""座標(x, y, z)に球を作成します。""" | |
bpy.ops.mesh.primitive_ico_sphere_add(location=(x, y, z), radius=1.0) | |
bpy.ops.object.material_slot_add() | |
bpy.ops.object.shade_smooth() | |
return bpy.context.active_object | |
def make_spheres(half): | |
"""2 * half + 1個の球を正弦波(または余弦波)の形に並べます。""" | |
objects = [] | |
if random.random() >= 0.5: | |
f = math.sin | |
else: | |
f = math.cos | |
for x in range(-half, half + 1): | |
z = f(math.radians(x * 10)) * 10 | |
object = make_sphere(x, 0, z) | |
objects.append(object) | |
return objects | |
def make_material(name, color): | |
"""与えられた名前と色のマテリアルを作ります。""" | |
material = bpy.data.materials.new(name) | |
material.diffuse_color = color | |
material.use_nodes = True | |
node_tree = material.node_tree | |
assert isinstance(node_tree, bpy.types.ShaderNodeTree) | |
principled_bsdf = node_tree.nodes['Principled BSDF'] | |
assert isinstance(principled_bsdf, bpy.types.ShaderNodeBsdfPrincipled) | |
principled_bsdf.inputs['Base Color'].default_value = color | |
return material | |
def make_materials(n): | |
"""n個のマテリアルを虹色状に作ります。""" | |
materials = [] | |
for i in range(n): | |
name = 'Color' + str(i) | |
# [0, 1)の範囲で色相を遷移させます。 | |
(r, g, b) = colorsys.hsv_to_rgb(i / (n - 1), 1.0, 1.0) | |
material = make_material(name, (r, g, b, 1.0)) | |
materials.append(material) | |
return materials | |
def set_materials(objects, materials): | |
"""各メッシュに対応するマテリアルを割り当てます。""" | |
for i in range(len(objects)): | |
objects[i].material_slots[0].material = materials[i] | |
if __name__ == '__main__': | |
delete_all() | |
objects = make_spheres(18) | |
materials = make_materials(len(objects)) | |
set_materials(objects, materials) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment