The correct way to modify global variable

I create a global point and want to update its value in GUI loop.

However, the following code does not work as expected. What is the correct way to do it?

import taichi as ti
ti.init(arch=ti.opengl)

vec3 = ti.types.vector(3, float)
point = vec3(0)
N = 500
P = ti.Vector.field(3, float, shape=(N, N))


@ti.kernel
def paint():
    for i, j in P:
        if (vec3(2 * i / N - 1, 2 * j / N - 1, 0) - point).norm() < 0.5: # NOT updated!
            P[i, j] = vec3(1)
        else:
            P[i, j] = vec3(0)


gui = ti.GUI('Test', (N, N), fast_gui=True)
while gui.running:
    paint()
    gui.set_image(P)
    gui.show()
    for e in gui.get_events(ti.GUI.PRESS):
        if e.key == ti.GUI.LEFT:
            point[0] -= 1
            print(point) # updated!
        if e.key == ti.GUI.RIGHT:
            point[0] += 1
            print(point) # updated!

Hi @johnao, you could pass point as the parameter of function paint.

import taichi as ti
ti.init(arch=ti.opengl)

vec3 = ti.types.vector(3, float)
point = vec3(0)
N = 500
P = ti.Vector.field(3, float, shape=(N, N))


@ti.kernel
def paint(point: vec3):
    for i, j in P:
        if (vec3(2 * i / N - 1, 2 * j / N - 1, 0) - point).norm() < 0.5: # NOT updated!
            P[i, j] = vec3(1)
        else:
            P[i, j] = vec3(0)


gui = ti.GUI('Test', (N, N), fast_gui=True)
while gui.running:
    paint(point)
    gui.set_image(P)
    gui.show()
    for e in gui.get_events(ti.GUI.PRESS):
        if e.key == ti.GUI.LEFT:
            point[0] -= 1
            print(point) # updated!
        if e.key == ti.GUI.RIGHT:
            point[0] += 1
            print(point) # updated!
1 个赞