def main(): for f in range(args.begin, args.end, args.step): print('frame', f, end=' ') output_fn = f'{output_folder}/{f:05d}.png' if os.path.exists(output_fn) and not args.force: print('skip.') continue else: print('rendering...') Path(output_fn).touch() t = time.time() renderer.set_camera_pos(3.24, 1.86, -4.57) renderer.floor_height[None] = -5e-3 renderer.initialize_particles_from_taichi_elements( f'{args.in_dir}/{f:05d}.npz') total_voxels = renderer.total_non_empty_voxels() total_inserted_particles = renderer.total_inserted_particles() print('Total particles (with motion blur)', total_inserted_particles) print('Total nonempty voxels', total_voxels) print('Average particle_list_length', total_inserted_particles / total_voxels) img = renderer.render_frame(spp=spp) if with_gui: gui.set_image(img) gui.show(output_fn) else: ti.imwrite(img, output_fn) print(f'Frame rendered. {spp} take {time.time() - t} s.')
def main(): for f in range(int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4])): print('frame', f, end=' ') output_fn = f'{output_folder}/{f:05d}.png' if os.path.exists(output_fn): print('skip.') continue else: print('rendering...') Path(output_fn).touch() t = time.time() renderer.initialize_particles_from_taichi_elements( f'{sys.argv[1]}/{f:05d}.npz') total_voxels = renderer.total_non_empty_voxels() total_inserted_particles = renderer.total_inserted_particles() print('Total particles (with motion blur)', total_inserted_particles) print('Total nonempty voxels', total_voxels) print('Average particle_list_length', total_inserted_particles / total_voxels) img = renderer.render_frame(spp=spp) if with_gui: gui.set_image(img) gui.show(output_fn) else: ti.imwrite(img, output_fn) print(f'Frame rendered. {spp} take {time.time() - t} s.')
def main(): gui = ti.GUI("Logistic Map", res=(WIDTH, HEIGHT)) paused = False save_screenshot = False ts = 0 while True: while gui.get_event(ti.GUI.PRESS): e = gui.event if e.key == ti.GUI.ESCAPE: exit(0) elif e.key == "p": paused = not paused elif e.key == "s": save_screenshot = True if not paused: render(ts * 0.03) ts += 1 img = pixels.to_numpy() if save_screenshot: ti.imwrite(img, "screenshot.png") save_screenshot = False gui.set_image(img) gui.show()
def display(self, step_index): ### These are slow, to be removed # self.display_img.fill(0.0) # self.display_setimage() # self.gui.set_image(self.display_img) ## self.display_elem_q_raw(3) ## field should be displayed at the bottom, draw grids/arrows later if self.display_field: self.display_elem_q() ## grid and center, velocity arrows if self.display_show_grid: self.display_grid() if self.display_show_xc: self.display_xc() if self.display_show_velocity: self.display_v() if self.display_show_surface: self.display_surf_norm(self.display_show_surface_norm) ## output quantities on monitor points to console for point in self.output_monitor_points: self.print_output_monitor_point(point) ## output gif if self.display_gif_files: gif_name = f'img_{step_index:03}.png' ti.imwrite(self.gui.get_image(), gif_name) self.gui.show()
def test_image_io(): pixel = (np.random.rand(128, 128, 3) * 255).astype(np.uint8) for ext in ['bmp', 'png']: # jpg is also supported but hard to test here since it's lossy fn = 'taichi-image-io-test.' + ext ti.imwrite(pixel, fn) pixel_r = ti.imread(fn) assert (pixel_r == pixel).all() os.remove(fn)
def test_image_io_vector(resx, resy, comp, ext, dt): shape = (resx, resy) pixel = np.random.rand(*shape, comp).astype(to_numpy_type(dt)) pixel_t = ti.Vector.field(comp, dt, shape) pixel_t.from_numpy(pixel) fn = make_temp_file(suffix='.' + ext) ti.imwrite(pixel_t, fn) pixel_r = (ti.imread(fn).astype(to_numpy_type(dt)) + 0.5) / 256.0 assert np.allclose(pixel_r, pixel, atol=2e-2) os.remove(fn)
def test_image_io_uint(resx, resy, comp, ext, dt): shape = (resx, resy) np_type = to_numpy_type(dt) # When saving to disk, pixel data will be truncated into 8 bits. # Be careful here if you want lossless saving. np_max = np.iinfo(np_type).max // 256 pixel = np.random.randint(256, size=(*shape, comp), dtype=np_type) * np_max pixel_t = ti.Vector.field(comp, dt, shape) pixel_t.from_numpy(pixel) fn = make_temp_file(suffix='.' + ext) ti.imwrite(pixel_t, fn) pixel_r = ti.imread(fn).astype(np_type) * np_max assert (pixel_r == pixel).all() os.remove(fn)
def test_image_io(resx, resy, comp, ext, is_field, dt): if comp != 1: shape = (resx, resy, comp) else: shape = (resx, resy) if is_field: pixel_t = ti.field(dt, shape) pixel = np.random.randint(256, size=shape, dtype=to_numpy_type(dt)) if is_field: pixel_t.from_numpy(pixel) fn = make_temp_file(suffix='.' + ext) if is_field: ti.imwrite(pixel_t, fn) else: ti.imwrite(pixel, fn) pixel_r = ti.imread(fn) if comp == 1: # from (resx, resy, 1) to (resx, resy) pixel_r = pixel_r.reshape((resx, resy)) assert (pixel_r == pixel).all() os.remove(fn)
def main(): for f in range(int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4])): print('frame', f, end='') output_fn = f'{output_folder}/{f:05d}.png' if os.path.exists(output_fn): print('skip.') continue else: print('rendering...') Path(output_fn).touch() t = time.time() renderer.initialize_particles(f'{sys.argv[1]}/{f:05d}.npz') print('Average particle_list_length', renderer.average_particle_list_length()) img = renderer.render_frame(spp=spp) if with_gui: gui.set_image(img) gui.show(output_fn) else: ti.imwrite(img, output_fn) print(f'Frame rendered. {spp} take {time.time() - t} s.')
list_particle_indices = list(range(num_particles)) list_combination = list(itertools.combinations(list_particle_indices, 2)) colors = np.array([0x0033FF, 0xFF3333], dtype=np.uint32) # For this many time steps for i in range(100000): # Drawing the ground, springs and particles on the screen print("loop ", i) gui.line([0, GROUND], [1, GROUND], radius=2, color=0x617763) if spring_debug: drawSprings() gui.circles(x, radius=particle_radius, color=colors[pinned]) if ti.static(write_image): ti.imwrite(gui.get_image(), image_dir + project_name + "_debug_" + str(g_rows) + "x" + str(g_cols) + "_" + str(i) + ".png") else: gf.draw_shape(gui, x, outer_particles_indices, out_length, color_shape, thickness) if ti.static(write_image): ti.imwrite(gui.get_image(), image_dir + project_name + "_" + str(g_rows) + "x" + str(g_cols) + "_" + str(i) + ".png") # print("loopa ", i) gui.show() # Peform 1 RK4 step for k in ti.static(range(num_substeps)): rk4_step() # ti.sync() # print("loopb ", i, ", ", k)
if draw_center: gui.circle(get_center(), radius=particle_radius, color=0xFFFFFF) if draw_bounding_box_flag: draw_bounding_box(get_bounding_box_coords()) if draw_triangulation_flag: draw_triangulation() # Drawing the ground, springs and particles on the screen gui.line([0, GROUND], [1, GROUND], radius=2, color=0x617763) if spring_debug: drawSprings() gui.circles(x, radius=particle_radius, color=colors[pinned]) if write_image: ti.imwrite( gui.get_image(), image_dir + project_name + "_debug_" + str(num_particles) + "_" + str(i) + ".png") else: bf.draw_shape(gui, x, num_particles, color_shape, thickness) if write_image: ti.imwrite( gui.get_image(), image_dir + project_name + "_" + str(num_particles) + "_" + str(i) + ".png") gui.show() # Peform 1 RK4 step for k in ti.static(range(num_substeps)): update_phase_space(phase_space) RK4_update()
if gui.is_pressed('1', ti.GUI.LEFT): mode = 1 reset_cloth() if gui.is_pressed('2', ti.GUI.LEFT): mode = 2 reset_cloth() #start_time = time.perf_counter() for i in range(0, 20): if mode == 0: integrator_explicit() if mode == 1: integrator_implicit() if mode == 2: integrator_verlet() #end_time = time.perf_counter() #print("{:.4f}".format(end_time - start_time)) clear() draw_mass_point() draw_grid() gui.set_image(img.to_numpy()) gui.show() ti.imwrite(img, str(frame)+ ".png") frame += 1
import taichi as ti import os pixel = ti.field(ti.u8, shape=(512, 512, 3)) @ti.kernel def paint(): for I in ti.grouped(pixel): pixel[I] = ti.random() * 255 paint() pixel = pixel.to_numpy() ti.imshow(pixel, 'Random Generated') for ext in ['bmp', 'png', 'jpg']: fn = 'taichi-example-random-img.' + ext ti.imwrite(pixel, fn) pixel_r = ti.imread(fn) if ext != 'jpg': assert (pixel_r == pixel).all() else: ti.imshow(pixel_r, 'JPEG Read Result') os.remove(fn)
import taichi as ti import numpy as np import tina ti.init(ti.gpu) scene = tina.PTScene(smoothing=True, texturing=True) scene.load_gltf('assets/cornell.gltf') scene.add_object(tina.MeshTransform(tina.MeshModel('assets/plane.obj'), tina.translate([0, 3.98, 0]) @ tina.scale(0.1)), tina.Lamp(color=64)) if isinstance(scene, tina.PTScene): scene.update() gui = ti.GUI('cornell_box', scene.res) scene.init_control(gui, center=(0, 2, 0), radius=5) while gui.running: scene.input(gui) if isinstance(scene, tina.PTScene): scene.render(nsteps=8) else: scene.render() gui.set_image(scene.img) gui.show() ti.imwrite(scene.img, 'cornell.png')
framerate=24, automatic_build=False) # Setup Raycaster vr.set_volume(vol) vr.cam_pos[None] = tl.vec3(*in_circles(t)) # Create Reference if necessary if args.ref: # Generate new reference vr.set_tf_tex(tf) vr.forward(args.fw_sampling_rate, jitter=False) plot_tf(vr.tf_tex.to_torch().permute( 1, 0).contiguous()).savefig('temp_tf_reference.png') gui_fw.set_image(vr.output_rgb) gui_fw.show() gui_bw.set_image(vr.output_rgb) gui_bw.show() ti.imwrite(vr.output_rgba, 'temp_reference.png') vr.set_reference(vr.output_rgba.to_numpy()) else: # Use old reference vr.set_reference(ti.imread('temp_reference.png') / 255.0) # Optimize for Transfer Function vr.set_tf_tex(tf_init) # initial tf lr = args.lr for i in range(args.iterations): # Optimization vr.backward(args.bw_sampling_rate, jitter=args.bw_jitter) # computes grads vr.apply_grad(lr, args.mom, args.clip_grads) # Gradient descent with momentum lr *= args.lr_decay # decay # Log Backward Pass
import taichi as ti ti.init() ## Load the image: input_file_name = input('Enter the input image file name: ') input_image = ti.imread(input_file_name) ## Process the image: image = ti.field(ti.u8, input_image.shape) image.from_numpy(input_image) @ti.kernel def process(): for i, j, k in image: image[i, j, k] = 255 - image[i, j, k] # revert color process() ## Save the image: output_image = image.to_numpy() ti.imshow(output_image) output_file_name = input('Enter the image file name to save: ') ti.imwrite(output_image, output_file_name)
# tex[I][1] = ti.abs(x[I // dx][1])/x[I // dx].norm() # tex[I][2] = 1.0 p_max = p_old[I].x if p_old[I].x > p_max else p_max p_min = p_old[I].x if p_old[I].x < p_min else p_min # x += p_old[I].x for I in ti.grouped(tex): tex[I].fill((p_old[I].x - p_min) / (p_max - p_min)) def step(dt): advection(dt) diffusion(dt, 40) #addRandomForce(dt) projection(dt, 100) #################### ## Main Execution ## #################### init() gui = ti.GUI("Test", tex_size, background_color=0x112F41, fast_gui=True) for i in range(180): #while not gui.get_event(ti.GUI.ESCAPE, ti.GUI.EXIT): step(1. / 100) render(u_old) #gui.set_image(tex) if (i == 49): ti.imwrite(tex.to_numpy(), 'test.png') #gui.show(f'test.png')
s_rest_lengths[i] = tmp.dot(tmp) # -------------------------- Main -------------------------- # gui = ti.GUI("test", res=(width, height)) initialize() colors = np.array([0x0033FF, 0xFF3333], dtype=np.uint32) # For this many time steps for i in range(10000): # Drawing the ground, springs and particles on the screen gui.line([0, GROUND], [1, GROUND], radius=2, color=0x617763) gui.circles(x, radius=particle_radius, color=colors[pinned]) drawSprings() if ti.static(write_image): ti.imwrite(gui.get_image(), image_dir + project_name + "_" + str(i) + ".png") gui.show() # Peform 1 RK4 step for k in ti.static(range(num_substeps)): rk4_step() # Draws the ground check_ground() # ------------------------------------------------------------------------ #