using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Threading;
namespace AcDream.Core.Chat;
///
/// Unified chat log — mirrors every chat-bearing message the server
/// sends (local HearSpeech, broadcast ChannelBroadcast, whispered
/// Tell, system TransientMessage, PopupString).
///
///
/// Sits behind the UI chat panel (Phase D.2) and the scripting
/// plugin API so plugins can react to chat (e.g. auto-reply, loot
/// logging).
///
///
///
/// Retail keeps ~200 lines of scrollback. Our ring buffer defaults to
/// 500 and is configurable.
///
///
public sealed class ChatLog
{
private readonly ConcurrentQueue _buffer = new();
private readonly int _maxEntries;
private uint _localPlayerGuid;
private long _revision;
// Phase J follow-up: ACE often sends the same system text via two
// wire paths (GameMessageSystemChat 0xF7E0 + GameEventCommunication-
// TransientString 0x02EB) for back-compat — we wired both to
// OnSystemMessage in I.5/J, so the user saw lines like "Unknown
// command: help" twice. Dedupe within a short window: track the
// last system text + arrival time; if a second identical text
// shows up within one second, skip.
private string _lastSystemText = "";
private DateTime _lastSystemAt = DateTime.MinValue;
private static readonly TimeSpan SystemDedupWindow = TimeSpan.FromSeconds(1);
public ChatLog(int maxEntries = 500)
{
if (maxEntries < 1) throw new ArgumentOutOfRangeException(nameof(maxEntries));
_maxEntries = maxEntries;
}
/// Fires every time a new entry is appended.
public event Action? EntryAppended;
/// Snapshot of all current entries, oldest first.
public ChatEntry[] Snapshot() => _buffer.ToArray();
public int Count => _buffer.Count;
///
/// Monotonic content revision. It advances after every successful append and
/// every explicit clear, allowing retained UI consumers to cache formatted
/// transcript layout without snapshotting the concurrent queue every frame.
///
public long Revision => Interlocked.Read(ref _revision);
///
/// Push the authoritative local-player GUID from WorldSession.
/// The host sets it after character selection and resets it at session
/// teardown. Used by to
/// recognize ACE's HearSpeech echo of our own /say (server's
/// HandleActionTalk broadcasts to all in range INCLUDING the
/// sender) and re-render it as "You say, ...".
///
public void SetLocalPlayerGuid(uint guid) => _localPlayerGuid = guid;
///
/// Reset per-session speaker classification and duplicate suppression
/// while preserving the visible transcript. Retail has an explicit
/// ChatInterface::RecvNotice_ClearChatBuffer @ 0x004F2F60 path;
/// character-session teardown does not use that clear-buffer notice.
///
public void ResetSessionIdentity()
{
_localPlayerGuid = 0u;
_lastSystemText = string.Empty;
_lastSystemAt = DateTime.MinValue;
}
// ── Inbound adapters ─────────────────────────────────────────────────────
/// Local or ranged HearSpeech (0x02BB / 0x02BC).
///
/// Phase I.5: an empty is substituted with
/// "You" — the server uses this convention to indicate that the
/// player is the speaker (e.g. their own ranged shouts echo back).
/// Port from holtburger
/// references/holtburger/.../client/messages.rs lines 476-487.
///
///
/// The wire chatType carried by HearSpeech/HearRangedSpeech
/// (speech.ChatType) — passed through VERBATIM, with zero
/// remapping, matching retail's Handle_Communication__HearSpeech
/// @0x005712A0 (the raw arg5 feeds AddTextToScroll
/// directly). Defaults to 0x02 (Speech) for callers that
/// don't have a wire value in hand.
///
public void OnLocalSpeech(string sender, string text, uint senderGuid, bool isRanged, uint logTextType = 0x02u)
{
// Phase J: ACE's HandleActionTalk broadcasts a HearSpeech echo
// back to the sender too. Detect own echo by guid match and
// substitute "" so the formatter renders "You say, ..." (single
// first-person echo) instead of "+Acdream says, ..."
// (third-person duplicate of our optimistic, already dropped).
bool isOwnEcho = _localPlayerGuid != 0 && senderGuid == _localPlayerGuid;
string effectiveSender = (isOwnEcho || string.IsNullOrEmpty(sender)) ? "You" : sender;
Append(new ChatEntry(
Kind: isRanged ? ChatKind.RangedSpeech : ChatKind.LocalSpeech,
Sender: effectiveSender,
Text: text,
SenderGuid: senderGuid,
ChannelId: 0)
{
LogTextType = logTextType,
});
}
/// EmoteText (0x01E0) — server-driven third-person emote.
public void OnEmote(string senderName, string text, uint senderGuid)
{
Append(new ChatEntry(
Kind: ChatKind.Emote,
Sender: senderName,
Text: text,
SenderGuid: senderGuid,
ChannelId: 0)
{
// Retail hard-codes Emote (0x0C) for every HearEmote line —
// ClientCommunicationSystem::HearEmote @0x0057CBE0, the
// literal constant at 0x0057CF94. Not a wire value.
LogTextType = 0x0Cu,
});
}
/// SoulEmote (0x01E2) — complex emote (chat + paired animation).
public void OnSoulEmote(string senderName, string text, uint senderGuid)
{
Append(new ChatEntry(
Kind: ChatKind.SoulEmote,
Sender: senderName,
Text: text,
SenderGuid: senderGuid,
ChannelId: 0)
{
// HearSoulEmote tail-calls HearEmote @0x0057D096 — same
// hard-coded 0x0C.
LogTextType = 0x0Cu,
});
}
/// PlayerKilled (0x019E) — death announcement.
///
/// Death messages are routed as so they
/// share styling with other server announcements. The
/// SenderGuid field carries the victim guid; the
/// ChannelId field carries the killer guid (a small misuse
/// of the field but avoids a schema change).
///
public void OnPlayerKilled(string deathMessage, uint victimGuid, uint killerGuid)
{
Append(new ChatEntry(
Kind: ChatKind.System,
Sender: "",
Text: deathMessage,
SenderGuid: victimGuid,
ChannelId: killerGuid)
{
// Inferred by analogy from the sibling GameEvents this opcode
// shares a dispatch pattern with: VictimNotification (0x01AC)
// and KillerNotification (0x01AD) both route through the SAME
// retail handler, ClientCombatSystem::HandleKillerNotification
// Event @0x0056C410 (cases 0xa/0xb of the combat-envelope
// switch, pc:359548-359559), which calls
// AddTextToScroll(..., 0, 1, 0) — type 0x00 Default. No direct
// decomp citation was traced for 0x019E PlayerKilled itself.
LogTextType = 0x00u,
});
}
/// WeenieError (0x028A) / WeenieErrorWithString (0x028B).
///
/// Phase I.5: previously-orphaned parser. The server fires this when a
/// game-logic action fails (e.g. "you don't have enough mana", "you
/// can't pick that up"). Routed as ; the
/// ChannelId field carries the WeenieError code so plugins can
/// filter or react. is the interpolated
/// substring (null for plain WeenieError, set for WeenieErrorWithString).
///
public void OnWeenieError(uint errorId, string? param)
{
if (WeenieErrorMessages.IsSilentClientControlStatus(errorId))
return;
// Phase I (post-launch fix): translate the wire code into the
// retail-faithful template via WeenieErrorMessages. Many codes
// are *informational* (e.g. 0x051B "You have entered the X
// channel.", 0x051D "Turbine Chat is enabled.") not errors;
// the old "WeenieError 0xNNNN" framing was misleading. Unknown
// codes still fall back to the raw "WeenieError 0xNNNN[: param]"
// form so nothing is silently lost. See
// WeenieErrorMessages.Format for the templates + lookup table.
string text = WeenieErrorMessages.Format(errorId, param);
Append(new ChatEntry(
Kind: ChatKind.System,
Sender: "",
Text: text,
SenderGuid: 0,
ChannelId: errorId)
{
// Retail's HandleFailureEvent @0x00571990 dispatches per ERROR
// CODE across an ~87-case switch, mostly AddTextToScroll(...,
// 0, ...) with a scattered handful at 0x1a (client-local red).
// A full per-code port is future work; 0x00 (Default) matches
// the switch's majority behavior and is the safe baseline.
LogTextType = 0x00u,
});
}
///
/// Channel broadcast — legacy ChatChannel (0x0147) or the
/// TurbineChat (0xF7DE) global community channels (General,
/// Trade, LFG, Roleplay, Society, Olthoi). Pass
/// when the caller knows the
/// friendly room name (TurbineChat dispatch always does); the
/// ChatVM formatter renders entries as
/// "[ChannelName] Sender says, \"text\"" when set.
///
///
/// The retail LogTextType for this line. When
/// (the legacy 0x0147 default), it is derived
/// from via
/// as a HEARD (not
/// own-send) message — correct for this method's only production
/// caller, the inbound ChannelBroadcast GameEvent handler.
/// TurbineChat-sourced calls MUST pass an explicit value computed
/// from the room's TurbineChat.ChatType instead — the wire
/// there is an opaque per-session room
/// GUID, not a legacy channel bitflag, and the two id spaces must
/// never be conflated.
///
public void OnChannelBroadcast(
uint channelId, string sender, string text, uint? logTextType = null, string channelName = "")
{
Append(new ChatEntry(
Kind: ChatKind.Channel,
Sender: sender,
Text: text,
SenderGuid: 0,
ChannelId: channelId)
{
ChannelName = channelName,
LogTextType = logTextType ?? LegacyChannelChatType.Resolve(channelId, ownSend: false),
});
}
/// GameEvent Tell (0x02BD) — whisper received.
///
/// The wire chatType from the Tell GameEvent payload
/// (GameEvents.Tell.ChatType) — retail's normal value is
/// 0x03 (Tell), which is also this parameter's default for
/// callers without a wire value in hand.
///
public void OnTellReceived(string sender, string text, uint senderGuid, uint logTextType = 0x03u)
{
Append(new ChatEntry(
Kind: ChatKind.Tell,
Sender: sender,
Text: text,
SenderGuid: senderGuid,
ChannelId: 0)
{
LogTextType = logTextType,
});
}
///
/// System chat — covers GameMessageSystemChat (0xF7E0
/// ServerMessage) and GameEventCommunicationTransientString
/// (0x02EB). Phase J follow-up: dedupe identical text arriving
/// within so flows that fire on
/// both opcodes (e.g. "Unknown command: help" via help-command
/// failure path) only show once.
///
public void OnSystemMessage(string text, uint chatType)
{
var now = DateTime.UtcNow;
if (text == _lastSystemText && (now - _lastSystemAt) < SystemDedupWindow)
{
// Suppress the dup — the wire-level duplicate isn't a
// user-meaningful signal. Reset the timer so a long burst
// of the same text still skips.
_lastSystemAt = now;
return;
}
_lastSystemText = text;
_lastSystemAt = now;
Append(new ChatEntry(
Kind: ChatKind.System,
Sender: "",
Text: text,
SenderGuid: 0,
ChannelId: chatType)
{
// `chatType` IS the retail LogTextType here — every caller
// (ServerMessage.ChatType, GameEventWiring's transient/
// query-age/use-done sites, App's client-command echoes)
// already passes the wire/retail-correct value.
LogTextType = chatType,
});
}
///
/// GameEvent PopupString (0x0004) — modal dialog text.
///
///
/// Retail shows PopUpString as a MODAL DIALOG
/// (Handle_Communication__PopUpString @0x0057FE80), never as a
/// chat-log line — acdream's choice to render it in chat at all is a
/// registered divergence (register row AP-175). Fixed at LogTextType
/// 0x00 (Default/green) to preserve the color this entry has
/// always rendered with; retail has no chat color for this type since
/// it never reaches the chat log.
///
public void OnPopup(string text)
{
Append(new ChatEntry(
Kind: ChatKind.Popup,
Sender: "",
Text: text,
SenderGuid: 0,
ChannelId: 0)
{
LogTextType = 0x00u,
});
}
///
/// Phase I.7: combat-translator emits a pre-formatted line. The
/// translator () subscribes to
/// events and renders the retail
/// template (e.g. "You hit Mosswart for 12 slashing damage (54.0%)
/// Critical hit.") and decorates the entry with a
/// so the panel can color the
/// line. Maps to holtburger's info().combat() /
/// warning().combat() / error().combat() tag flow at
/// chat.rs:221-308.
///
///
/// The retail LogTextType for this combat line. Callers should
/// pass one of the ACE-cited combat types (0x16 Combat_Self for
/// lines about the local player's OWN offensive action, 0x15
/// Combat_Enemy for lines about an enemy's action against the local
/// player — see ) or 0x00
/// Default for retail's decompiled kill/death-notification color
/// (HandleKillerNotificationEvent @0x0056C410). Defaults to
/// 0x06 (the generic Combat slot) for callers with no more
/// specific classification in hand.
///
public void OnCombatLine(
string text, Combat.CombatLineKind kind = Combat.CombatLineKind.Info, uint logTextType = 0x06u)
{
Append(new ChatEntry(
Kind: ChatKind.Combat,
Sender: "",
Text: text,
SenderGuid: 0,
ChannelId: 0)
{
CombatKind = kind,
LogTextType = logTextType,
});
}
///
/// Echo the player's own outbound message after local send.
///
///
///
/// - Say: pass as
/// empty; the formatter renders "You say, \"text\"".
/// - Tell: pass the target name; the formatter
/// renders "You tell {target}, \"text\"".
/// - Channel: do not call for global community
/// channels — the server (ACE TurbineChatHandler) echoes the
/// broadcast back to the sender already, so optimistic-echoing
/// would double-print. For legacy channels (Fellowship,
/// Allegiance) where the server may not echo, pass the
/// channel name as ; it
/// becomes the entry's ChannelName.
///
/// SenderGuid == 0 on the resulting entry is the
/// discriminator the formatter uses to render outgoing-vs-incoming
/// (a real incoming Tell carries the sender's player guid).
///
///
/// The retail LogTextType for this self-sent line. When
/// , defaults to 0x04 Speech_Direct_Send
/// for Tell (retail's own-echo "You tell ..." type — cross-check
/// ACE's ChatMessageType.OutgoingTell comment "You tell ...") or
/// 0x0B Social_Send for Channel (the simplified own-send default
/// research doc §3.3 records; the LiveSessionCommandRouter production
/// caller overrides this with the precise per-channel-bit value from
/// instead of relying on
/// this fallback).
///
public void OnSelfSent(ChatKind kind, string text, string targetOrChannel = "", uint? logTextType = null)
{
Append(new ChatEntry(
Kind: kind,
// For Tell, Sender carries the target name (so the formatter
// can render "You tell {Sender}..."). For LocalSpeech, we
// leave Sender empty and let the formatter substitute "You".
// For Channel callers, Sender stays empty too — ChannelName
// (below) carries the friendly name.
Sender: kind == ChatKind.Tell ? targetOrChannel : "",
Text: text,
SenderGuid: 0,
ChannelId: 0)
{
ChannelName = kind == ChatKind.Channel ? targetOrChannel : "",
LogTextType = logTextType ?? (kind == ChatKind.Tell ? 0x04u : 0x0Bu),
});
}
private void Append(ChatEntry entry)
{
_buffer.Enqueue(entry);
while (_buffer.Count > _maxEntries)
_buffer.TryDequeue(out _);
Interlocked.Increment(ref _revision);
EntryAppended?.Invoke(entry);
}
public void Clear()
{
while (_buffer.TryDequeue(out _)) { /* drain */ }
Interlocked.Increment(ref _revision);
}
}
public enum ChatKind
{
LocalSpeech,
RangedSpeech,
Channel,
Tell,
System,
Popup,
Emote,
SoulEmote,
///
/// Phase I.7: a combat feedback line emitted by
/// from
/// events. The accompanying field
/// drives panel coloring (info / warning / error per holtburger
/// chat.rs:221-308).
///
Combat,
}
public readonly record struct ChatEntry(
ChatKind Kind,
string Sender,
string Text,
uint SenderGuid,
uint ChannelId)
{
public DateTime Received { get; init; } = DateTime.UtcNow;
///
/// Phase I.7: severity bucket for
/// entries. Null for every other kind. Drives the
/// 's TextColored color choice.
///
public Combat.CombatLineKind? CombatKind { get; init; }
///
/// Friendly name of the channel for
/// entries (e.g. "General", "Trade", "LFG", "Fellowship"). Empty
/// for non-Channel kinds. Used by ChatVM.FormatEntry to
/// render lines as "[ChannelName] Sender says, \"text\"".
/// Falls back to "ch {ChannelId}" if not populated.
///
public string ChannelName { get; init; } = "";
///
/// Campaign CH slice CH1: the retail wire LogTextType
/// (0x00-0x21) that keys
/// RetailChatColorTable/ChatInterface::BuildChatColorLookupTable
/// @0x004F31C0. This is the FULL 34-value retail index space, NOT
/// — retail colors by this integer, never by our
/// synthetic 9-value . Populated by every
/// OnXxx ingestion method above; defaults to 0x00
/// (Default/green, retail's own unfilled-slot default) for any entry
/// constructed without setting it explicitly.
///
public uint LogTextType { get; init; } = 0x00u;
}