A better XR start script

In Setting up XR we introduced a startup script that initialises our setup which we used as our script on our main node. This script performs the minimum steps required for any given interface.

When using OpenXR there are a number of improvements we should do here. For this we’ve created a more elaborate starting script. You will find these used in our demo projects.

Alternatively, if you are using XR Tools (see Introducing XR tools) it contains a version of this script updated with some features related to XR tools.

Below we will detail out the script used in our demos and explain the parts that are added.

Signals for our script

We are introducing 3 signals to our script so that our game can add further logic:

  • focus_lost is emitted when the player takes off their headset or when the player enters the menu system of the headset.

  • focus_gained is emitted when the player puts their headset back on or exits the menu system and returns to the game.

  • pose_recentered is emitted when the headset requests the players position to be reset.

Our game should react accordingly to these signals.

GDScriptC#

  1. extends Node3D
  2. signal focus_lost
  3. signal focus_gained
  4. signal pose_recentered
  5. ...
  1. using Godot;
  2. public partial class MyNode3D : Node3D
  3. {
  4. [Signal]
  5. public delegate void FocusLostEventHandler();
  6. [Signal]
  7. public delegate void FocusGainedEventHandler();
  8. [Signal]
  9. public delegate void PoseRecenteredEventHandler();
  10. ...

Variables for our script

We introduce a few new variables to our script as well:

  • maximum_refresh_rate will control the headsets refresh rate if this is supported by the headset.

  • xr_interface holds a reference to our XR interface, this already existed but we now type it to get full access to our XRInterface API.

  • xr_is_focussed will be set to true whenever our game has focus.

GDScriptC#

  1. ...
  2. @export var maximum_refresh_rate : int = 90
  3. var xr_interface : OpenXRInterface
  4. var xr_is_focussed = false
  5. ...
  1. ...
  2. [Export]
  3. public int MaximumRefreshRate { get; set; } = 90;
  4. private OpenXRInterface _xrInterface;
  5. private bool _xrIsFocused;
  6. ...

Our updated ready function

We add a few things to the ready function.

If we’re using the mobile or forward+ renderer we set the viewports vrs_mode to VRS_XR. On platforms that support this, this will enable foveated rendering.

If we’re using the compatibility renderer, we check if the OpenXR foveated rendering settings are configured and if not, we output a warning. See OpenXR Settings for further details.

We hook up a number of signals that will be emitted by the XRInterface. We’ll provide more detail about these signals as we implement them.

We also quit our application if we couldn’t successfully initialise OpenXR. Now this can be a choice. If you are making a mixed mode game you setup the VR mode of your game on success, and setup the non-VR mode of your game on failure. However, when running a VR only application on a standalone headset, it is nicer to exit on failure than to hang the system.

GDScriptC#

  1. ...
  2. # Called when the node enters the scene tree for the first time.
  3. func _ready():
  4. xr_interface = XRServer.find_interface("OpenXR")
  5. if xr_interface and xr_interface.is_initialized():
  6. print("OpenXR instantiated successfully.")
  7. var vp : Viewport = get_viewport()
  8. # Enable XR on our viewport
  9. vp.use_xr = true
  10. # Make sure v-sync is off, v-sync is handled by OpenXR
  11. DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_DISABLED)
  12. # Enable VRS
  13. if RenderingServer.get_rendering_device():
  14. vp.vrs_mode = Viewport.VRS_XR
  15. elif int(ProjectSettings.get_setting("xr/openxr/foveation_level")) == 0:
  16. push_warning("OpenXR: Recommend setting Foveation level to High in Project Settings")
  17. # Connect the OpenXR events
  18. xr_interface.session_begun.connect(_on_openxr_session_begun)
  19. xr_interface.session_visible.connect(_on_openxr_visible_state)
  20. xr_interface.session_focussed.connect(_on_openxr_focused_state)
  21. xr_interface.session_stopping.connect(_on_openxr_stopping)
  22. xr_interface.pose_recentered.connect(_on_openxr_pose_recentered)
  23. else:
  24. # We couldn't start OpenXR.
  25. print("OpenXR not instantiated!")
  26. get_tree().quit()
  27. ...
  1. ...
  2. /// <summary>
  3. /// Called when the node enters the scene tree for the first time.
  4. /// </summary>
  5. public override void _Ready()
  6. {
  7. _xrInterface = (OpenXRInterface)XRServer.FindInterface("OpenXR");
  8. if (_xrInterface != null && _xrInterface.IsInitialized())
  9. {
  10. GD.Print("OpenXR instantiated successfully.");
  11. var vp = GetViewport();
  12. // Enable XR on our viewport
  13. vp.UseXR = true;
  14. // Make sure v-sync is off, v-sync is handled by OpenXR
  15. DisplayServer.WindowSetVsyncMode(DisplayServer.VSyncMode.Disabled);
  16. // Enable VRS
  17. if (RenderingServer.GetRenderingDevice() != null)
  18. vp.VrsMode = Viewport.VrsModeEnum.XR;
  19. else if ((int)ProjectSettings.GetSetting("xr/openxr/foveation_level") == 0)
  20. GD.PushWarning("OpenXR: Recommend setting Foveation level to High in Project Settings");
  21. // Connect the OpenXR events
  22. _xrInterface.SessionBegun += OnOpenXRSessionBegun;
  23. _xrInterface.SessionVisible += OnOpenXRVisibleState;
  24. _xrInterface.SessionFocussed += OnOpenXRFocusedState;
  25. _xrInterface.SessionStopping += OnOpenXRStopping;
  26. _xrInterface.PoseRecentered += OnOpenXRPoseRecentered;
  27. }
  28. else
  29. {
  30. // We couldn't start OpenXR.
  31. GD.Print("OpenXR not instantiated!");
  32. GetTree().Quit();
  33. }
  34. }
  35. ...

