Homework0: BarnsleyFern 巴恩斯利蕨

看到大家好多都在写分形,那我也写一个BarnsleyFern好了 :crazy_face:
BarnsleyFern
拿taichi写分形简直不要太爽!真的快…真的快…
版本:0.6.7
用新版的同学可以看下方的回复,貌似官方对gui.set_image()做了些改动,导致老版本代码跑不起来

import taichi as ti
import math

ti.init(arch=ti.gpu)

width = 660
height = 1000
pixels = ti.var(dt=ti.f32, shape=(width, height, 3))


@ti.func
def generatePoint(x, y, t):
    r = ti.random()
    nextX = 0.0
    nextY = 0.0

    if(r < 0.01):
        nextX = 0
        nextY = 0.16*y
    elif(r < 0.85):
        nextX = 0.85*x + (0.04 + t)*y
        nextY = -(0.04 + t)*x + 0.85*y + 1.6
    elif(r < 0.93):
        nextX =  0.20*x + -0.26*y
        nextY = 0.23*x + 0.22*y + 1.0
    else:
        nextX =  -0.15*x + 0.28*y
        nextY = 0.26*x + 0.24*y + 0.44
    return nextX, nextY

@ti.kernel
def drawPoint(t: ti.f32):
    for i in range(0, 100000):
        x = 0.0
        y = 0.0
        for j in range(0, 40):
            x, y = generatePoint(x, y, t)
            pixels[(int)((x/6+0.5)*width), (int)(y*height/10.5), 0] += 0.01
            pixels[(int)((x/6+0.5)*width), (int)(y*height/10.5), 1] += 0.02
            pixels[(int)((x/6+0.5)*width), (int)(y*height/10.5), 2] += 0.005


gui = ti.GUI("BarnsleyFern", (width, height))

timer = 0.0

while(True):
    timer += 0.08
    drawPoint(math.sin(timer)*0.03)
    gui.set_image(pixels)
    gui.show()
    pixels.fill(0)
4 个赞

你好,我这里的版本是0.6.9
但是报“Image resolution does not match GUI resolution.”的错

我没找出问题在哪,tensor和gui的长宽应该都是w和h吧。
望解答,谢谢

哎?奇怪,我用的是0.6.7,没有这个问题。我换个版本试试看怎么回事

把pixels的定义方式做了修改,从Tensor改成了Vector
开发组把gui.set_image()做了不小的改动,传入数组的shape必须和ti.GUI里定义的一样
但是文档还没更新… :thinking:

import taichi as ti
import math

ti.init(arch=ti.gpu)

width = 660
height = 1000
pixels = ti.Vector(3, dt=ti.f32, shape=(width, height))


@ti.func
def generatePoint(x, y, t):
    r = ti.random()
    nextX = 0.0
    nextY = 0.0

    if(r < 0.01):
        nextX = 0
        nextY = 0.16*y
    elif(r < 0.85):
        nextX = 0.85*x + (0.04 + t)*y
        nextY = -(0.04 + t)*x + 0.85*y + 1.6
    elif(r < 0.93):
        nextX =  0.20*x + -0.26*y
        nextY = 0.23*x + 0.22*y + 1.0
    else:
        nextX =  -0.15*x + 0.28*y
        nextY = 0.26*x + 0.24*y + 0.44
    return nextX, nextY

@ti.kernel
def drawPoint(t: ti.f32):
    for i in range(0, 100000):
        x = 0.0
        y = 0.0
        for j in range(0, 40):
            x, y = generatePoint(x, y, t)
            pixels[(int)((x/6+0.5)*width), (int)(y*height/10.5)][0] += 0.01
            pixels[(int)((x/6+0.5)*width), (int)(y*height/10.5)][1] += 0.02
            pixels[(int)((x/6+0.5)*width), (int)(y*height/10.5)][2] += 0.005


gui = ti.GUI("BarnsleyFern", (width, height))


timer = 0.0

while(True):
    timer += 0.08
    drawPoint(math.sin(timer)*0.03)
    gui.set_image(pixels)
    gui.show()
    pixels.fill(0)

效果很棒呀!!

1 个赞

如何能更新到新版本taichi了0.6.10,我的也是0.6.7

pip install --upgrade Taichi

2 个赞

非常感谢

1 个赞

目前可以通过gui.set_image(pixels.to_numpy())暂时解决问题。