import { CHUNK_SIZE, MessageType } from "../../../shared/protocol/constants.js"; import { obscureSpeech, speechReadability } from "../../../shared/speech/proximity.js"; let nextMessageId = 1; export function broadcastSpeech (sessions, simulation, speakerSession, rawText) { const maxChars = Math.max(1, Math.round(simulation.settings.chatMaxCharacters || 100)); const text = String(rawText ?? "").trim().slice(0, maxChars); if (!text) { return; } const speakerPos = simulation.positionOf(speakerSession.entityId); if (!speakerPos) { return; } const messageId = nextMessageId++; const createdAt = Date.now(); for (const other of sessions.values()) { if (!other.entityId) { continue; } let readable = text; let readability = 1; if (other !== speakerSession) { const listenerPos = simulation.positionOf(other.entityId); if (!listenerPos) { continue; } const distance = Math.hypot(listenerPos.tileX - speakerPos.tileX, listenerPos.tileY - speakerPos.tileY); readability = speechReadability(distance, CHUNK_SIZE); if (readability <= 0) { continue; } readable = obscureSpeech(text, readability, messageId ^ other.id); if (!readable) { continue; } } if (other.socket.readyState === 1) { other.socket.send(JSON.stringify({ type: MessageType.chatBubble, messageId, entityId: speakerSession.entityId, characterId: speakerSession.characterId, text: readable, readability, createdAt })); } } } /** * Product icon above the crafter's head. Same proximity opacity as chat, * but no text and no letter obfuscation. */ export function broadcastItemBubble (sessions, simulation, speakerEntityId, itemId, quantity = 1) { const speakerPos = simulation.positionOf(speakerEntityId); if (!speakerPos || itemId == null) { return; } const messageId = nextMessageId++; const createdAt = Date.now(); for (const other of sessions.values()) { if (!other.entityId) { continue; } let readability = 1; if (other.entityId !== speakerEntityId) { const listenerPos = simulation.positionOf(other.entityId); if (!listenerPos) { continue; } const distance = Math.hypot(listenerPos.tileX - speakerPos.tileX, listenerPos.tileY - speakerPos.tileY); readability = speechReadability(distance, CHUNK_SIZE); if (readability <= 0) { continue; } } if (other.socket.readyState === 1) { other.socket.send(JSON.stringify({ type: MessageType.itemBubble, messageId, entityId: speakerEntityId, itemId, quantity: Math.max(1, quantity | 0 || 1), readability, createdAt })); } } }