[Blender x Python] Let's master random !!

This time, I will introduce a mechanism to arrange a large number of objects at random.

table of contents

  1. How to get a random number
  2. Make a cube appear at a random position
  3. Create a function to organize the process
  4. Sample code
  5. English words Reference material

0. How to get a random number

This time, we will use the rand () function in a library called ** numpy ** (a collection of useful code).

The rand () function returns a random value ** from ** 0 to 1. The argument (parameter) specifies how many random numbers to return. If it is rand (3), it returns 3 random numbers.

import numpy as np

#np.You can think of random as a right-pointing arrow and ignore it.
np.random.rand(3)

Point:import numpy as np The library called numpy is abbreviated as np in the code.

array([0.90681482, 0.04813658, 0.47969033])

↑ Three random values in the range 0 to 1 are output.

1. Make a cube appear at a random position

1-0. Let's make the cube appear in random positions !!

Use the library numpy for numerical calculation

import bpy
import numpy as np

bpy.ops.mesh.primitive_cube_add(location = np.random.rand(3))

Point:rand( ) Generate a random value from 0 to 1. The argument determines how many values to return. rand (3) returns 3 random values.

スクリーンショット 2020-11-16 5.33.17.png

1-1. Let's be able to specify the range where the cube appears

○ Gets a random number in the range of -10 or more and less than 10. The code has the following structure.

Data (information) is assigned to the variable □, and processing is executed using that data. And you can think of the dots as right-pointing arrows (almost negligible).

□ ← Random numerical data
===>function( □ )
import bpy
import numpy as np

#Variable random_Create a location and assign a random value
random_location = (10 - (-10)) * np.random.rand(3) + (-10)
bpy.ops.mesh.primitive_cube_add(location = random_location)

スクリーンショット 2020-11-16 6.16.00.png

Point: ** Numerical value within a certain range ** An expression that gets a random value in the range min or greater and less than max (max-min) * np.random.rand() + min is.

In other words ** Range where numbers fluctuate * Random value from 0 to 1 + Start of range ** about it.

In this example, we get (random) numbers in the range +20 from -10. Range → (-10, ..-9, ..0, ..9, ..10)

2. Create a function to organize the process

2-0. Create a function that returns a random number and a function that uses it to make a cube appear.

import bpy
import numpy as np

#Definition of a function to generate three random values
def get_random_location(min,max):
    return (max - min) * np.random.rand(3) + min

#get_random_location()Definition of a function that makes a cube appear using the value generated by the function
def generate_random_cube(min,max):
    random_location = get_random_location(min,max)
    bpy.ops.mesh.primitive_cube_add(location = random_location)

generate_random_cube(-10,10)

Point:Return It is used in the form of `` return information'' when the function outputs some information.

スクリーンショット 2020-11-16 8.55.19.png

2-1. Create a function that makes multiple cubes appear at random positions

import bpy
import numpy as np

#Definition of a function to generate three random values
def get_random_location(min,max):
    return (max - min) * np.random.rand(3) + min

#get_random_location()Definition of a function that makes a cube appear using the value generated by the function
def generate_random_cube(min,max):
    random_location = get_random_location(min,max)
    bpy.ops.mesh.primitive_cube_add(location = random_location)

#Definition of a function that causes multiple cubes to appear at random positions
def generate_random_cubes(min,max,num):
    for i in range(0,num):
        generate_random_cube(min,max)

generate_random_cubes(-10,10,200)

スクリーンショット 2020-11-16 8.53.45.png

2-2. Make multiple cubes with random angles appear at random positions

import bpy
import math
import numpy as np

#Definition of a function to generate three random values
def get_random_location(min,max):
    return (max - min) * np.random.rand(3) + min

#random_number()Definition of a function that rotates and makes a cube appear using the value generated by the function
def generate_random_rotate_cube(min,max):
    random_location = get_random_location(min,max)
    bpy.ops.mesh.primitive_cube_add(location = random_location,rotation = math.pi * np.random.rand(3))

#Definition of a function that rotates and makes multiple cubes appear at random positions
def generate_random_rotate_cubes(min,max,num):
    for i in range(0,num):
        generate_random_rotate_cube(min,max)

generate_random_rotate_cubes(-10,10,200)

スクリーンショット 2020-11-16 9.47.40.png


3. Sample code

Create a function that randomly determines the color

○ Place colorful cubes at random positions and at random angles.

import bpy
import math
import numpy as np

#Definition of the function that determines the material
def material(name = 'material'):
    material_glass = bpy.data.materials.new(name)
    #Make the node available
    material_glass.use_nodes = True
    p_BSDF = material_glass.node_tree.nodes["Principled BSDF"]
    #0→BaseColor/7→roughness(=Roughness)/15→transmission(=propagation)
    #default_value = (R, G, B, A)
    p_BSDF.inputs[0].default_value = np.random.rand(4)
    p_BSDF.inputs[7].default_value = 0
    p_BSDF.inputs[15].default_value = 1
    #Add a material element to an object
    bpy.context.object.data.materials.append(material_glass)

#Definition of a function to generate three random values
def get_random_location(min,max):
    return (max - min) * np.random.rand(3) + min

#random_number()Definition of a function that rotates and makes a cube appear using the value generated by the function
def generate_random_rotate_cube(min,max):
    random_location = get_random_location(min,max)
    bpy.ops.mesh.primitive_cube_add(location = random_location,rotation = math.pi * np.random.rand(3))

