From e92ae750012d37733ef803e882eb8191ad530e11 Mon Sep 17 00:00:00 2001
From: Star Rauchenberger <fefferburbia@gmail.com>
Date: Fri, 20 Sep 2024 21:29:42 -0400
Subject: Added proximity chat

---
 Archipelago/multiplayer.gd | 55 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 55 insertions(+)

(limited to 'Archipelago/multiplayer.gd')

diff --git a/Archipelago/multiplayer.gd b/Archipelago/multiplayer.gd
index 0bc2241..c2d9875 100644
--- a/Archipelago/multiplayer.gd
+++ b/Archipelago/multiplayer.gd
@@ -1,5 +1,8 @@
 extends "res://scripts/multiplayer.gd"
 
+var queued_messages = []
+var queued_messages_mutex = Mutex.new()
+
 
 func _request_lobby_list():
 	var apclient = global.get_node("Archipelago")
@@ -41,3 +44,55 @@ func _update_lobby_members():
 		if member_id != player_steam_id and member_id in active_lobby_members:
 			var slot_name = Steam.getLobbyMemberData(active_lobby_id, member_id, "slot_name")
 			active_lobby_members[member_id].steam_name = slot_name
+
+
+func say(text):
+	queued_messages_mutex.lock()
+	queued_messages.append(text)
+	queued_messages_mutex.unlock()
+
+
+func _physics_process(_delta):
+	if queued_messages_mutex.try_lock() == OK:
+		if queued_messages.empty():
+			queued_messages_mutex.unlock()
+		else:
+			var messages = queued_messages.duplicate()
+			queued_messages = []
+			queued_messages_mutex.unlock()
+
+			var player = get_tree().get_root().get_node("Spatial/player")
+			var space_state = get_tree().get_root().get_world().direct_space_state
+			var nearby_members = []
+			for member_id in active_lobby_members.keys():
+				var other_member = active_lobby_members[member_id]
+				var ray = space_state.intersect_ray(
+					player.global_translation, other_member.global_translation, [player], 0b0101
+				)
+				if !("collider" in ray) or ray["collider"] == other_member:
+					# Visible!
+					nearby_members.append(member_id)
+
+			var apclient = global.get_node("Archipelago")
+			var player_name = apclient.get_player_name()
+			for member_id in nearby_members:
+				for msg in messages:
+					_send_p2p_packet(
+						{"solves": [{"say": msg, "from": player_name}]},
+						member_id,
+						Steam.P2P_SEND_RELIABLE,
+						true
+					)
+
+
+# I'm completely hijacking this callback, since we're in ghost mode and it won't be called normally.
+func _receive_solve(data):
+	if "say" in data:
+		get_tree().get_root().get_node("Spatial/AP_TextClient").parse_printjson(
+			"[LOCAL] [color=#fafad2]%s[/color]: %s" % [data["from"], data["say"]]
+		)
+		messages.showMessage("[color=#fafad2]%s[/color]: %s" % [data["from"], data["say"]])
+
+
+func _send_hi(_discard):
+	pass
-- 
cgit 1.4.1