On session begun

This signal is emitted by OpenXR when our session is setup. This means the headset has run through setting everything up and is ready to begin receiving content from us. Only at this time various information is properly available.

The main thing we do here is to check our headsets refresh rate. We also check the available refresh rates reported by the XR runtime to determine if we want to set our headset to a higher refresh rate.

Finally we match our physics update rate to our headset update rate. Godot runs at a physics update rate of 60 updates per second by default while headsets run at a minimum of 72, and for modern headsets often up to 144 frames per second. Not matching the physics update rate will cause stuttering as frames are rendered without objects moving.

GDScriptC#

  1. ...
  2. # Handle OpenXR session ready
  3. func _on_openxr_session_begun() -> void:
  4. # Get the reported refresh rate
  5. var current_refresh_rate = xr_interface.get_display_refresh_rate()
  6. if current_refresh_rate > 0:
  7. print("OpenXR: Refresh rate reported as ", str(current_refresh_rate))
  8. else:
  9. print("OpenXR: No refresh rate given by XR runtime")
  10. # See if we have a better refresh rate available
  11. var new_rate = current_refresh_rate
  12. var available_rates : Array = xr_interface.get_available_display_refresh_rates()
  13. if available_rates.size() == 0:
  14. print("OpenXR: Target does not support refresh rate extension")
  15. elif available_rates.size() == 1:
  16. # Only one available, so use it
  17. new_rate = available_rates[0]
  18. else:
  19. for rate in available_rates:
  20. if rate > new_rate and rate <= maximum_refresh_rate:
  21. new_rate = rate
  22. # Did we find a better rate?
  23. if current_refresh_rate != new_rate:
  24. print("OpenXR: Setting refresh rate to ", str(new_rate))
  25. xr_interface.set_display_refresh_rate(new_rate)
  26. current_refresh_rate = new_rate
  27. # Now match our physics rate
  28. Engine.physics_ticks_per_second = current_refresh_rate
  29. ...
  1. ...
  2. /// <summary>
  3. /// Handle OpenXR session ready
  4. /// </summary>
  5. private void OnOpenXRSessionBegun()
  6. {
  7. // Get the reported refresh rate
  8. var currentRefreshRate = _xrInterface.DisplayRefreshRate;
  9. GD.Print(currentRefreshRate > 0.0F
  10. ? $"OpenXR: Refresh rate reported as {currentRefreshRate}"
  11. : "OpenXR: No refresh rate given by XR runtime");
  12. // See if we have a better refresh rate available
  13. var newRate = currentRefreshRate;
  14. var availableRates = _xrInterface.GetAvailableDisplayRefreshRates();
  15. if (availableRates.Count == 0)
  16. {
  17. GD.Print("OpenXR: Target does not support refresh rate extension");
  18. }
  19. else if (availableRates.Count == 1)
  20. {
  21. // Only one available, so use it
  22. newRate = (float)availableRates[0];
  23. }
  24. else
  25. {
  26. GD.Print("OpenXR: Available refresh rates: ", availableRates);
  27. foreach (float rate in availableRates)
  28. if (rate > newRate && rate <= MaximumRefreshRate)
  29. newRate = rate;
  30. }
  31. // Did we find a better rate?
  32. if (currentRefreshRate != newRate)
  33. {
  34. GD.Print($"OpenXR: Setting refresh rate to {newRate}");
  35. _xrInterface.DisplayRefreshRate = newRate;
  36. currentRefreshRate = newRate;
  37. }
  38. // Now match our physics rate
  39. Engine.PhysicsTicksPerSecond = (int)currentRefreshRate;
  40. }
  41. ...

On visible state

This signal is emitted by OpenXR when our game becomes visible but is not focussed. This is a bit of a weird description in OpenXR but it basically means that our game has just started and we’re about to switch to the focussed state next, that the user has opened a system menu or the users has just took their headset off.

