I’ve found some logic scene.render() with camera.getViewMatrix somehow calls Observable.notifyObservers multiple times in a single frame.
I’ve already changed every camera.getViewMatrix() in my domain to camera._worldMatrix to prevent infinite onViewMatrixChangedObservable.notiftyObservers.
Why does the engine call onViewMatrixChangedObservable.notiftyObservers inside getViewMatrix?
Why does the engine update the camera before this.onBeforeRenderObservable.notifyObservers(this); and run _processSubCameras after.
What is the best refactoring for me to fix this problem?
onViewMatrixChangedObservable should be notified only when the view matrix changes, or when true is passed to getViewMatrix (force parameter). The first three lines of this function are:
if (!force && this._isSynchronizedViewMatrix()) {
return this._computedViewMatrix;
}
<onViewMatrixChangedObservable is notified in later code>
If you can setup a repro, we can have a look at why you get too many notifications.
Regarding 2/, scene.render first update all cameras of the scene, then loop over the cameras and call _processSubCameras
I think changing camera matrix in beforeRender causes another onViewMatrixChangedObservable notification.
The naming or method getWorldMatrix is misleading and has sideffects.
I’ve refactored my code to
flag whenever onViewMatrixChangedObservable is notified
move original observers to beforeRender and run only if the flag is true
and release the flag after each frame
How about we do the similar in the engine?
Do notification in scene render or some places that insures frame cycle.
It might be a breaking change, but I plead it clears things out.
As explained, with the existing code, the view matrix should only be recalculated when necessary. It would be great if you could setup a repro of your bug so that we can fix it on our side!
I would say on the one hand this is expected behaviour. You are calling the function that triggers the callback from within the callback. But on the other hand, would be nice if Babylon caught the recursion.