参数怎么才能传入到kernel里

import taichi as ti
ti.init(arch=ti.gpu,default_fp=ti.f64)
res_x=1024
res_y=1024
pixels=ti.Vector.field(3,ti.f64,shape=(res_x,res_y))
G=6.674*10**-11
M_sun=3
m_earth=1
color_sun = ti.Vector([255, 255, 0])
r_sun = 32
color_earth = ti.Vector([255, 255, 255])
r_earth = 10
pos_sun = ti.Vector([512, 512])
pos_earth = ti.Vector([100, 100])
v_sun = ti.Vector([0.0, 0.0])
a_sun = ti.Vector([0.0, 0.0])
v_earth = ti.Vector([100.0, 200.0])
a_earth = ti.Vector([0.0, 0.0])

@ti.func
def draw_global(pixels,color,pos,r,i,j):
    pos_now = ti.Vector([i, j])
    c=ti.random(ti.f64)
    if((pos_now-pos).norm()<r and c<0.995):
        pixels[i, j] =color
@ti.func
def render(pos_sun:ti.template(),pos_earth:ti.template()):
    for i, j in pixels:
        pixels[i,j]=ti.Vector([0,0,0])
        draw_global(pixels,color_sun,pos_sun,r_sun,i,j)
        draw_global(pixels,color_earth,pos_earth,r_earth,i,j)
@ti.kernel
def update(a_sun:ti.template(),a_earth:ti.template(),v_sun:ti.template(),v_earth:ti.template(),pos_sun:ti.template(),pos_earth:ti.template()):
    r = (pos_sun - pos_earth).norm()
    force = G * M_sun * m_earth / (r ** 2)
    x = pos_sun[0] - pos_earth[0]
    y = pos_sun[1] - pos_earth[1]
    forced_sun = ti.Vector([force * ti.sin(ti.atan2(x, y)), force * ti.cos(ti.atan2(x, y))])
    forced_earth = ti.Vector([force * ti.sin(ti.atan2(y, x)), force * ti.cos(ti.atan2(y, x))])
    a_sun = a_sun + forced_sun / M_sun
    a_earth = a_earth + forced_earth / m_earth
    v_sun = v_sun + a_sun
    v_earth = v_earth + a_earth
    pos_sun = ti.cast(pos_sun + v_sun, ti.i64)
    pos_earth = ti.cast(pos_earth + v_earth, ti.i64)
    render(pos_sun,pos_earth)
if __name__ == '__main__':
    print("starting")
    gui = ti.GUI("gui", res=(res_x, res_y))
    while gui.running:
        update(a_sun, a_earth, v_sun, v_earth, pos_sun, pos_earth)
        gui.set_image(pixels)
        gui.show()

error
On line 40 of file “C:\Users\PycharmProjects\pythonProject\taichi-test.py”, in update:
a_sun = a_sun + forced_sun / M_sun
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Variable ‘a_sun’ cannot be assigned. Maybe it is not a Taichi object?
a_sun明明已经定义为taichi类型了
想问问这参数要怎么才能传入到kernel里

Hi @money , 非常欢迎来到Taichi论坛。

Kernel函数具体可以接受什么样的参数类型,在文档里面有简要的介绍:Kernels and functions | Taichi Docs 。Taichi Kernel支持的所有参数类型,可以看API 这里

其次需要指出的是,Taichi中的Vector, Matrix只是数据的容器,你可以把他们当作C++中的std::vector 这样的容器来看待。也就是说,它上面并没有定义操作符比如+,-,*,/等操作,所以你在Kernel中不可以直接进行两个 ti.Vector相加的操作。

至于如何做比较方便,这里我给了一个例子,你可以参考:

import taichi as ti
ti.init()
vec2 = ti.math.vec2
a = vec2(1.0, 2.0)
b = vec3(1.0, 2.0, 3.0)
@ti.kernel
def test1(a: vec2) -> vec2:
    b =  ti.Vector([a.x+2.0,a.y+ 1.0])
    print(b)
    return b

@ti.kernel
def test2()->vec3:
    return vec3(1.0+b.x, 2.0+b.y, 3.0+b.z)

test1(a)
test2()

希望对你有所帮助,如果还有问题,欢迎你继续留言!