#Definition of a function that rotates and makes multiple cubes appear at random positions
def generate_random_rotate_colorful_cubes(min,max,num):
    for i in range(0,num):
        generate_random_rotate_cube(min,max)
        material('Random')


generate_random_rotate_colorful_cubes(-10,10,200)

    

c1.png


Create a function that arranges cubes while rotating them

import bpy
import math
import numpy as np

#Definition of the function that determines the material
def material(name = 'material'):
    material_glass = bpy.data.materials.new(name)
    #Make the node available
    material_glass.use_nodes = True
    p_BSDF = material_glass.node_tree.nodes["Principled BSDF"]
    #0→BaseColor/7→roughness(=Roughness)/15→transmission(=propagation)
    #default_value = (R, G, B, A)
    p_BSDF.inputs[0].default_value = np.random.rand(4)
    p_BSDF.inputs[7].default_value = 0
    p_BSDF.inputs[15].default_value = 1
    #Add a material element to an object
    bpy.context.object.data.materials.append(material_glass)

#Definition of a function that arranges colorful cubes while rotating them
def spiral_colorful_cubes():
    #Iterate 100 times
    for i in range(0,100):
        bpy.ops.mesh.primitive_cube_add(
            #Move up little by little
            location=(0, 0, i/50),
            scale=(1, 1, 0.05),
            #180 * i * 36(Every time)Shift one by one
            rotation = (0, 0, math.pi*i*10/360)
            )
        #Add a material element to an object
        material('Random')

#Execute the process
spiral_colorful_cubes()

スクリーンショット 2020-11-16 15.08.30.png


Create a function that transforms the torus, rotates it, and arranges it

import bpy
import math
import numpy as np

#Definition of the function that determines the material
def material(name = 'material'):
    material_glass = bpy.data.materials.new(name)
    #Make the node available
    material_glass.use_nodes = True
    p_BSDF = material_glass.node_tree.nodes["Principled BSDF"]
    #0→BaseColor/7→roughness(=Roughness)/15→transmission(=propagation)
    #default_value = (R, G, B, A)
    p_BSDF.inputs[0].default_value = np.random.rand(4)
    p_BSDF.inputs[7].default_value = 0
    p_BSDF.inputs[15].default_value = 1
    #Add a material element to an object
    bpy.context.object.data.materials.append(material_glass)

#Definition of a function that transforms and shifts the torus and colors each
def colorful_torus_spiral():
    for i in range(0,36):
        bpy.ops.mesh.primitive_torus_add(
            location=(0, 0, 0),
            major_radius=1.0,
            minor_radius=0.01,
            )
        #Shrink in the Y-axis direction
        bpy.ops.transform.resize(value=(1, 0.3, 1))
        #Rotate around the Z axis
        bpy.ops.transform.rotate(value=math.pi*i*10/360,orient_axis='Z')
        #Add a material element to an object
        material('Random')

colorful_torus_spiral()

c4.png


4. English words

English words Translation
spiral Spiral
material Material, material
principled Principle, principle
primitive Primitive
math Math
add to add
context Context, environment
value value
default Default
append to add
generate produce
inputs get

Reference material

Reference: Automatically generate a large amount of particle live material with Blender x Python

Recommended Posts

[Blender x Python] Let's master random !!
[Blender x Python] Let's master rotation !!
[Blender x Python] Let's master the material !!
[Blender x Python] Let's get started with Blender Python !!
[Blender x Python] Blender Python tips (11/100)
[Python] Let's master all and any
[Blender x Python] Particle Animation (Part 1)
[Blender x Python] How to use modifiers
Blender 2.9 Python Extrude extrude
Blender 2.8, Python, camera movement, random number color specification
[Blender x Python] How to make an animation
[Blender x Python] How to make vertex animation
[Blender x Python] Think of code with symbols
[Blender x Python] How to create an original object
[Blender x Python] 3D Bouncing Ball and other animations
Python string manipulation master
blender, python, spiral staircase
Random walk in Python
Run Blender with python
blender, python, sphere behavior
Random string generation (Python)
Blender 2.8, Python Cube Scaling
Aim python library master (36) json2html
Aim python library master (49) psidialogs
Let's use def in python
Let's use python janome easily
Aim python library master (26) easyxml
x86 compiler self-made with python
Aim python library master (29) table_printer
Balanced Random Forest in python
Register DynamoDB x Python / Decimal
Aim python library master (46) browserplus
Aim python library master (30) chronyk
Aim python library master (3) workalendar
Aim python library master (42) speedrecorder
Aim python library master (37) slimurl
Aim python library master (44) pynetviz
Aim python library master (8) rolex
Aim python library master (52) marktime
Aim python library master (7) numparser
Let's run Excel with Python
Aim python library master (21) hy
Aim python library master (18) requests
Blender 2.9, Python Buildings, Cars, Videos
Aim python library master (13) easydev
Aim python library master (34) concurrent
Aim python library master (40) wordsegmentation
blender, python, spiral staircase, color
Aim python library master (43) cpmoptimize
Aim python library master (68) pazudorasolver
Aim python library master (58) faker
Aim python library master (11) nlist
Aim python library master (38) beautiful_print
Aim python library master (2) vincenty
Aim python library master (59) logbook
Aim python library master (51) pyautogui
Put Python 3.x on Ubuntu
Aim python library master (10) timeit
Aim python library master (0) Links
Use Random Forest in Python
Aim python library master (66) youtube-dl