BlueGit

timfa questward

Files

questward / server / src / chat / speech.js

speech.js

speech.js 1.4 KiB Download Raw
1import { CHUNK_SIZE, MessageType } from "../../../shared/protocol/constants.js";
2import { obscureSpeech, speechReadability } from "../../../shared/speech/proximity.js";
3
4let nextMessageId = 1;
5
6export function broadcastSpeech (sessions, simulation, speakerSession, rawText)
7{
8 const maxChars = Math.max(1, Math.round(simulation.settings.chatMaxCharacters || 100));
9 const text = String(rawText ?? "").trim().slice(0, maxChars);
10 if (!text)
11 { return; }
12
13 const speakerPos = simulation.positionOf(speakerSession.entityId);
14 if (!speakerPos)
15 { return; }
16
17 const messageId = nextMessageId++;
18 const createdAt = Date.now();
19 for (const other of sessions.values())
20 {
21 if (!other.entityId)
22 { continue; }
23 let readable = text;
24 let readability = 1;
25 if (other !== speakerSession)
26 {
27 const listenerPos = simulation.positionOf(other.entityId);
28 if (!listenerPos)
29 { continue; }
30 const distance = Math.hypot(listenerPos.tileX - speakerPos.tileX, listenerPos.tileY - speakerPos.tileY);
31 readability = speechReadability(distance, CHUNK_SIZE);
32 if (readability <= 0)
33 { continue; }
34 readable = obscureSpeech(text, readability, messageId ^ other.id);
35 if (!readable)
36 { continue; }
37 }
38 if (other.socket.readyState === 1)
39 {
40 other.socket.send(JSON.stringify({
41 type: MessageType.chatBubble,
42 messageId,
43 entityId: speakerSession.entityId,
44 characterId: speakerSession.characterId,
45 text: readable,
46 readability,
47 createdAt
48 }));
49 }
50 }
51}