From 80096e9e629fe44b11f8e4b3c9d59b70b5cf13cc Mon Sep 17 00:00:00 2001
From: James <james@rattlecan.games>
Date: Mon, 20 Jan 2025 22:09:56 +0000
Subject: [PATCH] Fix a crash bug in LightmapGI::_assign_lightmaps triggered
 after reparenting

After reparenting the LightmapGI node, the following `node` would be
initialized to null:

Node *node = get_node(light_data->get_user_path(i));

Which would then crash when de-referenced further down. This fix detects
which the node has been reparented and clears its users.
---
 scene/3d/lightmap_gi.cpp | 6 ++++++
 scene/3d/lightmap_gi.h   | 1 +
 2 files changed, 7 insertions(+)

diff --git a/scene/3d/lightmap_gi.cpp b/scene/3d/lightmap_gi.cpp
index 37380fd2b467..8f21260d573b 100644
--- a/scene/3d/lightmap_gi.cpp
+++ b/scene/3d/lightmap_gi.cpp
@@ -1491,11 +1491,17 @@ void LightmapGI::_notification(int p_what) {
 								"%s (%s): The directional lightmap textures are stored in a format that isn't supported anymore. Please bake lightmaps again to make lightmaps display from this node again.",
 								get_light_data()->get_path(), get_name()));
 
+				if (last_owner && last_owner != get_owner()) {
+					light_data->clear_users();
+				}
+
 				_assign_lightmaps();
 			}
 		} break;
 
 		case NOTIFICATION_EXIT_TREE: {
+			last_owner = get_owner();
+
 			if (light_data.is_valid()) {
 				_clear_lightmaps();
 			}
diff --git a/scene/3d/lightmap_gi.h b/scene/3d/lightmap_gi.h
index a48e599d6815..0848239fee0a 100644
--- a/scene/3d/lightmap_gi.h
+++ b/scene/3d/lightmap_gi.h
@@ -206,6 +206,7 @@ class LightmapGI : public VisualInstance3D {
 	Ref<CameraAttributes> camera_attributes;
 
 	Ref<LightmapGIData> light_data;
+	Node *last_owner = nullptr;
 
 	struct LightsFound {
 		Transform3D xform;