### Run Taichi MPM128 Example Source: https://docs.taichi-lang.org/docs/dev_install Executes a specific Taichi example script to verify the installation. Ensure you are in the Taichi project directory. ```bash python3 python/taichi/examples/simulation/mpm128.py ``` -------------------------------- ### View All Taichi Examples Source: https://docs.taichi-lang.org/docs/hello_world Execute this command to access the complete list of Taichi examples. ```bash ti example ``` -------------------------------- ### Install Test Dependencies Source: https://docs.taichi-lang.org/docs/write_test Before running the test launcher, install the necessary dependencies using pip. ```bash pip install -r requirements_test.txt ``` -------------------------------- ### Install ffmpeg on Ubuntu Source: https://docs.taichi-lang.org/docs/export_results Use apt-get to install ffmpeg on Ubuntu systems. ```bash sudo apt-get update sudo apt-get install ffmpeg ``` -------------------------------- ### Save Fractal Example Source: https://docs.taichi-lang.org/docs/hello_world Run this command to save the fractal example to your current working directory. ```bash ti example -s fractal ``` -------------------------------- ### Install Taichi from Wheel Package Source: https://docs.taichi-lang.org/docs/faq Install Taichi and its dependencies using downloaded wheel packages on a local server. Ensure all dependencies are installed before Taichi. ```bash python -m pip install xxxx.whl ``` -------------------------------- ### Install pre-commit Source: https://docs.taichi-lang.org/docs/contributor_guide Install the pre-commit tool, which is used to enforce code style checks. ```bash pip install pre-commit ``` -------------------------------- ### Print Fractal Example Source Code Source: https://docs.taichi-lang.org/docs/hello_world Use this command to print the source code of the fractal example. ```bash ti example -p fractal ``` -------------------------------- ### Print Fractal Example Source Code (Alternative) Source: https://docs.taichi-lang.org/docs/hello_world An alternative command to print the source code of the fractal example. ```bash ti example -P fractal ``` -------------------------------- ### Install ffmpeg on Arch Linux Source: https://docs.taichi-lang.org/docs/export_results Use pacman to install ffmpeg on Arch Linux. ```bash pacman -S ffmpeg ``` -------------------------------- ### Install Taichi Package Source: https://docs.taichi-lang.org/docs/hello_world Install the Taichi package using pip. This is a prerequisite for using Taichi. ```bash pip install taichi ``` -------------------------------- ### Install Taichi Nightly Source: https://docs.taichi-lang.org/docs/tutorial Install the Taichi nightly build for compiling kernels. Ensure you use a version compatible with your project. ```bash pip install -i https://pypi.taichi.graphics/simple/ taichi-nightly ``` -------------------------------- ### Test ffmpeg Installation on Windows Source: https://docs.taichi-lang.org/docs/export_results Run this command in Windows cmd or PowerShell to verify ffmpeg installation. ```bash ffmpeg -version ``` -------------------------------- ### Check Vulkan SDK Installation on Linux Source: https://docs.taichi-lang.org/docs/dev_install After enabling the Vulkan backend, enter the Taichi build shell and run 'vulkaninfo' to confirm the Vulkan SDK is properly installed and configured. ```bash ./build.py --shell ``` ```bash vulkaninfo ``` -------------------------------- ### Example: Fetching Color Information Source: https://docs.taichi-lang.org/docs/ggui Demonstrates fetching the color buffer as a NumPy array and writing it as a video frame. ```python window = ti.ui.Window("Test for getting image buffer from ggui", (768, 768), vsync=True) video_manager = ti.tools.VideoManager("OutputDir") while window.running: # render_scene() img = window.get_image_buffer_as_numpy() video_manager.write_frame(img) window.show() video_manager.make_video(gif=True, mp4=True) ``` -------------------------------- ### Install Taichi from a Mirror Source Source: https://docs.taichi-lang.org/docs/install Use this pip command to install Taichi from a mirror source if the default download process is interrupted by HTTPSConnection errors. ```bash pip install taichi -i https://pypi.douban.com/simple ``` -------------------------------- ### Example: Constructing Matrix from Rows Source: https://docs.taichi-lang.org/api/taichi Demonstrates how to create a matrix by providing a list of vectors as rows. ```python >>> @ti.kernel def test(): v1 = ti.Vector([1, 2, 3]) v2 = ti.Vector([4, 5, 6]) m = ti.Matrix.rows([v1, v2]) print(m) >>> test() [[1, 2, 3], [4, 5, 6]] ``` -------------------------------- ### Check Vulkan SDK Installation on Windows Source: https://docs.taichi-lang.org/docs/dev_install After enabling the Vulkan backend, enter the Taichi build shell using Python and run 'vulkaninfo' to confirm the Vulkan SDK is properly installed and configured. ```powershell python ./build.py --shell ``` ```powershell vulkaninfo ``` -------------------------------- ### Install Taichi in User Space Source: https://docs.taichi-lang.org/docs/dev_install Workaround for 'permission denied' errors during installation. Installs Taichi packages into the user's home directory, avoiding the need for root privileges. ```bash python3 setup.py develop --user ``` ```bash python3 setup.py install --user ``` -------------------------------- ### Test ffmpeg Installation on Linux Source: https://docs.taichi-lang.org/docs/export_results Run this command on Linux to check if ffmpeg is installed and accessible. ```bash ffmpeg -h ``` -------------------------------- ### Install ffmpeg on macOS Source: https://docs.taichi-lang.org/docs/export_results Install ffmpeg on macOS using the homebrew package manager. ```bash brew install ffmpeg ``` -------------------------------- ### Install CUDA on Arch Linux Source: https://docs.taichi-lang.org/docs/dev_install Install the CUDA toolkit on Arch Linux using the pacman package manager. ```bash pacman -S cuda ``` -------------------------------- ### Install wget using Homebrew Source: https://docs.taichi-lang.org/docs/dev_install Installs the 'wget' utility on macOS using the Homebrew package manager. This is a workaround for macOS systems that do not come with 'wget' pre-installed. ```bash brew install wget ``` -------------------------------- ### Check CUDA Installation Source: https://docs.taichi-lang.org/docs/dev_install Verify that the CUDA toolkit is correctly installed and accessible on your system by running the nvidia-smi command. ```bash nvidia-smi ``` -------------------------------- ### Install pre-commit hooks Source: https://docs.taichi-lang.org/docs/contributor_guide Install pre-commit as a git hook to automatically run checks before each commit. ```bash pre-commit install ``` -------------------------------- ### Install ffmpeg on CentOS and RHEL Source: https://docs.taichi-lang.org/docs/export_results Use yum to install ffmpeg on CentOS and RHEL systems. ```bash sudo yum install ffmpeg ffmpeg-devel ``` -------------------------------- ### Python Logging Examples Source: https://docs.taichi-lang.org/docs/developer_utilities Demonstrates how to write logs at different levels in Python using the ti.* interface. Ensure ti is imported. ```python import taichi as ti ti.trace("Hello world!") ti.debug("Hello world!") ti.info("Hello world!") ti.warn("Hello world!") ti.error("Hello world!") ``` -------------------------------- ### User Input Processing Example (mpm128) Source: https://docs.taichi-lang.org/docs/ggui An example demonstrating keyboard and mouse event processing for user input, including movement controls and mouse button actions. ```python gravity = ti.Vector.field(2, ti.f32, shape=()) attractor_strength = ti.field(ti.f32, shape=()) while window.running: # keyboard event processing if window.get_event(ti.ui.PRESS): if window.event.key == 'r': reset() elif window.event.key in [ti.ui.ESCAPE]: break if window.event is not None: gravity[None] = [0, 0] # if had any event if window.is_pressed(ti.ui.LEFT, 'a'): gravity[None][0] = -1 if window.is_pressed(ti.ui.RIGHT, 'd'): gravity[None][0] = 1 if window.is_pressed(ti.ui.UP, 'w'): gravity[None][1] = 1 if window.is_pressed(ti.ui.DOWN, 's'): gravity[None][1] = -1 # mouse event processing mouse = window.get_cursor_pos() # ... if window.is_pressed(ti.ui.LMB): attractor_strength[None] = 1 if window.is_pressed(ti.ui.RMB): attractor_strength[None] = -1 window.show() ``` -------------------------------- ### Taichi List Generation Example Source: https://docs.taichi-lang.org/docs/internal Demonstrates how Taichi generates lists for sparse data structures. This example initializes fields and defines a kernel that triggers list generation for different SNode types. ```python import taichi as ti ti.init(print_ir=True) x = ti.field(ti.i32) S0 = ti.root S1 = S0.dense(ti.i, 4) S2 = S1.bitmasked(ti.i, 4) S2.place(x) @ti.kernel def func(): for i in x: print(i) func() ``` -------------------------------- ### Example: Creating a VectorNdarray Source: https://docs.taichi-lang.org/api/taichi Shows the instantiation of a VectorNdarray with specified vector size, data type, and shape. ```python >>> a = ti.VectorNdarray(3, ti.f32, (3, 3)) ``` -------------------------------- ### Taichi Sine Function Example Source: https://docs.taichi-lang.org/api/taichi Demonstrates calculating the sine of elements in a Taichi matrix. ```python >>> from math import pi >>> x = ti.Matrix([-pi/2., 0, pi/2.]) >>> ti.sin(x) [-1., 0., 1.] ``` -------------------------------- ### Camera Setup and Control Source: https://docs.taichi-lang.org/api/taichi/ui Demonstrates how to initialize a camera, set its position, lookat, and up vectors, and attach it to a window for user input tracking. This is useful for interactive 3D scenes. ```python >>> scene = ti.ui.Scene() # assume you have a scene >>> >>> camera = ti.ui.Camera() >>> camera.position(1, 1, 1) # set camera position >>> camera.lookat(0, 0, 0) # set camera lookat >>> camera.up(0, 1, 0) # set camera up vector >>> scene.set_camera(camera) >>> >>> # you can also control camera movement in a window >>> window = ti.ui.Window("GGUI Camera", res=(640, 480), vsync=True) >>> camera.track_user_inputs(window, movement_speed=0.03, hold_key=ti.ui.RMB) ``` -------------------------------- ### Uninstall Taichi Pip Build Source: https://docs.taichi-lang.org/docs/dev_install Uninstalls Taichi when it was installed using 'pip'. This is part of the process to get a fresh Taichi build. ```bash pip uninstall taichi ``` -------------------------------- ### Setup ti.tools.PLYWriter Source: https://docs.taichi-lang.org/docs/export_results Initialize PLYWriter with the number of vertices and optionally the number of faces and face type. num_vertices must be a positive integer. ```python # num_vertices must be a positive int # num_faces is optional, default to 0 # face_type can be either "tri" or "quad", default to "tri" # in our previous example, a writer with 1000 vertices and 0 triangle faces is created num_vertices = 1000 writer = ti.tools.PLYWriter(num_vertices=num_vertices) # in the below example, a writer with 20 vertices and 5 quadrangle faces is created writer2 = ti.tools.PLYWriter(num_vertices=20, num_faces=5, face_type="quad") ``` -------------------------------- ### Define Sparse Data Structure Source: https://docs.taichi-lang.org/docs/sparse Defines a sparse data structure using Taichi's root, pointer, and bitmasked SNodes. This setup is used for subsequent sparsity manipulation examples. ```python x = ti.field(dtype=ti.i32) block1 = ti.root.pointer(ti.ij, (3, 3)) block2 = block1.pointer(ti.ij, (2, 2)) pixel = block2.bitmasked(ti.ij, (2, 2)) pixel.place(x) ``` -------------------------------- ### Initialize Taichi with CPU Backend Source: https://docs.taichi-lang.org/docs/accelerate_python Import Taichi and initialize it to use the CPU backend for accelerated computation. This is the first step to leverage Taichi's performance. ```python import taichi as ti ti.init(arch=ti.cpu) ``` -------------------------------- ### CMakeLists.txt for Taichi C-API Project Source: https://docs.taichi-lang.org/docs/tutorial Configure CMake to find the Taichi installation and link the Taichi runtime library to the executable. ```cmake cmake_minimum_required(VERSION 3.17) set(TAICHI_AOT_APP_NAME TaichiAot) project(${TAICHI_AOT_APP_NAME} LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) # Declare executable target. add_executable(${TAICHI_AOT_APP_NAME} app.cpp) target_include_directories(${TAICHI_AOT_APP_NAME} PUBLIC ${TAICHI_C_API_INSTALL_DIR}/include) # Find and link Taichi runtime library. set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake) find_package(Taichi REQUIRED) target_link_libraries(${TAICHI_AOT_APP_NAME} Taichi::Runtime) ``` -------------------------------- ### Create and Fill Sparse Matrix Builder Source: https://docs.taichi-lang.org/docs/sparse_matrix Demonstrates the three steps to use sparse matrices: creating a builder, filling it with data using a kernel, and building the sparse matrix. Supports += and -= operators for filling. ```python import taichi as ti arch = ti.cpu # or ti.cuda ti.init(arch=arch) n = 4 # step 1: create sparse matrix builder K = ti.linalg.SparseMatrixBuilder(n, n, max_num_triplets=100) @ti.kernel def fill(A: ti.types.sparse_matrix_builder()): for i in range(n): A[i, i] += 1 # Only += and -= operators are supported for now. # step 2: fill the builder with data. fill(K) print(">>>> K.print_triplets()") K.print_triplets() # outputs: # >>>> K.print_triplets() # n=4, m=4, num_triplets=4 (max=100)(0, 0) val=1.0(1, 1) val=1.0(2, 2) val=1.0(3, 3) val=1.0 # step 3: create a sparse matrix from the builder. A = K.build() print(">>>> A = K.build()") print(A) # outputs: # >>>> A = K.build() # [1, 0, 0, 0] # [0, 1, 0, 0] # [0, 0, 1, 0] # [0, 0, 0, 1] ``` -------------------------------- ### Taichi Field Layout Example Source: https://docs.taichi-lang.org/api/taichi Demonstrates how to define and place a Taichi field using nested layout functions. ```python >>> x = ti.field(ti.f32) >>> ti.root.pointer(ti.ij, 4).dense(ti.ij, 8).place(x) ``` -------------------------------- ### Gui.begin Source: https://docs.taichi-lang.org/api/taichi/ui Creates a subwindow that holds imgui widgets. ```APIDOC ## Gui.begin ### Description Creates a subwindow that holds imgui widgets. All widget function calls (e.g. text, button) after the begin and before the next end will describe the widgets within this subwindow. ### Parameters * **name** (str): The name of the subwindow. * **x** (float): The x-coordinate (between 0 and 1) of the top-left corner of the subwindow, relative to the full window. * **y** (float): The y-coordinate (between 0 and 1) of the top-left corner of the subwindow, relative to the full window. * **width** (float): The width of the subwindow relative to the full window. * **height** (float): The height of the subwindow relative to the full window. ``` -------------------------------- ### Taichi Static Compile-Time Loop Unrolling Example Source: https://docs.taichi-lang.org/api/taichi Demonstrates using taichi.static with a range to achieve compile-time loop unrolling. ```python >>> @ti.kernel >>> def run(): >>> for i in ti.static(range(3)): >>> print(i) >>> >>> # The above will be unrolled to: >>> @ti.kernel >>> def run(): >>> print(0) >>> print(1) >>> print(2) ``` -------------------------------- ### Initialize Structs with Positional and Keyword Arguments Source: https://docs.taichi-lang.org/docs/type Demonstrates various ways to initialize struct instances, including positional arguments, keyword arguments, and default zero initialization. ```python @ti.dataclass class Ray: ro: vec3 rd: vec3 t: float # The definition above is equivalent to #Ray = ti.types.struct(ro=vec3, rd=vec3, t=float) # Use positional arguments to set struct members in order ray = Ray(vec3(0), vec3(1, 0, 0), 1.0) # ro is set to vec3(0) and t will be set to 0 ray = Ray(vec3(0), rd=vec3(1, 0, 0)) # both ro and rd are set to vec3(0) ray = Ray(t=1.0) # ro is set to vec3(1), rd=vec3(0) and t=0.0 ray = Ray(1) # All members are set to 0 ray = Ray() ``` -------------------------------- ### GGUI GUI Components Example Source: https://docs.taichi-lang.org/docs/ggui Demonstrates the usage of GGUI components like text, buttons, sliders, and color edits, following Dear ImGui APIs. ```python window = ti.ui.Window("Test for GUI", res=(512, 512)) gui = window.get_gui() value = 0 color = (1.0, 1.0, 1.0) with gui.sub_window("Sub Window", x=10, y=10, width=300, height=100): gui.text("text") is_clicked = gui.button("name") value = gui.slider_float("name1", value, minimum=0, maximum=100) color = gui.color_edit_3("name2", color) ``` -------------------------------- ### C++ Logging Examples Source: https://docs.taichi-lang.org/docs/developer_utilities Shows how to write logs at different levels in C++ using the TI_* interface. Ensure necessary Taichi headers are included. ```cpp #include TI_TRACE("Hello world!"); TI_DEBUG("Hello world!"); TI_INFO("Hello world!"); TI_WARN("Hello world!"); TI_ERROR("Hello world!"); ``` -------------------------------- ### Open Taichi Gallery Source: https://docs.taichi-lang.org/docs/hello_world Run this command to open the Taichi gallery and view featured demos. ```bash ti gallery ``` -------------------------------- ### Prepare and Launch Kernel with Positional Arguments Source: https://docs.taichi-lang.org/docs/taichi_core Prepares a TiNdArray and several TiArgument objects for launching a kernel. Ensure types, sizes, and order match the source code. ```c++ TiNdArray ndarray{}; ndarray.memory = get_some_memory(); ndarray.shape.dim_count = 1; ndarray.shape.dims[0] = 16; ndarray.elem_shape.dim_count = 2; ndarray.elem_shape.dims[0] = 4; ndarray.elem_shape.dims[1] = 4; ndarray.elem_type = TI_DATA_TYPE_F32; std::array args{}; TiArgument& arg0 = args[0]; arg0.type = TI_ARGUMENT_TYPE_I32; arg0.value.i32 = 123; TiArgument& arg1 = args[1]; arg1.type = TI_ARGUMENT_TYPE_F32; arg1.value.f32 = 123.0f; TiArgument& arg2 = args[2]; arg2.type = TI_ARGUMENT_TYPE_NDARRAY; arg2.value.ndarray = ndarray; ti_launch_kernel(runtime, kernel, args.size(), args.data()); ``` -------------------------------- ### Create a GGUI Window Source: https://docs.taichi-lang.org/docs/ggui Initializes a new GGUI window with a specified title, resolution, FPS limit, and position. The window serves as the base for rendering UI elements. ```python window = ti.ui.Window(name='Window Title', res = (640, 360), fps_limit=200, pos = (150, 150)) ``` -------------------------------- ### Show all test options Source: https://docs.taichi-lang.org/docs/contributor_guide Display all available command-line options for the test runner script. ```bash python tests/run_tests.py -h ``` -------------------------------- ### Start Recording Taichi Kernel Information Source: https://docs.taichi-lang.org/api/taichi/aot Starts recording kernel information to a yml file. This function should be paired with `stop_recording()` and is useful for debugging and analysis. ```python ti.aot.start_recording('record.yml') ti.init(arch=ti.cc) loss = ti.field(float, (), needs_grad=True) x = ti.field(float, 233, needs_grad=True) @ti.kernel def compute_loss(): for i in x: loss[None] += x[i]**2 @ti.kernel def do_some_works(): for i in x: x[i] -= x.grad[i] with ti.ad.Tape(loss): compute_loss() do_some_works() ``` -------------------------------- ### Instantiate and Build a Taichi Mesh Model Source: https://docs.taichi-lang.org/api/taichi Demonstrates how to instantiate a mesh builder, define vertex attributes, and build a Taichi mesh model. ```python mesh_builder = ti.Mesh.tri() mesh_builder.verts.place({ 'x' : ti.f32, 'y' : ti.f32 }) model = mesh_builder.build(meta) ``` -------------------------------- ### Taichi IR Output Example Source: https://docs.taichi-lang.org/docs/internal This is an example of the Intermediate Representation (IR) generated by Taichi for a simple kernel. It showcases the static-single assignment and hierarchical nature of the IR. ```text kernel { $0 = offloaded range_for(0, 10) grid_dim=0 block_dim=32 body { $1 = loop $0 index 0 $2 = const [4] $3 = cmp_lt $1 $2 $4 = const [1] $5 = bit_and $3 $4 $6 : if $5 { print $1, "\n" } } } ``` -------------------------------- ### Example of ti.static_assert in a Function Source: https://docs.taichi-lang.org/docs/debugging This example demonstrates using `ti.static_assert` within a Taichi function to ensure that the shapes of source and destination fields match before copying elements. ```python @ti.func def copy(dst: ti.template(), src: ti.template()): ti.static_assert(dst.shape == src.shape, "copy() needs src and dst fields to be same shape") for I in ti.grouped(src): dst[I] = src[I] ``` -------------------------------- ### Launching a Kernel Source: https://docs.taichi-lang.org/docs/taichi_core Shows how to launch a Taichi kernel with positional arguments. Ensure argument types, sizes, and order match the Python source. ```APIDOC ## Launching a Kernel ### Description You can launch a kernel with positional arguments. Please ensure the types, the sizes and the order matches the source code in Python. ### Code Example ```c++ TiNdArray ndarray{}; ndarray.memory = get_some_memory(); ndarray.shape.dim_count = 1; ndarray.shape.dims[0] = 16; ndarray.elem_shape.dim_count = 2; ndarray.elem_shape.dims[0] = 4; ndarray.elem_shape.dims[1] = 4; ndarray.elem_type = TI_DATA_TYPE_F32; std::array args{}; TiArgument& arg0 = args[0]; arg0.type = TI_ARGUMENT_TYPE_I32; arg0.value.i32 = 123; TiArgument& arg1 = args[1]; arg1.type = TI_ARGUMENT_TYPE_F32; arg1.value.f32 = 123.0f; TiArgument& arg2 = args[2]; arg2.type = TI_ARGUMENT_TYPE_NDARRAY; arg2.value.ndarray = ndarray; ti_launch_kernel(runtime, kernel, args.size(), args.data()); ``` ``` -------------------------------- ### Launching a Compute Graph Source: https://docs.taichi-lang.org/docs/taichi_core Explains how to launch a compute graph, emphasizing the need for matching argument names with the Python source. ```APIDOC ## Launching a Compute Graph ### Description You can launch a compute graph in a similar way. But additionally please ensure the argument names matches those in the Python source. ### Code Example ```c++ std::array named_args{}; TiNamedArgument& named_arg0 = named_args[0]; named_arg0.name = "foo"; named_arg0.argument = args[0]; TiNamedArgument& named_arg1 = named_args[1]; named_arg1.name = "bar"; named_arg1.argument = args[1]; TiNamedArgument& named_arg2 = named_args[2]; named_arg2.name = "baz"; named_arg2.argument = args[2]; ti_launch_compute_graph(runtime, compute_graph, named_args.size(), named_args.data()); ``` ``` -------------------------------- ### Taichi OpenGL Stack Trace Example Source: https://docs.taichi-lang.org/docs/install Example of a stack trace indicating a segmentation fault related to OpenGL initialization, often due to an old OpenGL API version. ```text [Taichi] mode=release [E 05/12/20 18.25:00.129] Received signal 11 (Segmentation Fault) *********************************** * Taichi Compiler Stack Traceback * *********************************** ... (many lines, omitted) /lib/python3.8/site-packages/taichi/core/../lib/taichi_python.so: _glfwPlatformCreateWindow /lib/python3.8/site-packages/taichi/core/../lib/taichi_python.so: glfwCreateWindow /lib/python3.8/site-packages/taichi/core/../lib/taichi_python.so: taichi::lang::opengl::initialize_opengl(bool) ... (many lines, omitted) ``` -------------------------------- ### Example: Fetching Depth Data Source: https://docs.taichi-lang.org/docs/ggui An example of fetching depth data into a Taichi ndarray or field. The shape must match the window's shape and the data type must be ti.f32. ```python window_shape = (720, 1080) window = ti.ui.Window("Test for copy depth data", window_shape) canvas = window.get_canvas() scene = ti.ui.Scene() camera = ti.ui.Camera() # Get the shape of the window w, h = window.get_window_shape() # The field/ndarray stores the depth information, and must be of the ti.f32 data type and have a 2d shape. # or, in other words, the shape must equal the window's shape scene_depth = ti.ndarray(ti.f32, shape = (w, h)) # scene_depth = ti.field(ti.f32, shape = (w, h)) while window.running: # render() canvas.scene(scene) window.get_depth_buffer(scene_depth) window.show() ``` -------------------------------- ### Create and Use a Sub-window in Taichi UI Source: https://docs.taichi-lang.org/api/taichi/ui Demonstrates how to create a sub-window using a context manager and add text within it. Ensure 'gui', 'name', 'x', 'y', 'width', and 'height' are properly defined before use. ```python with gui.sub_window(name, x, y, width, height) as g: g.text("Hello, World!") ``` -------------------------------- ### Initialize Taichi and Simulation Parameters Source: https://docs.taichi-lang.org/docs/cloth_simulation Initializes Taichi with the Vulkan backend and sets up simulation parameters like grid size, time step, gravity, and spring constants. This code defines the foundational elements for the cloth simulation. ```python import taichi as ti tiw.init(arch=ti.vulkan) # Alternatively, ti.init(arch=ti.cpu) n = 128 quad_size = 1.0 / n dt = 4e-2 / n substeps = int(1 / 60 // dt) gravity = ti.Vector([0, -9.8, 0]) spring_Y = 3e4 dashpot_damping = 1e4 drag_damping = 1 ball_radius = 0.3 ball_center = ti.Vector.field(3, dtype=float, shape=(1, )) ball_center[0] = [0, 0, 0] x = ti.Vector.field(3, dtype=float, shape=(n, n)) v = ti.Vector.field(3, dtype=float, shape=(n, n)) num_triangles = (n - 1) * (n - 1) * 2 indices = ti.field(int, shape=num_triangles * 3) vertices = ti.Vector.field(3, dtype=float, shape=n * n) colors = ti.Vector.field(3, dtype=float, shape=n * n) bending_springs = False ``` -------------------------------- ### ScalarNdarray.get_type Source: https://docs.taichi-lang.org/api/taichi Gets the data type of the ScalarNdarray. ```APIDOC ## get_type(_self_) ### Description Gets the data type of the ScalarNdarray. ### Returns The data type of the ScalarNdarray. ``` -------------------------------- ### Get Matrix Shape Source: https://docs.taichi-lang.org/api/taichi Retrieves the shape of the matrix. ```python get_shape(_self_) ``` -------------------------------- ### Create a GUI Window Source: https://docs.taichi-lang.org/docs/gui_system Creates a GUI window with a specified title and resolution. This is the first step to using the GUI system. ```python gui = ti.GUI('Hello World!', (640, 360)) ``` -------------------------------- ### ScalarField.parent Source: https://docs.taichi-lang.org/api/taichi Gets an ancestor of the representative SNode in the SNode tree. ```APIDOC ## parent(_self_ , _n =1_) ### Description Gets an ancestor of the representative SNode in the SNode tree. ### Parameters * **n** (_int_) – the number of levels going up from the representative SNode. ### Returns The n-th parent of the representative SNode. ### Return type SNode ``` -------------------------------- ### Build LLVM from Source on Linux/macOS Source: https://docs.taichi-lang.org/docs/dev_install Steps to download, configure, and build LLVM 15.0.0 from source. This is an alternative to using pre-built binaries. Ensure you have the necessary build tools installed. ```bash wget https://github.com/llvm/llvm-project/archive/refs/tags/llvmorg-15.0.5.tar.gz tar zxvf llvmorg-15.0.5.tar.gz cd llvm-project-llvmorg-15.0.5/llvm mkdir build cd build cmake .. -DLLVM_ENABLE_RTTI:BOOL=ON -DBUILD_SHARED_LIBS:BOOL=OFF -DCMAKE_BUILD_TYPE=Release -DLLVM_TARGETS_TO_BUILD="X86;NVPTX" -DLLVM_ENABLE_ASSERTIONS=ON -DLLVM_ENABLE_TERMINFO=OFF # If you are building on Apple M1, use -DLLVM_TARGETS_TO_BUILD="AArch64". # If you are building on NVIDIA Jetson TX2, use -DLLVM_TARGETS_TO_BUILD="ARM;NVPTX" # If you are building for a PyPI release, add -DLLVM_ENABLE_Z3_SOLVER=OFF to reduce the library dependency. make -j 8 sudo make install # Check your LLVM installation llvm-config --version # You should get 15.0.5 ``` -------------------------------- ### parent Source: https://docs.taichi-lang.org/api/taichi Gets an ancestor of the current SNode in the SNode tree. ```APIDOC ## parent(_self_ , _n =1_) ### Description Gets an ancestor of self in the SNode tree. ### Parameters * **n** (_int_) – the number of levels going up from self. ### Returns The n-th parent of self. ### Return type Union[None, _Root, SNode] ``` -------------------------------- ### Off-screen Rendering Setup Source: https://docs.taichi-lang.org/docs/ggui Enable off-screen rendering by setting `show_window=False` during window initialization. This allows saving frames without displaying the window. ```python window = ti.ui.Window('Window Title', (640, 360), show_window = False) ``` -------------------------------- ### MeshInstance.get_relation_size Source: https://docs.taichi-lang.org/api/taichi Gets the size of the relation for a given mesh element. ```APIDOC ## Method: MeshInstance.get_relation_size ### Parameters * **from_index** - The index of the starting element. * **to_element_type** - The type of the target element. ``` -------------------------------- ### MeshInstance.get_relation_access Source: https://docs.taichi-lang.org/api/taichi Gets the relation access for a given mesh element. ```APIDOC ## Method: MeshInstance.get_relation_access ### Parameters * **from_index** - The index of the starting element. * **to_element_type** - The type of the target element. * **neighbor_idx_ptr** - Pointer to the neighbor index. ``` -------------------------------- ### List Built Wheel Files Source: https://docs.taichi-lang.org/docs/dev_install Lists the generated wheel files in the dist directory after building. ```bash ls dist/*.whl ``` -------------------------------- ### Get Data Type Source: https://docs.taichi-lang.org/api/taichi Retrieves the data type of the elements in the ndarray. ```python get_type() ``` -------------------------------- ### taichi.init() Source: https://docs.taichi-lang.org/api/taichi Initializes the Taichi runtime and sets the backend for the program. It accepts various parameters to configure the runtime, including the architecture, default floating-point and integral types, and other compilation-related keyword arguments. ```APIDOC ## taichi.init(_arch =None_, _default_fp =None_, _default_ip =None_, __test_mode =False_, _enable_fallback =True_, _require_version =None_, _** kwargs_) ### Description Initializes the Taichi runtime. This should always be the entry point of your Taichi program. Most importantly, it sets the backend used throughout the program. ### Parameters: * **arch** – Backend to use. This is usually `cpu` or `gpu`. * **default_fp** (_Optional_ _[__type_ _]_) – Default floating-point type. * **default_ip** (_Optional_ _[__type_ _]_) – Default integral type. * **require_version** (_Optional_ _[__string_ _]_) – A version string. * ****kwargs** – Taichi provides highly customizable compilation through `kwargs`, which allows for fine grained control of Taichi compiler behavior. Below we list some of the most frequently used ones. For a complete list, please check out https://github.com/taichi-dev/taichi/blob/master/taichi/program/compile_config.h. * `cpu_max_num_threads` (int): Sets the number of threads used by the CPU thread pool. * `debug` (bool): Enables the debug mode, under which Taichi does a few more things like boundary checks. * `print_ir` (bool): Prints the CHI IR of the Taichi kernels. *`offline_cache` (bool): Enables offline cache of the compiled kernels. Default to True. When this is enabled Taichi will cache compiled kernel on your local disk to accelerate future calls. *`random_seed` (int): Sets the seed of the random generator. The default is 0. ``` -------------------------------- ### MeshInstance.get_position_as_numpy Source: https://docs.taichi-lang.org/api/taichi Gets the vertex position of the current mesh as a numpy array. ```APIDOC ## Method: MeshInstance.get_position_as_numpy ### Description Get the vertex position of current mesh to numpy array. ### Returns * **3d numpy array** - [x, y, z] with float-format. ``` -------------------------------- ### Example Output and Performance Source: https://docs.taichi-lang.org/docs/accelerate_python Shows a sample output of the LCS length calculation and its execution time. Highlights the significant performance improvement achieved with Taichi (around 0.9s) compared to a pure Python/NumPy approach (476s). ```text 2721 real 0m1.409s user 0m1.112s sys 0m0.549s ``` -------------------------------- ### Taichi Field Index Mapping Example Source: https://docs.taichi-lang.org/docs/internal Demonstrates the virtual-to-physical index mapping for dense and custom-laid-out fields in Taichi. Use this to verify memory layout assumptions. ```python a = ti.field(ti.f32, shape=(128, 32, 8)) b = ti.field(ti.f32) ti.root.dense(ti.j, 32).dense(ti.i, 16).place(b) ti.lang.impl.get_runtime().materialize() # This is an internal api for dev, we don't make sure it is stable for user. mapping_a = a.snode().physical_index_position() assert mapping_a == {0: 0, 1: 1, 2: 2} mapping_b = b.snode().physical_index_position() assert mapping_b == {0: 1, 1: 0} # Note that b is column-major: # the virtual first index exposed to the user comes second in memory layout. ``` -------------------------------- ### Set Taichi Logging Level Source: https://docs.taichi-lang.org/api/taichi Example of setting the Taichi logging level to 'debug'. ```python >>> set_logging_level('debug') ``` -------------------------------- ### Drawing 3D Lines and Particles Source: https://docs.taichi-lang.org/docs/ggui This snippet demonstrates initializing Taichi, setting up a window, scene, and camera, and then drawing 3D particles and lines. It includes camera controls and lighting setup. ```python import taichi as ti ti.init(arch=ti.cuda) N = 10 particles_pos = ti.Vector.field(3, dtype=ti.f32, shape = N) points_pos = ti.Vector.field(3, dtype=ti.f32, shape = N) @ti.kernel def init_points_pos(points : ti.template()): for i in range(points.shape[0]): points[i] = [i for j in ti.static(range(3))] init_points_pos(particles_pos) init_points_pos(points_pos) window = ti.ui.Window("Test for Drawing 3d-lines", (768, 768)) cavas = window.get_canvas() scene = ti.ui.Scene() camera = ti.ui.Camera() camera.position(5, 2, 2) while window.running: camera.track_user_inputs(window, movement_speed=0.03, hold_key=ti.ui.RMB) scene.set_camera(camera) scene.ambient_light((0.8, 0.8, 0.8)) scene.point_light(pos=(0.5, 1.5, 1.5), color=(1, 1, 1)) scene.particles(particles_pos, color = (0.68, 0.26, 0.19), radius = 0.1) # Draw 3d-lines in the scene scene.lines(points_pos, color = (0.28, 0.68, 0.99), width = 5.0) canvas.scene(scene) window.show() ``` -------------------------------- ### Vector Absolute Value Example Source: https://docs.taichi-lang.org/api/taichi Calculates the element-wise absolute value of a Taichi vector. ```python x = ti.Vector([-1.0, 0.0, 1.0]) y = ti.abs(x) print(y) ``` -------------------------------- ### Taichi Runtime Error Example Source: https://docs.taichi-lang.org/api/taichi Demonstrates TaichiRuntimeError, thrown when the compiled program cannot be executed. ```python raise ti.TaichiRuntimeError('Runtime error occurred!') ``` -------------------------------- ### Initialize Taichi Backend Source: https://docs.taichi-lang.org/docs/hello_world Initialize the Taichi environment, specifying the compute backend (e.g., GPU or CPU). ```python ti.init(arch=ti.gpu) ``` -------------------------------- ### Taichi Compilation Error Example Source: https://docs.taichi-lang.org/api/taichi Illustrates TaichiCompilationError, the base class for all compilation exceptions. ```python raise ti.TaichiCompilationError('Compilation failed!') ``` -------------------------------- ### Create a 3D Scene Source: https://docs.taichi-lang.org/docs/ggui Initializes an empty 3D scene object. This scene will be populated with geometries, lights, and a camera. ```python scene = ti.ui.Scene() ``` -------------------------------- ### Elif Clause Example Source: https://docs.taichi-lang.org/docs/language_reference Illustrates the use of elif clauses for multiple conditional branches. ```taichi if cond_a: body_a elif cond_b: body_b elif cond_c: body_c else: body_d ``` -------------------------------- ### Get Matrix Dimensions Source: https://docs.taichi-lang.org/api/taichi Retrieves the number of rows (n) and columns (m) of a Taichi Matrix. ```python M = ti.Matrix([[0, 1], [2, 3], [4, 5]], ti.i32) M.n # number of rows M.m # number of cols ``` -------------------------------- ### Example: Filling VectorNdarray from NumPy Source: https://docs.taichi-lang.org/api/taichi Demonstrates copying data from a NumPy array into a Taichi VectorNdarray. ```python >>> import numpy as np >>> a = ti.VectorNdarray(3, ti.f32, (2, 2), 0) >>> b = np.ones((2, 2, 3), dtype=np.float32) >>> a.from_numpy(b) ``` -------------------------------- ### Initialize Mass Points for Cloth Source: https://docs.taichi-lang.org/docs/cloth_simulation Sets up the initial positions and velocities for the mass points of a cloth simulation. Includes random offsets for variation. ```python import taichi as ti @ti.kernel def initialize_mass_points(): # A random offset to apply to each mass point random_offset = ti.Vector([ti.random() - 0.5, ti.random() - 0.5]) * 0.1 # Field x stores the mass points' positions for i, j in x: # The piece of cloth is 0.6 (y-axis) above the original point # # By taking away 0.5 from each mass point's [x,z] coordinate value # you move the cloth right above the original point x[i, j] = [ i * quad_size - 0.5 + random_offset[0], 0.6, j * quad_size - 0.5 + random_offset[1] ] # The initial velocity of each mass point is set to 0 v[i, j] = [0, 0, 0] ``` -------------------------------- ### Using KernelProfiler for Device Kernel Analysis Source: https://docs.taichi-lang.org/docs/profiler This example shows how to use KernelProfiler to analyze Taichi kernels. Enable it with kernel_profiler=True in ti.init(). Use print_kernel_profiler_info('trace') for detailed kernel launches or print_kernel_profiler_info() for default 'count' mode. Remember to call ti.sync() before profiling on GPU. Use clear_kernel_profiler_info() to reset records. ```python import taichi as ti ti.init(ti.cpu, kernel_profiler=True) x = ti.field(ti.f32, shape=1024*1024) @ti.kernel def fill(): for i in x: x[i] = i for i in range(8): fill() ti.profiler.print_kernel_profiler_info('trace') ti.profiler.clear_kernel_profiler_info() # Clears all records for i in range(100): fill() ti.profiler.print_kernel_profiler_info() # The default mode: 'count' ``` -------------------------------- ### Taichi Type Error Example Source: https://docs.taichi-lang.org/api/taichi Demonstrates TaichiTypeError, thrown when a type mismatch is found during compilation. ```python raise ti.TaichiTypeError('Type mismatch!') ``` -------------------------------- ### Download Taichi Wheel Package Source: https://docs.taichi-lang.org/docs/faq Use this command to download the Taichi wheel package and its dependencies for offline installation. Ensure the operating system matches the target server. ```bash pip download taichi ``` -------------------------------- ### Initialize Taichi with Default CPU Backend Source: https://docs.taichi-lang.org/docs/global_settings If no `arch` argument or `TI_ARCH` environment variable is set, Taichi defaults to the CPU backend. ```python ti.init() ``` -------------------------------- ### Taichi Syntax Error Example Source: https://docs.taichi-lang.org/api/taichi Shows TaichiSyntaxError, thrown when a syntax error is found during compilation. ```python raise ti.TaichiSyntaxError('Syntax error!') ``` -------------------------------- ### Taichi Name Error Example Source: https://docs.taichi-lang.org/api/taichi Shows TaichiNameError, which is thrown when an undefined name is found during compilation. ```python raise ti.TaichiNameError('Name not found!') ``` -------------------------------- ### Initialize Taichi with GPU Backend Source: https://docs.taichi-lang.org/docs/accelerate_python Initialize Taichi to use the GPU backend. This allows Taichi to offload computations to the GPU for potentially greater acceleration. ```python ti.init(arch=ti.gpu) ``` -------------------------------- ### Taichi Assertion Error Example Source: https://docs.taichi-lang.org/api/taichi Demonstrates the usage of TaichiAssertionError, which is thrown when an assertion fails at runtime. ```python raise ti.TaichiAssertionError('Assertion failed!') ``` -------------------------------- ### ndrange for loop example Source: https://docs.taichi-lang.org/docs/language_reference Iterates over multidimensional ranges. The loop variables are assigned integers for each dimension. ```python for i in ti.ndrange(10): # i is a scalar for j in ti.ndrange(10): # j is a scalar for k in ti.ndrange(10, 20): # k is a scalar for l, m in ti.ndrange(10, (10, 20)): # l is a scalar, m is a scalar pass ``` -------------------------------- ### Initialize Taichi Runtime and Load Module Source: https://docs.taichi-lang.org/docs/tutorial Create a Taichi runtime with a specified target architecture and load a compiled AOT module. ```cpp ti::Runtime runtime(TI_ARCH_VULKAN); ti::AotModule aot_module = runtime.load_aot_module("module.tcm"); ti::Kernel kernel_paint = aot_module.get_kernel("paint"); ```