def main(): num_part = 100000 np_x = np.random.rand(num_part, 3).astype(np.float) * 0.4 + 0.2 np_v = np.random.rand(num_part, 3).astype(np.float) * 0 np_c = np.zeros((num_part, 3)).astype(np.float32) np_c[:, 0] = 0.85 np_c[:, 1] = 0.9 np_c[:, 2] = 1 for i in range(3): # bbox values must be multiples of dx bbox[0][i] = (math.floor(np_x[:, i].min() * particle_grid_res) - 3.0) / particle_grid_res bbox[1][i] = (math.floor(np_x[:, i].max() * particle_grid_res) + 3.0) / particle_grid_res num_particles[None] = num_part print('num_input_particles =', num_part) @ti.kernel def initialize_particle_x(x: ti.ext_arr(), v: ti.ext_arr(), color: ti.ext_arr()): for i in range(max_num_particles): if i < num_particles: for c in ti.static(range(3)): particle_x[i][c] = x[i, c] particle_v[i][c] = v[i, c] particle_color[i][c] = color[i, c] # reconstruct grid using particle position and MPM p2g. for k in ti.static(range(27)): base_coord = (inv_dx * particle_x[i] - 0.5).cast( ti.i32) + ti.Vector([k // 9, k // 3 % 3, k % 3]) grid_density[base_coord / grid_visualization_block_size] = 1 initialize_particle_x(np_x, np_v, np_c) initialize_particle_grid() gui = ti.core.GUI('Particle Renderer', ti.veci(*res)) last_t = 0 for i in range(500): render() interval = 10 if i % interval == 0: img = np.zeros((res[0], res[1], 3), dtype=np.float32) copy(img) if last_t != 0: print("time per spp = {:.2f} ms".format( (time.time() - last_t) * 1000 / interval)) last_t = time.time() img = img * (1 / (i + 1)) * exposure img = np.sqrt(img) gui.set_image(img) gui.update()
def __init__(self, name, res=512, background_color=0x0): import taichi as ti self.name = name if isinstance(res, numbers.Number): res = (res, res) self.res = res self.core = ti.core.GUI(name, ti.veci(*res)) self.canvas = self.core.get_canvas() self.background_color = background_color self.clear()
def main(): init_particles() print(f'boundary={boundary} grid={grid_size} cell_size={cell_size}') gui = ti.core.GUI('PBF2D', ti.veci(screen_res[0], screen_res[1])) canvas = gui.get_canvas() print_counter = 0 while True: move_board() run_pbf() print_counter += 1 if print_counter == 20: print_stats() print_counter = 0 render(gui, canvas)
def __init__(self, name, res=512, background_color=0x0): import taichi as ti self.name = name if isinstance(res, numbers.Number): res = (res, res) self.res = res self.core = ti.core.GUI(name, ti.veci(*res)) self.canvas = self.core.get_canvas() self.background_color = background_color self.key_pressed = set() self.clear() if ti.core.get_current_program(): self.core.set_profiler( ti.core.get_current_program().get_profiler())
def __init__(self, name, res=512, background_color=0x0): import taichi as ti self.name = name if isinstance(res, numbers.Number): res = (res, res) self.res = res # The GUI canvas uses RGBA for storage, therefore we need NxMx4 for an image. self.img = np.ascontiguousarray(np.zeros(self.res + (4, ), np.float32)) self.core = ti.core.GUI(name, ti.veci(*res)) self.canvas = self.core.get_canvas() self.background_color = background_color self.key_pressed = set() self.event = None self.clear()
x = ti.Vector(dim, dt=ti.f32, shape=n_particles) for i in range(n_particles): x[i] = x_logo[i] @ti.func def complexMul(a: ti.f32, b: ti.f32, c: ti.f32, d: ti.f32): # 复数乘法,用于旋转 return [a * c - b * d, b * c + a * d] @ti.kernel def substep(): for p in x: x[p] = x[p] - 0.5 x[p] = complexMul(x[p][0], x[p][1], spin[0], spin[1]) x[p] = x[p] + 0.5 gui = ti.core.GUI("SYSU_CG_COURSE", ti.veci(512, 512)) canvas = gui.get_canvas() for frame in range(19260817): substep() canvas.clear(0) pos = x.to_numpy(as_vector=True) for i in range(n_particles): canvas.circle(ti.vec(pos[i, 0], pos[i, 1])).radius(7).color(87 * 256 + 33).finish() # 中大绿 gui.update()
x[t, i] = x[t - 1, i] + dt * v[t, i] + x_inc[t, i] @ti.kernel def compute_loss(t: ti.i32): loss[None] = (x[t, target_ball][0] - goal[0])**2 + (x[t, target_ball][1] - goal[1])**2 @ti.kernel def initialize(): x[0, 0] = init_x v[0, 0] = init_v gui = tc.core.GUI("Billiards", tc.veci(1024, 1024)) def forward(visualize=False, output=None): initialize() interval = vis_interval if output: interval = output_vis_interval os.makedirs('billiards/{}/'.format(output), exist_ok=True) count = 0 for i in range(billiard_layers): for j in range(i + 1): count += 1 x[0, count] = [
new_v = ti.Vector([0.0, 0.0]) new_C = ti.Matrix([[0.0, 0.0], [0.0, 0.0]]) for i in ti.static(range(3)): for j in ti.static(range(3)): dpos = ti.cast(ti.Vector([i, j]), ti.f32) - fx g_v = grid_v[base(0) + i, base(1) + j] weight = w[i](0) * w[j](1) new_v += weight * g_v new_C += 4 * weight * ti.outer_product(g_v, dpos) * inv_dx v[p] = new_v x[p] += dt * v[p] C[p] = new_C gui = ti.core.GUI("MPM", ti.veci(1024, 1024)) canvas = gui.get_canvas() def mesh(i, j): return i * n_particle_y + j def main(): for i in range(n_particle_x): for j in range(n_particle_y): t = mesh(i, j) x[t] = [0.1 + i * dx * 0.5, 0.7 + j * dx * 0.5] v[t] = [0, -1] # build mesh for i in range(n_particle_x - 1): for j in range(n_particle_y - 1):
import taichi as tc vec = tc.vec gui = tc.core.GUI("Test GUI", tc.veci(512, 512)) canvas = gui.get_canvas() canvas.clear(0xFFFFFF) canvas.rect(vec(0.3, 0.3), vec(0.6, 0.6)).radius(2).color(0x000000).close().finish() canvas.path(vec(0.3, 0.3), vec(0.6, 0.6)).radius(2).color(0x000000).finish() canvas.circle(vec(0.5, 0.5)).radius(10).color(0xFF0000) while True: gui.update()
x[t, i] = x[t - 1, i] + dt * v[t, i] + x_inc[t, i] @ti.kernel def compute_loss(t: ti.i32): loss[None] = (x[t, target_ball][0] - goal[0])**2 + (x[t, target_ball][1] - goal[1])**2 @ti.kernel def initialize(): x[0, 0] = init_x v[0, 0] = init_v gui = ti.core.GUI("Billiards", ti.veci(1024, 1024)) def forward(visualize=False, output=None): initialize() interval = vis_interval if output: interval = output_vis_interval os.makedirs('billiards/{}/'.format(output), exist_ok=True) count = 0 for i in range(billiard_layers): for j in range(i + 1): count += 1 x[0, count] = [
new_v = ti.Vector.zero(ti.f32, 2) new_C = ti.Matrix.zero(ti.f32, 2, 2) for i in ti.static(range(3)): for j in ti.static(range(3)): dpos = ti.Vector([i, j]).cast(float) - fx g_v = grid_v[base + ti.Vector([i, j])] weight = w[i][0] * w[j][1] new_v += weight * g_v new_C += 4 * weight * ti.outer_product(g_v, dpos) * inv_dx v[p] = new_v x[p] += dt * v[p] J[p] *= 1 + dt * new_C.trace() C[p] = new_C gui = ti.core.GUI("MPM88", ti.veci(512, 512)) canvas = gui.get_canvas() for i in range(n_particles): x[i] = [random.random() * 0.4 + 0.2, random.random() * 0.4 + 0.2] v[i] = [0, -1] J[i] = 1 for frame in range(200): for s in range(50): grid_v.fill([0, 0]) grid_m.fill(0) substep() canvas.clear(0x112F41) pos = x.to_numpy(as_vector=True)
gravitational_force = ti.Vector([0.0, 0.0]) for i in ti.static(range(n_gravitation)): # instead of this one r = x[t - 1] - ti.Vector(gravitation_position[i]) len_r = ti.max(r.norm(), 1e-1) gravitational_force += K * gravitation[t, i] / (len_r * len_r * len_r) * r v[t] = v[t - 1] * math.exp(-dt * damping) + dt * gravitational_force x[t] = x[t - 1] + dt * v[t] @ti.kernel def compute_loss(t: ti.i32): ti.atomic_add(loss[None], dt * (x[t] - goal[t]).norm_sqr()) gui = ti.core.GUI("Electric", ti.veci(1024, 1024)) def forward(visualize=False, output=None): interval = vis_interval if output: interval = output_vis_interval os.makedirs('electric/{}/'.format(output), exist_ok=True) canvas = gui.get_canvas() for t in range(1, steps): nn1(t) nn2(t) advance(t) compute_loss(t)
scene.set_n_actuators(4) def robot(scene): scene.set_offset(0.1, 0.03) scene.add_rect(0.0, 0.1, 0.3, 0.1, -1) scene.add_rect(0.0, 0.0, 0.05, 0.1, 0) scene.add_rect(0.05, 0.0, 0.05, 0.1, 1) scene.add_rect(0.2, 0.0, 0.05, 0.1, 2) scene.add_rect(0.25, 0.0, 0.05, 0.1, 3) scene.set_n_actuators(4) from renderer_vector import rgb_to_hex gui = tc.core.GUI("Differentiable MPM", tc.veci(1024, 1024)) canvas = gui.get_canvas() def visualize(s, folder): canvas.clear(0xFFFFFF) vec = tc.vec for i in range(n_particles): color = 0x111111 aid = actuator_id[i] if aid != -1: act = actuation[s - 1, aid] color = rgb_to_hex((0.5 - act, 0.5 - abs(act), 0.5 + act)) canvas.circle(vec(x[s, i][0], x[s, i][1])).radius(2).color(color).finish() canvas.path(tc.vec(0.05, 0.02),
for i in range(n_objects): s = math.exp(-dt * damping) v[t, i] = s * v[t - 1, i] + v_inc[t, i] + dt * gravity * ti.Vector( [0.0, 1.0]) x[t, i] = x[t - 1, i] + dt * v[t, i] omega[t, i] = s * omega[t - 1, i] + omega_inc[t, i] rotation[t, i] = rotation[t - 1, i] + dt * omega[t, i] @ti.kernel def compute_loss(t: ti.i32): loss[None] = (x[t, head_id] - goal[None]).norm() import taichi as tc gui = tc.core.GUI('Rigid Body Simulation', tc.veci(1024, 1024)) canvas = gui.get_canvas() from renderer_vector import rgb_to_hex def forward(output=None, visualize=True): initialize_properties() interval = vis_interval total_steps = steps if output: print(output) interval = output_vis_interval os.makedirs('rigid_body/{}/'.format(output), exist_ok=True)
def advance_no_toi(t: ti.i32): for i in range(n_objects): new_v = v[t - 1, i] if x[t - 1, i][1] < ground_height and new_v[1] < 0: new_v[1] = -new_v[1] v[t, i] = new_v x[t, i] = x[t - 1, i] + dt * new_v @ti.kernel def compute_loss(t: ti.i32): # loss[None] = (x[t, 0] - ti.Vector(goal)).norm() loss[None] = x[t, 0][1] gui = ti.core.GUI("Rigid Body", ti.veci(1024, 1024)) canvas = gui.get_canvas() def forward(output=None, visualize=True): interval = vis_interval total_steps = steps if output: interval = output_vis_interval # os.makedirs('rigid_body/{}/'.format(output), exist_ok=True) total_steps *= 2 for t in range(1, total_steps): if use_toi: advance_toi(t) else:
def read_image(fn, linearize=False): img = taichi.core.Array2DVector3( taichi.veci(0, 0), taichi.vec(0.0, 0.0, 0.0)) img.read(fn, linearize) return img
def imread(fn, bgr=False): img = taichi.core.Array2DVector3( taichi.veci(0, 0), taichi.vec(0.0, 0.0, 0.0)) img.read(fn) return image_buffer_to_ndarray(img, bgr)[::-1]
gravitational_force = ti.Vector([0.0, 0.0]) for i in ti.static(range(n_gravitation)): # instead of this one r = x[t - 1] - ti.Vector(gravitation_position[i]) len_r = ti.max(r.norm(), 1e-1) gravitational_force += K * gravitation[t, i] / (len_r * len_r * len_r) * r v[t] = v[t - 1] * math.exp(-dt * damping) + dt * gravitational_force x[t] = x[t - 1] + dt * v[t] @ti.kernel def compute_loss(t: ti.i32): ti.atomic_add(loss[None], dt * (x[t] - goal[t]).norm_sqr()) gui = tc.core.GUI("Gravity", tc.veci(1024, 1024)) def forward(visualize=False, output=None): interval = vis_interval if output: interval = output_vis_interval os.makedirs('gravity/{}/'.format(output), exist_ok=True) canvas = gui.get_canvas() for t in range(1, steps): nn1(t) nn2(t) advance(t) compute_loss(t)
depth = old_x[1] - ground_height if depth < 0 and new_v[1] < 0: # friction projection new_v[0] = 0 new_v[1] = 0 new_x = old_x + dt * new_v v[t, i] = new_v x[t, i] = new_x @ti.kernel def compute_loss(t: ti.i32): ti.atomic_add(loss[None], dt * ti.sqr(target_v[t][0] - v[t, head_id][0])) gui = tc.core.GUI("Mass Spring Robot", tc.veci(1024, 1024)) canvas = gui.get_canvas() from renderer_vector import rgb_to_hex def forward(output=None, visualize=True): if random.random() > 0.5: goal[None] = [0.9, 0.2] else: goal[None] = [0.1, 0.2] goal[None] = [0.9, 0.2] interval = vis_interval if output: interval = output_vis_interval
import taichi as ti n = 320 pixels = ti.var(dt=ti.f32, shape=(n * 2, n)) @ti.func def complex_sqr(z): return ti.Vector([z[0] * z[0] - z[1] * z[1], z[1] * z[0] * 2]) # z^2 @ti.kernel def paint(t: ti.f32): for i, j in pixels: # Parallized over all pixels c = ti.Vector([-0.8, ti.cos(t) * 0.2]) z = ti.Vector([float(i) / n - 1, float(j) / n - 0.5]) * 2 iterations = 0 while z.norm() < 20 and iterations < 50: z = complex_sqr(z) + c iterations += 1 pixels[i, j] = 1 - iterations * 0.02 gui = ti.core.GUI("Julia Set", ti.veci(n * 2, n)) for i in range(1000000): paint(i * 0.03) gui.set_image(pixels) gui.update()
def advance_no_toi(t: ti.i32): for i in range(n_objects): new_v = v[t - 1, i] if x[t - 1, i][1] < ground_height and new_v[1] < 0: new_v[1] = -new_v[1] v[t, i] = new_v x[t, i] = x[t - 1, i] + dt * new_v @ti.kernel def compute_loss(t: ti.i32): # loss[None] = (x[t, 0] - ti.Vector(goal)).norm() loss[None] = x[t, 0][1] gui = tc.core.GUI("Rigid Body", tc.veci(1024, 1024)) canvas = gui.get_canvas() def forward(output=None, visualize=True): interval = vis_interval total_steps = steps if output: interval = output_vis_interval # os.makedirs('rigid_body/{}/'.format(output), exist_ok=True) total_steps *= 2 for t in range(1, total_steps): if use_toi: advance_toi(t) else:
gravitational_force = ti.Vector([0.0, 0.0]) for i in ti.static(range(n_gravitation)): # instead of this one r = x[t - 1] - ti.Vector(gravitation_position[i]) len_r = ti.max(r.norm(), 1e-1) gravitational_force += K * gravitation[t, i] / (len_r * len_r * len_r) * r v[t] = v[t - 1] * math.exp(-dt * damping) + dt * gravitational_force x[t] = x[t - 1] + dt * v[t] @ti.kernel def compute_loss(t: ti.i32): ti.atomic_add(loss[None], dt * (x[t] - goal[t]).norm_sqr()) gui = tc.core.GUI("Electric", tc.veci(1024, 1024)) def forward(visualize=False, output=None): interval = vis_interval if output: interval = output_vis_interval os.makedirs('electric/{}/'.format(output), exist_ok=True) canvas = gui.get_canvas() for t in range(1, steps): nn1(t) nn2(t) advance(t) compute_loss(t)