Improve piano instruments, previews, and key-stream safeguards

This commit is contained in:
Jage9
2026-02-22 23:51:13 -05:00
parent 1319c044dd
commit 89c6aa7e9b
10 changed files with 176 additions and 10 deletions

View File

@@ -32,9 +32,22 @@ INSTRUMENT_OPTIONS: tuple[str, ...] = (
"bass",
"violin",
"synth_lead",
"nintendo",
"drum_kit",
)
DEFAULT_ENVELOPE_BY_INSTRUMENT: dict[str, tuple[int, int]] = {
"piano": (15, 45),
"electric_piano": (12, 40),
"guitar": (8, 35),
"organ": (25, 70),
"bass": (10, 35),
"violin": (22, 75),
"synth_lead": (6, 30),
"nintendo": (2, 28),
"drum_kit": (1, 22),
}
PROPERTY_METADATA: dict[str, dict[str, object]] = {
"title": {"valueType": "text", "tooltip": "Display name spoken and shown for this item.", "maxLength": 80},
"instrument": {"valueType": "list", "tooltip": "Instrument voice used when playing this piano."},
@@ -62,6 +75,7 @@ def validate_update(_item: WorldItem, next_params: dict) -> dict:
instrument = str(next_params.get("instrument", "piano")).strip().lower()
if instrument not in INSTRUMENT_OPTIONS:
raise ValueError(f"instrument must be one of: {', '.join(INSTRUMENT_OPTIONS)}.")
previous_instrument = str(_item.params.get("instrument", "piano")).strip().lower()
next_params["instrument"] = instrument
try:
@@ -70,14 +84,17 @@ def validate_update(_item: WorldItem, next_params: dict) -> dict:
raise ValueError("attack must be an integer between 0 and 100.") from exc
if not (0 <= attack <= 100):
raise ValueError("attack must be between 0 and 100.")
next_params["attack"] = attack
try:
decay = int(next_params.get("decay", 45))
except (TypeError, ValueError) as exc:
raise ValueError("decay must be an integer between 0 and 100.") from exc
if not (0 <= decay <= 100):
raise ValueError("decay must be between 0 and 100.")
# When instrument changes, reset envelope to instrument-appropriate defaults.
if instrument != previous_instrument:
attack, decay = DEFAULT_ENVELOPE_BY_INSTRUMENT.get(instrument, (15, 45))
next_params["attack"] = attack
next_params["decay"] = decay
try:

View File

@@ -68,6 +68,7 @@ from .models import (
LOGGER = logging.getLogger("chgrid.server")
PACKET_LOGGER = logging.getLogger("chgrid.server.packet")
CLIENT_PACKET_ADAPTER = TypeAdapter(ClientPacket)
MAX_ACTIVE_PIANO_KEYS_PER_CLIENT = 32
class SignalingServer:
@@ -92,6 +93,7 @@ class SignalingServer:
self.clients: dict[ServerConnection, ClientConnection] = {}
self.item_service = ItemService(state_file=state_file)
self.item_last_use_ms: dict[str, int] = {}
self.active_piano_keys_by_client: dict[str, set[str]] = {}
self.grid_size = max(1, grid_size)
self.instance_id = str(uuid.uuid4())
self.server_version = self._resolve_server_version()
@@ -260,6 +262,7 @@ class SignalingServer:
finally:
if websocket in self.clients:
disconnected = self.clients.pop(websocket)
self.active_piano_keys_by_client.pop(disconnected.id, None)
for item in self.item_service.drop_carried_items_for_disconnect(disconnected):
await self._broadcast_item(item)
self.item_service.save_state()
@@ -666,6 +669,13 @@ class SignalingServer:
return
if item.carrierId is None and (item.x != client.x or item.y != client.y):
return
active_keys = self.active_piano_keys_by_client.setdefault(client.id, set())
if packet.on:
if packet.keyId not in active_keys and len(active_keys) >= MAX_ACTIVE_PIANO_KEYS_PER_CLIENT:
return
active_keys.add(packet.keyId)
else:
active_keys.discard(packet.keyId)
instrument = str(item.params.get("instrument", "piano")).strip().lower()
attack = int(item.params.get("attack", 15)) if isinstance(item.params.get("attack", 15), (int, float)) else 15
decay = int(item.params.get("decay", 45)) if isinstance(item.params.get("decay", 45), (int, float)) else 45

View File

@@ -370,8 +370,6 @@ async def test_piano_update_and_use(monkeypatch: pytest.MonkeyPatch) -> None:
"itemId": item.id,
"params": {
"instrument": "drum_kit",
"attack": 22,
"decay": 67,
"emitRange": 12,
},
}
@@ -379,10 +377,19 @@ async def test_piano_update_and_use(monkeypatch: pytest.MonkeyPatch) -> None:
)
assert send_payloads[-1].ok is True
assert item.params.get("instrument") == "drum_kit"
assert item.params.get("attack") == 22
assert item.params.get("decay") == 67
assert item.params.get("attack") == 1
assert item.params.get("decay") == 22
assert item.params.get("emitRange") == 12
await server._handle_message(
client,
json.dumps({"type": "item_update", "itemId": item.id, "params": {"instrument": "nintendo"}}),
)
assert send_payloads[-1].ok is True
assert item.params.get("instrument") == "nintendo"
assert item.params.get("attack") == 2
assert item.params.get("decay") == 28
await server._handle_message(client, json.dumps({"type": "item_use", "itemId": item.id}))
assert send_payloads[-1].ok is True
assert "begin playing" in send_payloads[-1].message.lower()
@@ -438,3 +445,38 @@ async def test_piano_note_packet_broadcasts(monkeypatch: pytest.MonkeyPatch) ->
assert getattr(packet, "attack", -1) == 20
assert getattr(packet, "decay", -1) == 60
assert getattr(packet, "emitRange", -1) == 12
@pytest.mark.asyncio
async def test_piano_note_key_cap(monkeypatch: pytest.MonkeyPatch) -> None:
server = SignalingServer("127.0.0.1", 8765, None, None)
ws_sender = _fake_ws()
sender = ClientConnection(websocket=ws_sender, id="u1", nickname="tester", x=5, y=6)
server.clients[ws_sender] = sender
item = server.item_service.default_item(sender, "piano")
server.item_service.add_item(item)
broadcast_payloads: list[object] = []
async def fake_send(websocket: ServerConnection, packet: object) -> None:
return
async def fake_broadcast(packet: object, exclude: ServerConnection | None = None) -> None:
broadcast_payloads.append(packet)
monkeypatch.setattr(server, "_send", fake_send)
monkeypatch.setattr(server, "_broadcast", fake_broadcast)
for index in range(32):
await server._handle_message(
sender,
json.dumps({"type": "item_piano_note", "itemId": item.id, "keyId": f"Key{index}", "midi": 60, "on": True}),
)
assert len(broadcast_payloads) == 32
# 33rd distinct held key is dropped by cap.
await server._handle_message(
sender,
json.dumps({"type": "item_piano_note", "itemId": item.id, "keyId": "KeyOverflow", "midi": 60, "on": True}),
)
assert len(broadcast_payloads) == 32