2026-05-27 14:19:32 +08:00

91 lines
2.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* @Author: 白哉
* @Description: 聊天管理
* @Date: 2026年01月19日 星期一 11:01:05
* @Modify:
*/
using System;
using System.Collections.Generic;
using MemoryPack;
using TH1_Logic.Net;
using TH1_Logic.Steam;
using UnityEngine;
namespace TH1_Logic.Chat
{
public class ChatManager
{
public static ChatManager Instance = new ChatManager();
public List<ChatItem> ChatItems = new List<ChatItem>();
private Dictionary<int, ChatItem> _chatItems = new Dictionary<int, ChatItem>();
private const int MaxStorageCount = 999;
private const int TrimCount = 900;
/// <summary>
/// ChatItems 发生变化时触发UI 层订阅此回调来刷新显示。
/// </summary>
public System.Action OnChatUpdated;
public void SendChatItem(string message)
{
var lobby = LobbyManager.Instance.Lobby;
if (lobby == null || !lobby.IsInLobby()) return;
var item = new ChatItem();
item.Hash = System.Guid.NewGuid().GetHashCode();
item.SenderId = lobby.GetSelfMemberId();
item.Message = BannedWordFilter.Filter(message, BannedTextContext.Chat, item.SenderId);
item.Time = Time.time;
ChatItems.Add(item);
_chatItems[item.Hash] = item;
if (lobby.IsLobbyOwner()) GameNetSender.Instance.BroadcastChatMessage(item);
else GameNetSender.Instance.SendChatMessage(item);
TrimIfNeeded();
Debug.Log($"[ChatManager] SendChatItem: \"{message}\", total={ChatItems.Count}, listeners={OnChatUpdated?.GetInvocationList()?.Length ?? 0}");
OnChatUpdated?.Invoke();
}
public void ReceiveChatItem(ChatItem newItem)
{
if (newItem == null || _chatItems.ContainsKey(newItem.Hash)) return;
newItem.Message = BannedWordFilter.Filter(newItem.Message, BannedTextContext.Chat, newItem.SenderId);
newItem.Time = Time.time;
ChatItems.Add(newItem);
_chatItems[newItem.Hash] = newItem;
if (LobbyManager.Instance.Lobby.IsLobbyOwner()) GameNetSender.Instance.BroadcastChatMessage(newItem);
TrimIfNeeded();
OnChatUpdated?.Invoke();
}
private void TrimIfNeeded()
{
if (ChatItems.Count <= MaxStorageCount) return;
for (int i = 0; i < TrimCount; i++)
_chatItems.Remove(ChatItems[i].Hash);
ChatItems.RemoveRange(0, TrimCount);
}
}
[MemoryPackable]
public partial class ChatItem
{
public int Hash;
public float Time;
public ulong SenderId;
public string Message;
[MemoryPackIgnore]
public bool AlreadyUIShow;
}
}