On receiving this signal we’ll update our focussed state, we’ll change the process mode of our node to disabled which will pause processing on this node and it’s children, and emit our focus_lost signal.

If you’ve added this script to your root node, this means your game will automatically pause when required. If you haven’t, you can connect a method to the signal that performs additional changes.

Note

While your game is in visible state because the user has opened a system menu, Godot will keep rendering frames and head tracking will remain active so your game will remain visible in the background. However controller and hand tracking will be disabled until the user exits the system menu.

GDScriptC#

  1. ...
  2. # Handle OpenXR visible state
  3. func _on_openxr_visible_state() -> void:
  4. # We always pass this state at startup,
  5. # but the second time we get this it means our player took off their headset
  6. if xr_is_focussed:
  7. print("OpenXR lost focus")
  8. xr_is_focussed = false
  9. # pause our game
  10. get_tree().paused = true
  11. emit_signal("focus_lost")
  12. ...
  1. ...
  2. /// <summary>
  3. /// Handle OpenXR visible state
  4. /// </summary>
  5. private void OnOpenXRVisibleState()
  6. {
  7. // We always pass this state at startup,
  8. // but the second time we get this it means our player took off their headset
  9. if (_xrIsFocused)
  10. {
  11. GD.Print("OpenXR lost focus");
  12. _xrIsFocused = false;
  13. // Pause our game
  14. GetTree().Paused = true;
  15. EmitSignal(SignalName.FocusLost);
  16. }
  17. }
  18. ...

On focussed state

This signal is emitted by OpenXR when our game gets focus. This is done at the completion of our startup, but it can also be emitted when the user exits a system menu, or put their headset back on.

Note also that when your game starts while the user is not wearing their headset, the game stays in ‘visible’ state until the user puts their headset on.

Warning

It is thus important to keep your game paused while in visible mode. If you don’t the game will keep on running while your user isn’t interacting with your game. Also when the game returns to focussed mode, suddenly all controller and hand tracking is re-enabled and could have game breaking consequences if you do not react to this accordingly. Be sure to test this behaviour in your game!

While handling our signal we will update the focusses state, unpause our node and emit our focus_gained signal.

GDScriptC#

  1. ...
  2. # Handle OpenXR focused state
  3. func _on_openxr_focused_state() -> void:
  4. print("OpenXR gained focus")
  5. xr_is_focussed = true
  6. # unpause our game
  7. get_tree().paused = false
  8. emit_signal("focus_gained")
  9. ...
  1. ...
  2. /// <summary>
  3. /// Handle OpenXR focused state
  4. /// </summary>
  5. private void OnOpenXRFocusedState()
  6. {
  7. GD.Print("OpenXR gained focus");
  8. _xrIsFocused = true;
  9. // Un-pause our game
  10. GetTree().Paused = false;
  11. EmitSignal(SignalName.FocusGained);
  12. }
  13. ...

On stopping state

This signal is emitted by OpenXR when we enter our stop state. There are some differences between platforms when this happens. On some platforms this is only emitted when the game is being closed. But on other platforms this will also be emitted every time the player takes off their headset.

For now this method is only a place holder.

GDScriptC#

  1. ...
  2. # Handle OpenXR stopping state
  3. func _on_openxr_stopping() -> void:
  4. # Our session is being stopped.
  5. print("OpenXR is stopping")
  6. ...
  1. ...
  2. /// <summary>
  3. /// Handle OpenXR stopping state
  4. /// </summary>
  5. private void OnOpenXRStopping()
  6. {
  7. // Our session is being stopped.
  8. GD.Print("OpenXR is stopping");
  9. }
  10. ...

On pose recentered

This signal is emitted by OpenXR when the user requests their view to be recentered. Basically this communicates to your game that the user is now facing forward and you should re-orient the player so they are facing forward in the virtual world.

As doing so is dependent on your game, your game needs to react accordingly.

All we do here is emit the pose_recentered signal. You can connect to this signal and implement the actual recenter code. Often it is enough to call center_on_hmd().

GDScriptC#

  1. ...
  2. # Handle OpenXR pose recentered signal
  3. func _on_openxr_pose_recentered() -> void:
  4. # User recentered view, we have to react to this by recentering the view.
  5. # This is game implementation dependent.
  6. emit_signal("pose_recentered")
  1. ...
  2. /// <summary>
  3. /// Handle OpenXR pose recentered signal
  4. /// </summary>
  5. private void OnOpenXRPoseRecentered()
  6. {
  7. // User recentered view, we have to react to this by recentering the view.
  8. // This is game implementation dependent.
  9. EmitSignal(SignalName.PoseRecentered);
  10. }
  11. }

And that finished our script. It was written so that it can be re-used over multiple projects. Just add it as the script on your main node (and extend it if needed) or add it on a child node specific for this script.


User-contributed notes

Please read the User-contributed notes policy before submitting a comment.

Previous Next