Android game update scenegraph from anotherr thread

So My android game went for testing and in some devices its throwing illegalstate exception scenegraph is not properly updated.
The reason is mostly usage of multiple coroutines(kotlin coroutines) and accidentally making scenegraph change in non render thread somewhere. So I am planning to make some changes in my code. But prior to that I need to ask if using one of physics method like warp, setviewdirection, setwalkdirection etc in non render thread shall be fine ? Or do I need to handle that too in update loop, my belief is physics thread will take care of synchronization.Am I correct ? Or should I make physics changes too in updat loop aka render thread?

Physics is not thread safe either.

Any more detailed answer depends on how you have physics setup… but in general, you should be safe updating physics using the same technique as updating the scene graph: app.enqueue()

1 Like

It depends, if that physics code updates the scene graph, then they are not thread-safe, but if they are just attributes changing that would be rendered normally on the next update phase, however, generally, it is far better to be on the safe side and update all JME code within a state or a control.

1 Like

Myth #1: it’s safe to read values from two different threads, I don’t need to synchronize them.

Myth #2: it’s safe to update a value from two different threads as long as I’m “pretty sure” I’m not doing it at the same time.

For various reasons, those are not ok. Unless you want random weird behavior to crop up that’s difficult to track down.

I could go more into the “why” but it’s sometimes complicated. Suffice it to say, if you want to mess with values from different threads then you need to take proper care.

1 Like

I would rather be on safe side. My code does warp characters in and out of camera view and I am not sure if that would affect rendering.
Currently I mostly updating my calculations in different thread/coroutine that will only update by state variable while in update loop/control update I will poll for changes in those state variables for actually making any transforms. I might have though not been careful with physics updates especially warp and setting walk directions.
Thanks for quick response :slightly_smiling_face:

Polling for changes blocks the thread and it is not a good design (especially if done on Ui-thread) in general, it is better to enqueue changes and use callbacks.

Thread blocks utilize the CPU actively without doing something useful, if your application is going to be huge and use a lot of resources, it is better to consider this.