Python makes Rendered Viewport Shading wierd

Hi all, I just started working with python in blender. I created a simple scipt:

import bpy
import math

scene = bpy.context.scene
cube = scene.objects['Cube']

def recalculate_cube(scene):
    
    cube.location.z = ( abs(math.sin(cube.location.x*math.pi/2))+
        abs(math.sin(cube.location.y*math.pi/2)) )

bpy.app.handlers.scene_update_pre.clear()
bpy.app.handlers.scene_update_pre.append(recalculate_cube)

It simply modifies the cubes z, based off if it’s x and y.

I can render it fine and everything, but I can not view it properly when I hit shift-Z(Rendered Viewport Shading).

In blender render, it just shows a transparent background, and in cycles it makes everything ridiculously noisy, and unstable, but when I render with F12 it works just fine.

Is it a bug, or is my script bad?

I attached the blend file.

Thanks in advance.

Okay, so I figured out a way around it. The problem is that my function forces an update which makes itself get called again forcing cycles to re-render… and the cycle keeps going. The solution then is to check whether the position changed since the last call to the function. If not, do nothing; problem solved!

import bpy
import math

scene = bpy.context.scene
cube = scene.objects['Cube']

last_pos = cube.location.copy()

def recalculate_cube(scene):
    global last_pos
    
    if last_pos != cube.location:
        cube.location.z = ( abs(math.sin(cube.location.x*math.pi/2))+
            abs(math.sin(cube.location.y*math.pi/2)) )
        last_pos = cube.location.copy()
    

bpy.app.handlers.scene_update_pre.clear()
bpy.app.handlers.scene_update_pre.append(recalculate_cube)

Attachments

TEST.blend (486 KB)