@idosgames/netplay 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +62 -2
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +346 -0
- package/dist/index.d.ts +346 -0
- package/dist/index.js +1 -0
- package/package.json +47 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 iDos Games
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,63 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @idosgames/netplay
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The network layer of iDosGames room games. Engine-free, no dependencies.
|
|
4
|
+
|
|
5
|
+
| Piece | What |
|
|
6
|
+
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
7
|
+
| `ByteWriter` / `ByteReader`, `encodeJson` | the message codec: dense binary records for frequent poses, JSON (deflated when large) for rare messages |
|
|
8
|
+
| `NetRoom` | a game in a room over any peer transport: the roster, joining a running game (HELLO / WELCOME with the host's state), relaying through the host of a star room, the host handover, the successor by link speed, taking over a host that vanished without leaving (`watchHost`) |
|
|
9
|
+
| `Replicator` | entities owned by one player (their character, the car they drive, the police chasing them) and their copies on the others, with interpolated poses; late joiners and leaving owners handled |
|
|
10
|
+
| `SnapshotBuffer` | the pose interpolation on its own |
|
|
11
|
+
| `MemoryHub` | a room in memory for tests and offline checks |
|
|
12
|
+
|
|
13
|
+
The lobby opens the room (the multiplayer system, `ctx.multiplayer`); the game gets the session in
|
|
14
|
+
`start(room)` and wraps it:
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import type { RealtimeSession } from "@idosgames/core/realtime";
|
|
18
|
+
import {
|
|
19
|
+
NetRoom,
|
|
20
|
+
Replicator,
|
|
21
|
+
defineJson,
|
|
22
|
+
type NetTransport,
|
|
23
|
+
} from "@idosgames/netplay";
|
|
24
|
+
|
|
25
|
+
const transport = (s: RealtimeSession): NetTransport => ({
|
|
26
|
+
get selfId() {
|
|
27
|
+
return s.selfId;
|
|
28
|
+
},
|
|
29
|
+
get hostId() {
|
|
30
|
+
return s.hostId;
|
|
31
|
+
},
|
|
32
|
+
topology: s.topology,
|
|
33
|
+
openPeers: () => s.openPeers(),
|
|
34
|
+
isOpen: (p) => s.isOpen(p),
|
|
35
|
+
send: (p, ch, d) => s.send(p, ch, d),
|
|
36
|
+
broadcast: (ch, d, ex) => s.broadcast(ch, d, ex),
|
|
37
|
+
on: (ev, fn) => s.on(ev, fn as never),
|
|
38
|
+
setSuccessor: (u) => s.setSuccessor(u),
|
|
39
|
+
linkStats: (p) => s.linkStats(p),
|
|
40
|
+
claimHost: () => s.claimHost(),
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
const room = new NetRoom(transport(session), {
|
|
44
|
+
name,
|
|
45
|
+
meta: { look },
|
|
46
|
+
onWelcome: () => snapshot(),
|
|
47
|
+
});
|
|
48
|
+
const CHAT = defineJson<{ text: string }>(20);
|
|
49
|
+
room.on(CHAT, (m, from) => show(from, m.text));
|
|
50
|
+
room.broadcast(CHAT, { text: "hi" });
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
The game calls `room.pickSuccessor()` on the host every few seconds and `room.watchHost()` on a guest
|
|
54
|
+
every frame: a host that left properly hands the role over itself; one that just
|
|
55
|
+
vanished (closed tab, lost network) is replaced by its successor through the transport's `claimHost`
|
|
56
|
+
after 5 s, the other guests try later in turn. The server lets exactly one through.
|
|
57
|
+
|
|
58
|
+
Message types 0..15 belong to the room, 16..255 to the game. A `Replicator` takes three types in a row
|
|
59
|
+
from its `baseType`.
|
|
60
|
+
|
|
61
|
+
Why a package: it is a network format with its runtime that more than one catalog game needs (Open
|
|
62
|
+
City first, VoxelCraft's own copy moves onto it later). See the "Package or module" rule in the
|
|
63
|
+
repository's CLAUDE.md.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var g=new TextEncoder,y=new TextDecoder,h=class{buf;view;at=0;constructor(e=256){this.buf=new Uint8Array(e),this.view=new DataView(this.buf.buffer);}ensure(e){if(this.at+e<=this.buf.length)return;let t=this.buf.length*2;for(;t<this.at+e;)t*=2;let s=new Uint8Array(t);s.set(this.buf.subarray(0,this.at)),this.buf=s,this.view=new DataView(s.buffer);}u8(e){return this.ensure(1),this.view.setUint8(this.at,e),this.at+=1,this}u16(e){return this.ensure(2),this.view.setUint16(this.at,e),this.at+=2,this}i16(e){return this.ensure(2),this.view.setInt16(this.at,e),this.at+=2,this}u32(e){return this.ensure(4),this.view.setUint32(this.at,e>>>0),this.at+=4,this}i32(e){return this.ensure(4),this.view.setInt32(this.at,e|0),this.at+=4,this}f32(e){return this.ensure(4),this.view.setFloat32(this.at,e),this.at+=4,this}bytes(e){return this.ensure(e.byteLength),this.buf.set(e,this.at),this.at+=e.byteLength,this}angle(e){let t=e%(Math.PI*2);return t>Math.PI&&(t-=Math.PI*2),t<-Math.PI&&(t+=Math.PI*2),this.i16(Math.round(t*1e4))}str(e){let t=g.encode(e);return this.u16(t.byteLength),this.bytes(t)}fixed(e,t){return this.i16(Math.max(-32768,Math.min(32767,Math.round(e/t))))}unit(e){return this.u8(Math.max(0,Math.min(255,Math.round(e*255))))}get length(){return this.at}finish(){return this.buf.slice(0,this.at)}},l=class{constructor(e){this.buf=e;this.view=new DataView(e.buffer,e.byteOffset,e.byteLength);}buf;view;at=0;get left(){return this.buf.byteLength-this.at}need(e){if(this.at+e>this.buf.byteLength)throw new RangeError("Truncated message")}u8(){return this.need(1),this.view.getUint8(this.at++)}u16(){this.need(2);let e=this.view.getUint16(this.at);return this.at+=2,e}i16(){this.need(2);let e=this.view.getInt16(this.at);return this.at+=2,e}u32(){this.need(4);let e=this.view.getUint32(this.at);return this.at+=4,e}i32(){this.need(4);let e=this.view.getInt32(this.at);return this.at+=4,e}f32(){this.need(4);let e=this.view.getFloat32(this.at);return this.at+=4,e}angle(){return this.i16()/1e4}str(){let e=this.u16();this.need(e);let t=y.decode(this.buf.subarray(this.at,this.at+e));return this.at+=e,t}fixed(e){return this.i16()*e}unit(){return this.u8()/255}rest(){let e=this.buf.subarray(this.at);return this.at=this.buf.byteLength,e}},U=2048;async function N(i,e){let t=new Blob([i]).stream().pipeThrough(e);return new Uint8Array(await new Response(t).arrayBuffer())}var H=typeof CompressionStream<"u";async function _(i,e){let t=g.encode(JSON.stringify(e)),s=0;H&&t.byteLength>U&&(t=await N(t,new CompressionStream("deflate-raw")),s|=1);let r=new Uint8Array(t.byteLength+2);return r[0]=i,r[1]=s,r.set(t,2),r}function d(i,e){let t=g.encode(JSON.stringify(e)),s=new Uint8Array(t.byteLength+2);return s[0]=i,s[1]=0,s.set(t,2),s}async function D(i){try{let e=i[1]??0,t=i.subarray(2);return e&1&&(t=await N(t,new DecompressionStream("deflate-raw"))),JSON.parse(y.decode(t))}catch{return null}}function u(i){try{return (i[1]??0)&1?null:JSON.parse(y.decode(i.subarray(2)))}catch{return null}}var k=16;function C(i){if(!Number.isInteger(i)||i<k||i>255)throw new RangeError(`netplay: message type ${i} must be 16..255`)}function m(i,e="rel"){return C(i),{type:i,channel:e,encode:t=>d(i,t),decode:t=>u(t)}}function M(i,e,t,s="fast"){return C(i),{type:i,channel:s,encode(r){let n=new h(64).u8(i);return e(n,r),n.finish()},decode(r){try{let n=new l(r);return n.u8(),t(n)}catch{return null}}}}var P=1,A=2,R=3,v=4,x=5,L=6,E=5e3,J=2e4,B=3e3,b=2e3,W=3e4,w=class{constructor(e,t){this.transport=e;this.opts=t;this.selfId=e.selfId,this.members.set(this.selfId,{userId:this.selfId,name:t.name,meta:t.meta}),this.welcomed=this.isHost;let s=e;this.offs.push(s.on("message",r=>this.receive(r.from,r.data)),s.on("peerOpen",r=>this.peerOpen(r.peerId)),s.on("peerClose",r=>{!this.isHost&&r.peerId===s.hostId&&this.hostLinkSeen&&!this.hostLostAt&&(this.hostLostAt=this.now());}),s.on("memberLeft",r=>this.dropMember(r.userId)),s.on("hostChanged",r=>this.hostChanged(r.hostId)),s.on("left",()=>this.close("left")),s.on("removed",r=>this.close(r.reason||"removed")),s.on("roomClosed",()=>this.close("closed"))),!this.isHost&&s.isOpen(s.hostId)&&(this.hostLinkSeen=true,this.sendHello());}transport;opts;selfId;members=new Map;handlers=new Map;offs=[];welcomed;successor=null;closedFlag=false;hostLinkSeen=false;hostLostAt=0;nextClaimAt=0;claimRetry=b;now(){return this.opts.now?this.opts.now():Date.now()}get isHost(){return this.transport.hostId===this.selfId}get hostId(){return this.transport.hostId}get ready(){return this.welcomed}get closed(){return this.closedFlag}roster(){return [...this.members.values()]}member(e){return this.members.get(e)}setMeta(e){let t=this.members.get(this.selfId);t&&(t.meta=e),this.broadcastRaw(d(L,{meta:e}),"rel"),this.opts.onRoster?.(this.roster());}on(e,t){e.channel==="fast"&&this.fastTypes.add(e.type);let s=this.handlers.get(e.type)??new Set,r=(n,o)=>{let a=e.decode(n);a!==null&&t(a,o);};return s.add(r),this.handlers.set(e.type,s),()=>s.delete(r)}broadcast(e,t){e.channel==="fast"&&this.fastTypes.add(e.type),this.broadcastRaw(e.encode(t),e.channel);}sendTo(e,t,s){if(e===this.selfId)return;let r=t.encode(s),n=this.transport;if(n.topology==="Mesh"||this.isHost||e===n.hostId){n.send(e,t.channel,r);return}let o=new h(r.byteLength+32).u8(v).u8(1).str(e);o.bytes(r),n.send(n.hostId,t.channel,o.finish());}pickSuccessor(){if(!this.isHost)return;let e=this.transport,t=null,s=1/0;for(let r of e.openPeers()){if(!this.members.has(r))continue;let n=e.linkStats?.(r)?.rttMs||999;n<s&&(s=n,t=r);}t!==this.successor&&(this.successor=t,e.setSuccessor?.(t),this.broadcastRoster());}get successorId(){return this.successor}watchHost(){if(this.isHost||this.closedFlag||!this.hostLinkSeen)return;let e=this.transport;if(e.isOpen(e.hostId)){this.hostLostAt=0,this.claimRetry=b;return}let t=this.now();this.hostLostAt||(this.hostLostAt=t);let s=this.successor===this.selfId?E:J+this.claimRank()*B;t-this.hostLostAt<s||t<this.nextClaimAt||!e.claimHost||(this.nextClaimAt=t+this.claimRetry,this.claimRetry=Math.min(W,this.claimRetry*2),Promise.resolve(e.claimHost()).catch(()=>{}));}claimRank(){let e=[...this.members.keys()].filter(t=>t!==this.transport.hostId&&t!==this.successor).sort();return Math.max(0,e.indexOf(this.selfId))}dispose(){for(let e of this.offs.splice(0))e();this.handlers.clear();}broadcastRaw(e,t){let s=this.transport;if(s.topology==="Mesh"||this.isHost){s.broadcast(t,e);return}if(!s.isOpen(s.hostId))return;let r=new h(e.byteLength+2).u8(v).u8(0);r.bytes(e),s.send(s.hostId,t,r.finish());}receive(e,t){let s=t[0];if(s!==void 0)switch(s){case v:this.isHost&&this.relay(e,t);return;case x:{try{let r=new l(t);r.u8();let n=r.str();this.receive(n,r.rest());}catch{}return}case P:this.isHost&&this.onHello(e,t);return;case A:e===this.transport.hostId&&this.onWelcome(t);return;case R:e===this.transport.hostId&&this.onRoster(t);return;case L:{let r=u(t),n=this.members.get(e);r&&n&&(n.meta=r.meta,this.opts.onRoster?.(this.roster()));return}default:if(s<k)return;for(let r of this.handlers.get(s)??[])r(t,e);}}relay(e,t){let s,r=null;try{s=new l(t),s.u8(),s.u8()===1&&(r=s.str());}catch{return}let n=s.rest(),o="rel",a=()=>{let p=new h(n.byteLength+32).u8(x).str(e);return p.bytes(n),p.finish()};if(r){r===this.selfId?this.receive(e,n.slice()):this.transport.send(r,this.channelOf(n,o),a());return}let f=a(),O=this.channelOf(n,o);for(let p of this.transport.openPeers())p!==e&&this.transport.send(p,O,f);this.receive(e,n.slice());}channelOf(e,t){let s=e[0]??0;return this.fastTypes.has(s)?"fast":t}fastTypes=new Set;peerOpen(e){this.isHost||e!==this.transport.hostId||(this.hostLinkSeen=true,this.hostLostAt=0,this.welcomed||this.sendHello());}sendHello(){let e=this.members.get(this.selfId),t={name:e?.name??this.opts.name,meta:e?.meta??this.opts.meta};this.transport.send(this.transport.hostId,"rel",d(P,t));}onHello(e,t){let s=u(t);if(!s)return;let r=!this.members.has(e),n={userId:e,name:String(s.name??"").slice(0,40),meta:s.meta};this.members.set(e,n);let o={roster:this.roster(),state:this.opts.onWelcome?.(e)??null,successor:this.successor};this.transport.send(e,"rel",d(A,o)),this.broadcastRoster(),r&&this.opts.onJoin?.(n),this.opts.onRoster?.(this.roster());}onWelcome(e){let t=u(e);t&&(this.applyRoster(t.roster),this.successor=typeof t.successor=="string"?t.successor:null,this.welcomed=true,this.opts.onWelcomed?.(t.state));}onRoster(e){let t=u(e);t&&(this.successor=typeof t.successor=="string"?t.successor:null,this.applyRoster(t.roster));}applyRoster(e){let t=new Set;for(let s of e){if(!s||typeof s.userId!="string"||(t.add(s.userId),s.userId===this.selfId))continue;let r=this.members.has(s.userId),n={userId:s.userId,name:String(s.name??""),meta:s.meta};this.members.set(s.userId,n),r||this.opts.onJoin?.(n);}for(let s of [...this.members.keys()])s!==this.selfId&&!t.has(s)&&this.dropMember(s);this.opts.onRoster?.(this.roster());}broadcastRoster(){this.transport.broadcast("rel",d(R,{roster:this.roster(),successor:this.successor}));}dropMember(e){e===this.selfId||!this.members.delete(e)||(this.opts.onLeave?.(e),this.isHost&&this.broadcastRoster(),this.opts.onRoster?.(this.roster()));}hostChanged(e){let t=e===this.selfId;this.hostLostAt=0,this.nextClaimAt=0,this.claimRetry=b,this.hostLinkSeen=!t&&this.transport.isOpen(e),this.successor=null,t?(this.welcomed=true,this.broadcastRoster()):(this.welcomed=false,this.transport.isOpen(e)&&this.sendHello()),this.opts.onHostChanged?.(t,e);}close(e){this.closedFlag||(this.closedFlag=true,this.opts.onClosed?.(e),this.dispose());}};function K(i,e,t){let s=(e-i)%(Math.PI*2);return s>Math.PI&&(s-=Math.PI*2),s<-Math.PI&&(s+=Math.PI*2),i+s*t}function $(i,e,t){return i+(e-i)*t}var c=class{constructor(e,t=.12,s=32){this.mix=e;this.delay=t;this.capacity=s;}mix;delay;capacity;samples=[];push(e,t){let s=this.samples[this.samples.length-1];s&&e<s.t||(this.samples.push({t:e,pose:t}),this.samples.length>this.capacity&&this.samples.shift());}latest(){return this.samples[this.samples.length-1]?.pose??null}get size(){return this.samples.length}sample(e){let t=this.samples;if(!t.length)return null;let s=e-this.delay,r=t[0];if(s<=r.t)return r.pose;for(let n=t.length-1;n>0;n--){let o=t[n-1],a=t[n];if(s>=o.t){if(s>=a.t)return a.pose;let f=a.t-o.t;return f>0?this.mix(o.pose,a.pose,(s-o.t)/f):a.pose}}return t[t.length-1].pose}clear(){this.samples.length=0;}};var I=class{constructor(e,t){this.room=e;this.opts=t;let s=t.rate??15;this.interval=1/s,this.delay=t.delay??2/s,this.spawnMsg=m(t.baseType),this.poseMsg=M(t.baseType+1,(r,n)=>{r.u16(n.length);for(let o of n)r.u16(o.n),t.writePose(r,o.pose);},r=>{let n=[],o=r.u16();for(let a=0;a<o;a++)n.push({n:r.u16(),pose:t.readPose(r)});return n}),this.goneMsg=m(t.baseType+2),this.offs.push(e.on(this.spawnMsg,(r,n)=>this.remoteSpawn(n,r)),e.on(this.poseMsg,(r,n)=>this.remotePoses(n,r)),e.on(this.goneMsg,(r,n)=>{let o=`${n}/${r.n}`;if(r.update){let a=this.replicas.get(o);a&&r.data!==void 0&&(a.data=r.data,this.opts.onData?.(o,r.data));return}this.remoteGone(o);}));}room;opts;owned=new Map;replicas=new Map;nextN=1;lastSend=-1/0;spawnMsg;poseMsg;goneMsg;offs=[];interval;delay;own(e,t,s){let r=this.nextN++;for(this.nextN>65535&&(this.nextN=1);this.owned.has(r);)r=this.nextN++;return this.owned.set(r,{n:r,kind:e,data:t,pose:s}),this.room.broadcast(this.spawnMsg,{n:r,kind:e,data:t}),`${this.room.selfId}/${r}`}update(e,t){let s=this.owned.get(this.numberOf(e));s&&(s.data=t,this.room.broadcast(this.goneMsg,{n:s.n,data:t,update:true}));}disown(e){let t=this.numberOf(e);this.owned.delete(t)&&this.room.broadcast(this.goneMsg,{n:t});}isMine(e){return e.startsWith(this.room.selfId+"/")}tick(){let e=this.opts.now();if(e-this.lastSend<this.interval||!this.owned.size)return;this.lastSend=e;let t=[];for(let s of this.owned.values())t.push({n:s.n,pose:s.pose()});for(let s=0;s<t.length;s+=24)this.room.broadcast(this.poseMsg,t.slice(s,s+24));}onJoin(e){for(let t of this.owned.values())this.room.sendTo(e,this.spawnMsg,{n:t.n,kind:t.kind,data:t.data});}onLeave(e){for(let t of [...this.replicas.values()])t.owner===e&&this.remoteGone(t.id);}sample(e){return this.replicas.get(e)?.buffer.sample(this.opts.now())??null}replica(e){return this.replicas.get(e)}list(){return [...this.replicas.values()]}dispose(){for(let e of this.offs.splice(0))e();for(let e of [...this.replicas.values()])this.remoteGone(e.id);this.owned.clear();}numberOf(e){let t=e.lastIndexOf("/");return Number(e.slice(t+1))}remoteSpawn(e,t){if(typeof t.n!="number"||typeof t.kind!="string")return;let s=`${e}/${t.n}`,r=this.replicas.get(s);if(r){r.data=t.data,this.opts.onData?.(s,t.data);return}let n={id:s,owner:e,kind:t.kind,data:t.data,buffer:new c(this.opts.lerp,this.delay)};this.replicas.set(s,n),this.opts.onSpawn?.(s,e,t.kind,t.data);}remotePoses(e,t){let s=this.opts.now();for(let r of t)this.replicas.get(`${e}/${r.n}`)?.buffer.push(s,r.pose);}remoteGone(e){let t=this.replicas.get(e);t&&(this.replicas.delete(e),this.opts.onDespawn?.(e,t.owner));}};var T=class{constructor(e="Host"){this.topology=e;}topology;peers=new Map;queue=[];hostId="";join(e){this.hostId||(this.hostId=e);let t=new S(this,e);this.peers.set(e,t);for(let s of this.peers.values())s===t||!this.linked(e,s.selfId)||this.later(()=>{s.emit("peerOpen",{peerId:e}),t.emit("peerOpen",{peerId:s.selfId});});return t}leave(e,t){if(this.peers.delete(e)){for(let s of this.peers.values())s.emit("peerClose",{peerId:e,reason:"left"}),s.emit("memberLeft",{userId:e,kind:"left"});this.hostId===e&&this.promote(t??[...this.peers.keys()][0]??"");}}vanish(e){if(this.peers.delete(e)){this.gone.add(e);for(let t of this.peers.values())t.emit("peerClose",{peerId:e,reason:"lost"});}}claims=0;claim(e){if(this.claims++,!this.gone.has(this.hostId)||!this.peers.has(e))return false;let t=this.hostId;for(let s of this.peers.values())s.emit("memberLeft",{userId:t,kind:"timeout"});return this.promote(e),true}gone=new Set;promote(e){let t=this.hostId;this.hostId=e;let s=this.hostId;for(let r of this.peers.values())r.emit("hostChanged",{hostId:s,previousHostId:t});this.topology==="Host"&&this.later(()=>{let r=this.peers.get(s);for(let n of this.peers.values())n.selfId===s||!r||(n.emit("peerOpen",{peerId:s}),r.emit("peerOpen",{peerId:n.selfId}));});}flush(e=1e4){for(let t=0;t<e&&this.queue.length;t++){let s=this.queue;this.queue=[];for(let n of s)n.to!=="__later__"&&this.peers.get(n.to)?.emit("message",{from:n.from,channel:n.channel,data:n.data});let r=this.jobs.splice(0);for(let n of r)n();}}jobs=[];later(e){this.jobs.push(e),this.queue.push({to:"__later__",from:"",channel:"rel",data:new Uint8Array});}linked(e,t){return e===t||!this.peers.has(e)||!this.peers.has(t)?false:this.topology==="Mesh"||e===this.hostId||t===this.hostId}linksOf(e){return [...this.peers.keys()].filter(t=>this.linked(e,t))}post(e){this.queue.push({...e,data:e.data.slice()});}},S=class{constructor(e,t){this.hub=e;this.selfId=t;}hub;selfId;listeners={};sent=0;get hostId(){return this.hub.hostId}get topology(){return this.hub.topology}openPeers(){return this.hub.linksOf(this.selfId)}isOpen(e){return this.hub.linked(this.selfId,e)}send(e,t,s){return this.isOpen(e)?(this.sent++,this.hub.post({to:e,from:this.selfId,channel:t,data:s}),true):false}broadcast(e,t,s){let r=0;for(let n of this.openPeers())n!==s&&this.send(n,e,t)&&r++;return r}on(e,t){let s=this.listeners,r=s[e]??=new Set;return r.add(t),()=>r.delete(t)}emit(e,t){let s=this.listeners[e];for(let r of [...s??[]])r(t);}linkStats(){return {rttMs:20}}setSuccessor(){}claimHost(){this.hub.claim(this.selfId);}};exports.ByteReader=l;exports.ByteWriter=h;exports.MemoryHub=T;exports.NetRoom=w;exports.Replicator=I;exports.SnapshotBuffer=c;exports.decodeJson=D;exports.decodeJsonSync=u;exports.defineBinary=M;exports.defineJson=m;exports.encodeJson=_;exports.encodeJsonSync=d;exports.lerp=$;exports.lerpAngle=K;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
declare class ByteWriter {
|
|
2
|
+
private buf;
|
|
3
|
+
private view;
|
|
4
|
+
private at;
|
|
5
|
+
constructor(initial?: number);
|
|
6
|
+
private ensure;
|
|
7
|
+
u8(v: number): this;
|
|
8
|
+
u16(v: number): this;
|
|
9
|
+
i16(v: number): this;
|
|
10
|
+
u32(v: number): this;
|
|
11
|
+
i32(v: number): this;
|
|
12
|
+
f32(v: number): this;
|
|
13
|
+
bytes(b: Uint8Array): this;
|
|
14
|
+
/** Угол (радианы) в i16: шаг ~0.0001 рад, глазу неотличимо. */
|
|
15
|
+
angle(rad: number): this;
|
|
16
|
+
/** Строка UTF-8 с длиной u16 впереди. */
|
|
17
|
+
str(s: string): this;
|
|
18
|
+
/** Число в i16 с шагом `step` (шаг 1/32 держит ±1024): вдвое меньше f32. */
|
|
19
|
+
fixed(v: number, step: number): this;
|
|
20
|
+
/** Доля 0..1 в u8. */
|
|
21
|
+
unit(v: number): this;
|
|
22
|
+
get length(): number;
|
|
23
|
+
finish(): Uint8Array;
|
|
24
|
+
}
|
|
25
|
+
declare class ByteReader {
|
|
26
|
+
private readonly buf;
|
|
27
|
+
private readonly view;
|
|
28
|
+
private at;
|
|
29
|
+
constructor(buf: Uint8Array);
|
|
30
|
+
get left(): number;
|
|
31
|
+
private need;
|
|
32
|
+
u8(): number;
|
|
33
|
+
u16(): number;
|
|
34
|
+
i16(): number;
|
|
35
|
+
u32(): number;
|
|
36
|
+
i32(): number;
|
|
37
|
+
f32(): number;
|
|
38
|
+
angle(): number;
|
|
39
|
+
str(): string;
|
|
40
|
+
fixed(step: number): number;
|
|
41
|
+
unit(): number;
|
|
42
|
+
rest(): Uint8Array;
|
|
43
|
+
}
|
|
44
|
+
/** JSON-сообщение: [тип][флаги][тело]. Большое тело сжимается, если среда умеет. */
|
|
45
|
+
declare function encodeJson(type: number, value: unknown): Promise<Uint8Array>;
|
|
46
|
+
/** То же без сжатия и синхронно: для мелких частых сообщений. */
|
|
47
|
+
declare function encodeJsonSync(type: number, value: unknown): Uint8Array;
|
|
48
|
+
/** Тело JSON-сообщения (без байта типа). null: битое. */
|
|
49
|
+
declare function decodeJson<T>(msg: Uint8Array): Promise<T | null>;
|
|
50
|
+
/** Тело JSON-сообщения синхронно; сжатое или битое: null. */
|
|
51
|
+
declare function decodeJsonSync<T>(msg: Uint8Array): T | null;
|
|
52
|
+
|
|
53
|
+
type NetChannel = "rel" | "fast";
|
|
54
|
+
/** События транспорта, которые слушает комната (подмножество событий `RealtimeSession`). */
|
|
55
|
+
interface NetTransportEvents {
|
|
56
|
+
message: {
|
|
57
|
+
from: string;
|
|
58
|
+
channel: NetChannel;
|
|
59
|
+
data: Uint8Array;
|
|
60
|
+
};
|
|
61
|
+
peerOpen: {
|
|
62
|
+
peerId: string;
|
|
63
|
+
};
|
|
64
|
+
peerClose: {
|
|
65
|
+
peerId: string;
|
|
66
|
+
reason: string;
|
|
67
|
+
};
|
|
68
|
+
memberLeft: {
|
|
69
|
+
userId: string;
|
|
70
|
+
kind: string;
|
|
71
|
+
by?: string;
|
|
72
|
+
};
|
|
73
|
+
hostChanged: {
|
|
74
|
+
hostId: string;
|
|
75
|
+
previousHostId: string | null;
|
|
76
|
+
};
|
|
77
|
+
left: Record<string, never>;
|
|
78
|
+
removed: {
|
|
79
|
+
reason: string;
|
|
80
|
+
};
|
|
81
|
+
roomClosed: Record<string, never>;
|
|
82
|
+
}
|
|
83
|
+
/** Транспорт пиров комнаты. */
|
|
84
|
+
interface NetTransport {
|
|
85
|
+
readonly selfId: string;
|
|
86
|
+
readonly hostId: string;
|
|
87
|
+
readonly topology: "Host" | "Mesh";
|
|
88
|
+
openPeers(): string[];
|
|
89
|
+
isOpen(peerId: string): boolean;
|
|
90
|
+
send(peerId: string, channel: NetChannel, data: Uint8Array): boolean;
|
|
91
|
+
broadcast(channel: NetChannel, data: Uint8Array, except?: string): number;
|
|
92
|
+
on<K extends keyof NetTransportEvents>(event: K, fn: (e: NetTransportEvents[K]) => void): () => void;
|
|
93
|
+
/** Кто станет хостом, если этот уйдёт (транспорт держит к нему запасную связь). */
|
|
94
|
+
setSuccessor?(userId: string | null): void;
|
|
95
|
+
/** Задержка связи с пиром, мс. */
|
|
96
|
+
linkStats?(peerId: string): {
|
|
97
|
+
rttMs: number;
|
|
98
|
+
} | null;
|
|
99
|
+
/**
|
|
100
|
+
* Перехватить роль хоста, который замолчал. Решает транспорт (сервер пускает одного и только когда
|
|
101
|
+
* хост молчит дольше своего порога); удалось: придёт `hostChanged`.
|
|
102
|
+
*/
|
|
103
|
+
claimHost?(): Promise<unknown> | void;
|
|
104
|
+
}
|
|
105
|
+
/** Игрок в составе комнаты. */
|
|
106
|
+
interface NetMember<M = unknown> {
|
|
107
|
+
userId: string;
|
|
108
|
+
name: string;
|
|
109
|
+
/** Данные игры о игроке (облик, цвет): их задаёт сам игрок (`setMeta`). */
|
|
110
|
+
meta: M;
|
|
111
|
+
}
|
|
112
|
+
/** Сообщение игры: тип, канал, как писать и читать. */
|
|
113
|
+
interface NetMessage<T> {
|
|
114
|
+
readonly type: number;
|
|
115
|
+
readonly channel: NetChannel;
|
|
116
|
+
encode(value: T): Uint8Array;
|
|
117
|
+
decode(data: Uint8Array): T | null;
|
|
118
|
+
}
|
|
119
|
+
/** Редкое сообщение JSON (по умолчанию надёжный канал). */
|
|
120
|
+
declare function defineJson<T>(type: number, channel?: NetChannel): NetMessage<T>;
|
|
121
|
+
/** Частое двоичное сообщение (по умолчанию быстрый канал). */
|
|
122
|
+
declare function defineBinary<T>(type: number, write: (w: ByteWriter, value: T) => void, read: (r: ByteReader) => T, channel?: NetChannel): NetMessage<T>;
|
|
123
|
+
interface NetRoomOptions<M, S> {
|
|
124
|
+
/** Имя этого игрока и его данные игры. */
|
|
125
|
+
name: string;
|
|
126
|
+
meta: M;
|
|
127
|
+
/** Хост: снимок игры для опоздавшего (вызывается на каждый HELLO). */
|
|
128
|
+
onWelcome?(userId: string): S | null;
|
|
129
|
+
/** Гость: хост прислал снимок (первый вход и каждый вход к новому хосту). */
|
|
130
|
+
onWelcomed?(state: S | null): void;
|
|
131
|
+
/** Состав сменился (вошёл, ушёл, сменил данные). */
|
|
132
|
+
onRoster?(members: readonly NetMember<M>[]): void;
|
|
133
|
+
/** Игрок вошёл (у всех, кроме него самого). */
|
|
134
|
+
onJoin?(member: NetMember<M>): void;
|
|
135
|
+
/** Игрок ушёл: его сущности пора убрать. */
|
|
136
|
+
onLeave?(userId: string): void;
|
|
137
|
+
/** Этот игрок стал хостом или перестал им быть. */
|
|
138
|
+
onHostChanged?(isHost: boolean, hostId: string): void;
|
|
139
|
+
/** Комната закрылась или игрок из неё ушёл. */
|
|
140
|
+
onClosed?(reason: string): void;
|
|
141
|
+
/** Часы для `watchHost`, мс (тесты). По умолчанию `Date.now`. */
|
|
142
|
+
now?(): number;
|
|
143
|
+
}
|
|
144
|
+
declare class NetRoom<M = unknown, S = unknown> {
|
|
145
|
+
private readonly transport;
|
|
146
|
+
private readonly opts;
|
|
147
|
+
readonly selfId: string;
|
|
148
|
+
private readonly members;
|
|
149
|
+
private readonly handlers;
|
|
150
|
+
private readonly offs;
|
|
151
|
+
private welcomed;
|
|
152
|
+
private successor;
|
|
153
|
+
private closedFlag;
|
|
154
|
+
/** Связь с этим хостом была: без неё тишина значит «ещё не связались», а не «хост пропал». */
|
|
155
|
+
private hostLinkSeen;
|
|
156
|
+
/** С какого момента нет связи с хостом (0: связь есть). */
|
|
157
|
+
private hostLostAt;
|
|
158
|
+
private nextClaimAt;
|
|
159
|
+
private claimRetry;
|
|
160
|
+
constructor(transport: NetTransport, opts: NetRoomOptions<M, S>);
|
|
161
|
+
private now;
|
|
162
|
+
get isHost(): boolean;
|
|
163
|
+
get hostId(): string;
|
|
164
|
+
/** Гость получил снимок хоста (у хоста всегда true). */
|
|
165
|
+
get ready(): boolean;
|
|
166
|
+
get closed(): boolean;
|
|
167
|
+
/** Состав комнаты, этот игрок тоже. */
|
|
168
|
+
roster(): NetMember<M>[];
|
|
169
|
+
member(userId: string): NetMember<M> | undefined;
|
|
170
|
+
/** Сменить свои данные (облик): дойдут до всех. */
|
|
171
|
+
setMeta(meta: M): void;
|
|
172
|
+
/** Слушать сообщение игры. Возвращает отписку. */
|
|
173
|
+
on<T>(msg: NetMessage<T>, fn: (value: T, from: string) => void): () => void;
|
|
174
|
+
/** Всем остальным (в звезде гость шлёт хосту, тот пересылает). */
|
|
175
|
+
broadcast<T>(msg: NetMessage<T>, value: T): void;
|
|
176
|
+
/** Одному игроку (в звезде гость гостю: через хоста). */
|
|
177
|
+
sendTo<T>(userId: string, msg: NetMessage<T>, value: T): void;
|
|
178
|
+
/** Раз в несколько секунд у хоста: выбрать преемника по скорости связи. */
|
|
179
|
+
pickSuccessor(): void;
|
|
180
|
+
/** Преемник, которого назвал хост (у гостя: из состава). */
|
|
181
|
+
get successorId(): string | null;
|
|
182
|
+
/**
|
|
183
|
+
* У гостя каждый кадр (дёшево): связь с хостом пропала и не вернулась → попросить роль хоста.
|
|
184
|
+
* Хост, ушедший как положено, передаёт роль сам (`hostChanged` придёт раньше); это путь для хоста,
|
|
185
|
+
* который просто исчез. Первым просит преемник, остальные позже и по очереди, сервер пустит одного.
|
|
186
|
+
*/
|
|
187
|
+
watchHost(): void;
|
|
188
|
+
/** Место в очереди на роль хоста среди гостей, кроме преемника. */
|
|
189
|
+
private claimRank;
|
|
190
|
+
dispose(): void;
|
|
191
|
+
private broadcastRaw;
|
|
192
|
+
private receive;
|
|
193
|
+
/** Хост: гость прислал «всем» или «одному». */
|
|
194
|
+
private relay;
|
|
195
|
+
/** Канал пересылки: частые позы (свой тип игры с fast) пересылаются быстрым, остальное надёжным. */
|
|
196
|
+
private channelOf;
|
|
197
|
+
/** Типы игры, которые идут быстрым каналом (их пересылка тоже быстрая). */
|
|
198
|
+
readonly fastTypes: Set<number>;
|
|
199
|
+
private peerOpen;
|
|
200
|
+
private sendHello;
|
|
201
|
+
private onHello;
|
|
202
|
+
private onWelcome;
|
|
203
|
+
private onRoster;
|
|
204
|
+
private applyRoster;
|
|
205
|
+
private broadcastRoster;
|
|
206
|
+
private dropMember;
|
|
207
|
+
private hostChanged;
|
|
208
|
+
private close;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Смешать два снимка позы: `out` = a + (b − a)·t. */
|
|
212
|
+
type PoseLerp<P> = (a: P, b: P, t: number) => P;
|
|
213
|
+
/** Угол a → b по кратчайшей дуге. */
|
|
214
|
+
declare function lerpAngle(a: number, b: number, t: number): number;
|
|
215
|
+
declare function lerp(a: number, b: number, t: number): number;
|
|
216
|
+
declare class SnapshotBuffer<P> {
|
|
217
|
+
private readonly mix;
|
|
218
|
+
private readonly delay;
|
|
219
|
+
private readonly capacity;
|
|
220
|
+
private readonly samples;
|
|
221
|
+
/**
|
|
222
|
+
* `delay`: на сколько секунд в прошлом показывать (две-три паузы между снимками);
|
|
223
|
+
* `hold`: сколько секунд держать последнюю позу, когда снимки кончились.
|
|
224
|
+
*/
|
|
225
|
+
constructor(mix: PoseLerp<P>, delay?: number, capacity?: number);
|
|
226
|
+
push(t: number, pose: P): void;
|
|
227
|
+
/** Последняя пришедшая поза (без сглаживания). */
|
|
228
|
+
latest(): P | null;
|
|
229
|
+
get size(): number;
|
|
230
|
+
/** Поза на момент `now − delay`. null: снимков ещё нет. */
|
|
231
|
+
sample(now: number): P | null;
|
|
232
|
+
clear(): void;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Что репликации нужно от комнаты (`NetRoom` подходит). */
|
|
236
|
+
interface ReplicaRoom {
|
|
237
|
+
readonly selfId: string;
|
|
238
|
+
on<T>(msg: NetMessage<T>, fn: (value: T, from: string) => void): () => void;
|
|
239
|
+
broadcast<T>(msg: NetMessage<T>, value: T): void;
|
|
240
|
+
sendTo<T>(userId: string, msg: NetMessage<T>, value: T): void;
|
|
241
|
+
}
|
|
242
|
+
interface ReplicaOptions<P, D> {
|
|
243
|
+
/** Первый из трёх подряд типов сообщений игры (появление, поза, исчезновение). */
|
|
244
|
+
baseType: number;
|
|
245
|
+
writePose(w: ByteWriter, pose: P): void;
|
|
246
|
+
readPose(r: ByteReader): P;
|
|
247
|
+
lerp: PoseLerp<P>;
|
|
248
|
+
/** Поз в секунду от владельца (по умолчанию 15). */
|
|
249
|
+
rate?: number;
|
|
250
|
+
/** Задержка сглаживания у копий, с (по умолчанию две паузы между позами). */
|
|
251
|
+
delay?: number;
|
|
252
|
+
/** Часы, секунды. */
|
|
253
|
+
now(): number;
|
|
254
|
+
/** Копия появилась (у не-владельцев). `data`: что владелец сказал о ней (вид, цвет). */
|
|
255
|
+
onSpawn?(id: string, owner: string, kind: string, data: D): void;
|
|
256
|
+
/** Копия исчезла. */
|
|
257
|
+
onDespawn?(id: string, owner: string): void;
|
|
258
|
+
/** Владелец сменил данные (`update`): у копий. */
|
|
259
|
+
onData?(id: string, data: D): void;
|
|
260
|
+
}
|
|
261
|
+
interface Replica<P, D> {
|
|
262
|
+
readonly id: string;
|
|
263
|
+
readonly owner: string;
|
|
264
|
+
readonly kind: string;
|
|
265
|
+
data: D;
|
|
266
|
+
readonly buffer: SnapshotBuffer<P>;
|
|
267
|
+
}
|
|
268
|
+
declare class Replicator<P, D = unknown> {
|
|
269
|
+
private readonly room;
|
|
270
|
+
private readonly opts;
|
|
271
|
+
private readonly owned;
|
|
272
|
+
private readonly replicas;
|
|
273
|
+
private nextN;
|
|
274
|
+
private lastSend;
|
|
275
|
+
private readonly spawnMsg;
|
|
276
|
+
private readonly poseMsg;
|
|
277
|
+
private readonly goneMsg;
|
|
278
|
+
private readonly offs;
|
|
279
|
+
private readonly interval;
|
|
280
|
+
private readonly delay;
|
|
281
|
+
constructor(room: ReplicaRoom, opts: ReplicaOptions<P, D>);
|
|
282
|
+
/** Начать владеть сущностью: она появится у всех. Возвращает её сетевой id. */
|
|
283
|
+
own(kind: string, data: D, pose: () => P): string;
|
|
284
|
+
/** Сменить данные своей сущности (цвет, разбита, сирена). */
|
|
285
|
+
update(id: string, data: D): void;
|
|
286
|
+
/** Перестать владеть: сущность исчезнет у всех. */
|
|
287
|
+
disown(id: string): void;
|
|
288
|
+
isMine(id: string): boolean;
|
|
289
|
+
/** Раз в кадр у всех: позы своих сущностей уходят не чаще `rate`. */
|
|
290
|
+
tick(): void;
|
|
291
|
+
/** Вошёл игрок: показать ему свои сущности. */
|
|
292
|
+
onJoin(userId: string): void;
|
|
293
|
+
/** Ушёл игрок: его копии исчезают. */
|
|
294
|
+
onLeave(userId: string): void;
|
|
295
|
+
/** Сглаженная поза копии на сейчас. */
|
|
296
|
+
sample(id: string): P | null;
|
|
297
|
+
replica(id: string): Replica<P, D> | undefined;
|
|
298
|
+
list(): Replica<P, D>[];
|
|
299
|
+
dispose(): void;
|
|
300
|
+
private numberOf;
|
|
301
|
+
private remoteSpawn;
|
|
302
|
+
private remotePoses;
|
|
303
|
+
private remoteGone;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
interface MemoryTransport extends NetTransport {
|
|
307
|
+
/** Сколько сообщений этот игрок отправил (для тестов трафика). */
|
|
308
|
+
readonly sent: number;
|
|
309
|
+
}
|
|
310
|
+
interface Packet {
|
|
311
|
+
to: string;
|
|
312
|
+
from: string;
|
|
313
|
+
channel: NetChannel;
|
|
314
|
+
data: Uint8Array;
|
|
315
|
+
}
|
|
316
|
+
declare class MemoryHub {
|
|
317
|
+
readonly topology: "Host" | "Mesh";
|
|
318
|
+
private readonly peers;
|
|
319
|
+
private queue;
|
|
320
|
+
hostId: string;
|
|
321
|
+
constructor(topology?: "Host" | "Mesh");
|
|
322
|
+
/** Войти в комнату. Первый вошедший: хост. */
|
|
323
|
+
join(userId: string): MemoryTransport;
|
|
324
|
+
/** Уйти как положено (выход из комнаты). Уходит хост: хостом становится `next` (или первый оставшийся). */
|
|
325
|
+
leave(userId: string, next?: string): void;
|
|
326
|
+
/**
|
|
327
|
+
* Пропасть без выхода (вкладка упала, сеть оборвалась): связи рвутся, но сервер ещё считает игрока
|
|
328
|
+
* в комнате, хоста никто не назначает. Роль хоста берут `claimHost`.
|
|
329
|
+
*/
|
|
330
|
+
vanish(userId: string): void;
|
|
331
|
+
/** Сколько раз просили роль хоста (тесты). */
|
|
332
|
+
claims: number;
|
|
333
|
+
/** Просьба роли хоста: даётся, только если хост пропал (`vanish`). */
|
|
334
|
+
claim(by: string): boolean;
|
|
335
|
+
private readonly gone;
|
|
336
|
+
private promote;
|
|
337
|
+
/** Доставить всё, что накопилось (и то, что появилось по ходу). */
|
|
338
|
+
flush(limit?: number): void;
|
|
339
|
+
private readonly jobs;
|
|
340
|
+
private later;
|
|
341
|
+
linked(a: string, b: string): boolean;
|
|
342
|
+
linksOf(userId: string): string[];
|
|
343
|
+
post(p: Packet): void;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export { ByteReader, ByteWriter, MemoryHub, type MemoryTransport, type NetChannel, type NetMember, type NetMessage, NetRoom, type NetRoomOptions, type NetTransport, type NetTransportEvents, type PoseLerp, type Replica, type ReplicaOptions, type ReplicaRoom, Replicator, SnapshotBuffer, decodeJson, decodeJsonSync, defineBinary, defineJson, encodeJson, encodeJsonSync, lerp, lerpAngle };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
declare class ByteWriter {
|
|
2
|
+
private buf;
|
|
3
|
+
private view;
|
|
4
|
+
private at;
|
|
5
|
+
constructor(initial?: number);
|
|
6
|
+
private ensure;
|
|
7
|
+
u8(v: number): this;
|
|
8
|
+
u16(v: number): this;
|
|
9
|
+
i16(v: number): this;
|
|
10
|
+
u32(v: number): this;
|
|
11
|
+
i32(v: number): this;
|
|
12
|
+
f32(v: number): this;
|
|
13
|
+
bytes(b: Uint8Array): this;
|
|
14
|
+
/** Угол (радианы) в i16: шаг ~0.0001 рад, глазу неотличимо. */
|
|
15
|
+
angle(rad: number): this;
|
|
16
|
+
/** Строка UTF-8 с длиной u16 впереди. */
|
|
17
|
+
str(s: string): this;
|
|
18
|
+
/** Число в i16 с шагом `step` (шаг 1/32 держит ±1024): вдвое меньше f32. */
|
|
19
|
+
fixed(v: number, step: number): this;
|
|
20
|
+
/** Доля 0..1 в u8. */
|
|
21
|
+
unit(v: number): this;
|
|
22
|
+
get length(): number;
|
|
23
|
+
finish(): Uint8Array;
|
|
24
|
+
}
|
|
25
|
+
declare class ByteReader {
|
|
26
|
+
private readonly buf;
|
|
27
|
+
private readonly view;
|
|
28
|
+
private at;
|
|
29
|
+
constructor(buf: Uint8Array);
|
|
30
|
+
get left(): number;
|
|
31
|
+
private need;
|
|
32
|
+
u8(): number;
|
|
33
|
+
u16(): number;
|
|
34
|
+
i16(): number;
|
|
35
|
+
u32(): number;
|
|
36
|
+
i32(): number;
|
|
37
|
+
f32(): number;
|
|
38
|
+
angle(): number;
|
|
39
|
+
str(): string;
|
|
40
|
+
fixed(step: number): number;
|
|
41
|
+
unit(): number;
|
|
42
|
+
rest(): Uint8Array;
|
|
43
|
+
}
|
|
44
|
+
/** JSON-сообщение: [тип][флаги][тело]. Большое тело сжимается, если среда умеет. */
|
|
45
|
+
declare function encodeJson(type: number, value: unknown): Promise<Uint8Array>;
|
|
46
|
+
/** То же без сжатия и синхронно: для мелких частых сообщений. */
|
|
47
|
+
declare function encodeJsonSync(type: number, value: unknown): Uint8Array;
|
|
48
|
+
/** Тело JSON-сообщения (без байта типа). null: битое. */
|
|
49
|
+
declare function decodeJson<T>(msg: Uint8Array): Promise<T | null>;
|
|
50
|
+
/** Тело JSON-сообщения синхронно; сжатое или битое: null. */
|
|
51
|
+
declare function decodeJsonSync<T>(msg: Uint8Array): T | null;
|
|
52
|
+
|
|
53
|
+
type NetChannel = "rel" | "fast";
|
|
54
|
+
/** События транспорта, которые слушает комната (подмножество событий `RealtimeSession`). */
|
|
55
|
+
interface NetTransportEvents {
|
|
56
|
+
message: {
|
|
57
|
+
from: string;
|
|
58
|
+
channel: NetChannel;
|
|
59
|
+
data: Uint8Array;
|
|
60
|
+
};
|
|
61
|
+
peerOpen: {
|
|
62
|
+
peerId: string;
|
|
63
|
+
};
|
|
64
|
+
peerClose: {
|
|
65
|
+
peerId: string;
|
|
66
|
+
reason: string;
|
|
67
|
+
};
|
|
68
|
+
memberLeft: {
|
|
69
|
+
userId: string;
|
|
70
|
+
kind: string;
|
|
71
|
+
by?: string;
|
|
72
|
+
};
|
|
73
|
+
hostChanged: {
|
|
74
|
+
hostId: string;
|
|
75
|
+
previousHostId: string | null;
|
|
76
|
+
};
|
|
77
|
+
left: Record<string, never>;
|
|
78
|
+
removed: {
|
|
79
|
+
reason: string;
|
|
80
|
+
};
|
|
81
|
+
roomClosed: Record<string, never>;
|
|
82
|
+
}
|
|
83
|
+
/** Транспорт пиров комнаты. */
|
|
84
|
+
interface NetTransport {
|
|
85
|
+
readonly selfId: string;
|
|
86
|
+
readonly hostId: string;
|
|
87
|
+
readonly topology: "Host" | "Mesh";
|
|
88
|
+
openPeers(): string[];
|
|
89
|
+
isOpen(peerId: string): boolean;
|
|
90
|
+
send(peerId: string, channel: NetChannel, data: Uint8Array): boolean;
|
|
91
|
+
broadcast(channel: NetChannel, data: Uint8Array, except?: string): number;
|
|
92
|
+
on<K extends keyof NetTransportEvents>(event: K, fn: (e: NetTransportEvents[K]) => void): () => void;
|
|
93
|
+
/** Кто станет хостом, если этот уйдёт (транспорт держит к нему запасную связь). */
|
|
94
|
+
setSuccessor?(userId: string | null): void;
|
|
95
|
+
/** Задержка связи с пиром, мс. */
|
|
96
|
+
linkStats?(peerId: string): {
|
|
97
|
+
rttMs: number;
|
|
98
|
+
} | null;
|
|
99
|
+
/**
|
|
100
|
+
* Перехватить роль хоста, который замолчал. Решает транспорт (сервер пускает одного и только когда
|
|
101
|
+
* хост молчит дольше своего порога); удалось: придёт `hostChanged`.
|
|
102
|
+
*/
|
|
103
|
+
claimHost?(): Promise<unknown> | void;
|
|
104
|
+
}
|
|
105
|
+
/** Игрок в составе комнаты. */
|
|
106
|
+
interface NetMember<M = unknown> {
|
|
107
|
+
userId: string;
|
|
108
|
+
name: string;
|
|
109
|
+
/** Данные игры о игроке (облик, цвет): их задаёт сам игрок (`setMeta`). */
|
|
110
|
+
meta: M;
|
|
111
|
+
}
|
|
112
|
+
/** Сообщение игры: тип, канал, как писать и читать. */
|
|
113
|
+
interface NetMessage<T> {
|
|
114
|
+
readonly type: number;
|
|
115
|
+
readonly channel: NetChannel;
|
|
116
|
+
encode(value: T): Uint8Array;
|
|
117
|
+
decode(data: Uint8Array): T | null;
|
|
118
|
+
}
|
|
119
|
+
/** Редкое сообщение JSON (по умолчанию надёжный канал). */
|
|
120
|
+
declare function defineJson<T>(type: number, channel?: NetChannel): NetMessage<T>;
|
|
121
|
+
/** Частое двоичное сообщение (по умолчанию быстрый канал). */
|
|
122
|
+
declare function defineBinary<T>(type: number, write: (w: ByteWriter, value: T) => void, read: (r: ByteReader) => T, channel?: NetChannel): NetMessage<T>;
|
|
123
|
+
interface NetRoomOptions<M, S> {
|
|
124
|
+
/** Имя этого игрока и его данные игры. */
|
|
125
|
+
name: string;
|
|
126
|
+
meta: M;
|
|
127
|
+
/** Хост: снимок игры для опоздавшего (вызывается на каждый HELLO). */
|
|
128
|
+
onWelcome?(userId: string): S | null;
|
|
129
|
+
/** Гость: хост прислал снимок (первый вход и каждый вход к новому хосту). */
|
|
130
|
+
onWelcomed?(state: S | null): void;
|
|
131
|
+
/** Состав сменился (вошёл, ушёл, сменил данные). */
|
|
132
|
+
onRoster?(members: readonly NetMember<M>[]): void;
|
|
133
|
+
/** Игрок вошёл (у всех, кроме него самого). */
|
|
134
|
+
onJoin?(member: NetMember<M>): void;
|
|
135
|
+
/** Игрок ушёл: его сущности пора убрать. */
|
|
136
|
+
onLeave?(userId: string): void;
|
|
137
|
+
/** Этот игрок стал хостом или перестал им быть. */
|
|
138
|
+
onHostChanged?(isHost: boolean, hostId: string): void;
|
|
139
|
+
/** Комната закрылась или игрок из неё ушёл. */
|
|
140
|
+
onClosed?(reason: string): void;
|
|
141
|
+
/** Часы для `watchHost`, мс (тесты). По умолчанию `Date.now`. */
|
|
142
|
+
now?(): number;
|
|
143
|
+
}
|
|
144
|
+
declare class NetRoom<M = unknown, S = unknown> {
|
|
145
|
+
private readonly transport;
|
|
146
|
+
private readonly opts;
|
|
147
|
+
readonly selfId: string;
|
|
148
|
+
private readonly members;
|
|
149
|
+
private readonly handlers;
|
|
150
|
+
private readonly offs;
|
|
151
|
+
private welcomed;
|
|
152
|
+
private successor;
|
|
153
|
+
private closedFlag;
|
|
154
|
+
/** Связь с этим хостом была: без неё тишина значит «ещё не связались», а не «хост пропал». */
|
|
155
|
+
private hostLinkSeen;
|
|
156
|
+
/** С какого момента нет связи с хостом (0: связь есть). */
|
|
157
|
+
private hostLostAt;
|
|
158
|
+
private nextClaimAt;
|
|
159
|
+
private claimRetry;
|
|
160
|
+
constructor(transport: NetTransport, opts: NetRoomOptions<M, S>);
|
|
161
|
+
private now;
|
|
162
|
+
get isHost(): boolean;
|
|
163
|
+
get hostId(): string;
|
|
164
|
+
/** Гость получил снимок хоста (у хоста всегда true). */
|
|
165
|
+
get ready(): boolean;
|
|
166
|
+
get closed(): boolean;
|
|
167
|
+
/** Состав комнаты, этот игрок тоже. */
|
|
168
|
+
roster(): NetMember<M>[];
|
|
169
|
+
member(userId: string): NetMember<M> | undefined;
|
|
170
|
+
/** Сменить свои данные (облик): дойдут до всех. */
|
|
171
|
+
setMeta(meta: M): void;
|
|
172
|
+
/** Слушать сообщение игры. Возвращает отписку. */
|
|
173
|
+
on<T>(msg: NetMessage<T>, fn: (value: T, from: string) => void): () => void;
|
|
174
|
+
/** Всем остальным (в звезде гость шлёт хосту, тот пересылает). */
|
|
175
|
+
broadcast<T>(msg: NetMessage<T>, value: T): void;
|
|
176
|
+
/** Одному игроку (в звезде гость гостю: через хоста). */
|
|
177
|
+
sendTo<T>(userId: string, msg: NetMessage<T>, value: T): void;
|
|
178
|
+
/** Раз в несколько секунд у хоста: выбрать преемника по скорости связи. */
|
|
179
|
+
pickSuccessor(): void;
|
|
180
|
+
/** Преемник, которого назвал хост (у гостя: из состава). */
|
|
181
|
+
get successorId(): string | null;
|
|
182
|
+
/**
|
|
183
|
+
* У гостя каждый кадр (дёшево): связь с хостом пропала и не вернулась → попросить роль хоста.
|
|
184
|
+
* Хост, ушедший как положено, передаёт роль сам (`hostChanged` придёт раньше); это путь для хоста,
|
|
185
|
+
* который просто исчез. Первым просит преемник, остальные позже и по очереди, сервер пустит одного.
|
|
186
|
+
*/
|
|
187
|
+
watchHost(): void;
|
|
188
|
+
/** Место в очереди на роль хоста среди гостей, кроме преемника. */
|
|
189
|
+
private claimRank;
|
|
190
|
+
dispose(): void;
|
|
191
|
+
private broadcastRaw;
|
|
192
|
+
private receive;
|
|
193
|
+
/** Хост: гость прислал «всем» или «одному». */
|
|
194
|
+
private relay;
|
|
195
|
+
/** Канал пересылки: частые позы (свой тип игры с fast) пересылаются быстрым, остальное надёжным. */
|
|
196
|
+
private channelOf;
|
|
197
|
+
/** Типы игры, которые идут быстрым каналом (их пересылка тоже быстрая). */
|
|
198
|
+
readonly fastTypes: Set<number>;
|
|
199
|
+
private peerOpen;
|
|
200
|
+
private sendHello;
|
|
201
|
+
private onHello;
|
|
202
|
+
private onWelcome;
|
|
203
|
+
private onRoster;
|
|
204
|
+
private applyRoster;
|
|
205
|
+
private broadcastRoster;
|
|
206
|
+
private dropMember;
|
|
207
|
+
private hostChanged;
|
|
208
|
+
private close;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Смешать два снимка позы: `out` = a + (b − a)·t. */
|
|
212
|
+
type PoseLerp<P> = (a: P, b: P, t: number) => P;
|
|
213
|
+
/** Угол a → b по кратчайшей дуге. */
|
|
214
|
+
declare function lerpAngle(a: number, b: number, t: number): number;
|
|
215
|
+
declare function lerp(a: number, b: number, t: number): number;
|
|
216
|
+
declare class SnapshotBuffer<P> {
|
|
217
|
+
private readonly mix;
|
|
218
|
+
private readonly delay;
|
|
219
|
+
private readonly capacity;
|
|
220
|
+
private readonly samples;
|
|
221
|
+
/**
|
|
222
|
+
* `delay`: на сколько секунд в прошлом показывать (две-три паузы между снимками);
|
|
223
|
+
* `hold`: сколько секунд держать последнюю позу, когда снимки кончились.
|
|
224
|
+
*/
|
|
225
|
+
constructor(mix: PoseLerp<P>, delay?: number, capacity?: number);
|
|
226
|
+
push(t: number, pose: P): void;
|
|
227
|
+
/** Последняя пришедшая поза (без сглаживания). */
|
|
228
|
+
latest(): P | null;
|
|
229
|
+
get size(): number;
|
|
230
|
+
/** Поза на момент `now − delay`. null: снимков ещё нет. */
|
|
231
|
+
sample(now: number): P | null;
|
|
232
|
+
clear(): void;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Что репликации нужно от комнаты (`NetRoom` подходит). */
|
|
236
|
+
interface ReplicaRoom {
|
|
237
|
+
readonly selfId: string;
|
|
238
|
+
on<T>(msg: NetMessage<T>, fn: (value: T, from: string) => void): () => void;
|
|
239
|
+
broadcast<T>(msg: NetMessage<T>, value: T): void;
|
|
240
|
+
sendTo<T>(userId: string, msg: NetMessage<T>, value: T): void;
|
|
241
|
+
}
|
|
242
|
+
interface ReplicaOptions<P, D> {
|
|
243
|
+
/** Первый из трёх подряд типов сообщений игры (появление, поза, исчезновение). */
|
|
244
|
+
baseType: number;
|
|
245
|
+
writePose(w: ByteWriter, pose: P): void;
|
|
246
|
+
readPose(r: ByteReader): P;
|
|
247
|
+
lerp: PoseLerp<P>;
|
|
248
|
+
/** Поз в секунду от владельца (по умолчанию 15). */
|
|
249
|
+
rate?: number;
|
|
250
|
+
/** Задержка сглаживания у копий, с (по умолчанию две паузы между позами). */
|
|
251
|
+
delay?: number;
|
|
252
|
+
/** Часы, секунды. */
|
|
253
|
+
now(): number;
|
|
254
|
+
/** Копия появилась (у не-владельцев). `data`: что владелец сказал о ней (вид, цвет). */
|
|
255
|
+
onSpawn?(id: string, owner: string, kind: string, data: D): void;
|
|
256
|
+
/** Копия исчезла. */
|
|
257
|
+
onDespawn?(id: string, owner: string): void;
|
|
258
|
+
/** Владелец сменил данные (`update`): у копий. */
|
|
259
|
+
onData?(id: string, data: D): void;
|
|
260
|
+
}
|
|
261
|
+
interface Replica<P, D> {
|
|
262
|
+
readonly id: string;
|
|
263
|
+
readonly owner: string;
|
|
264
|
+
readonly kind: string;
|
|
265
|
+
data: D;
|
|
266
|
+
readonly buffer: SnapshotBuffer<P>;
|
|
267
|
+
}
|
|
268
|
+
declare class Replicator<P, D = unknown> {
|
|
269
|
+
private readonly room;
|
|
270
|
+
private readonly opts;
|
|
271
|
+
private readonly owned;
|
|
272
|
+
private readonly replicas;
|
|
273
|
+
private nextN;
|
|
274
|
+
private lastSend;
|
|
275
|
+
private readonly spawnMsg;
|
|
276
|
+
private readonly poseMsg;
|
|
277
|
+
private readonly goneMsg;
|
|
278
|
+
private readonly offs;
|
|
279
|
+
private readonly interval;
|
|
280
|
+
private readonly delay;
|
|
281
|
+
constructor(room: ReplicaRoom, opts: ReplicaOptions<P, D>);
|
|
282
|
+
/** Начать владеть сущностью: она появится у всех. Возвращает её сетевой id. */
|
|
283
|
+
own(kind: string, data: D, pose: () => P): string;
|
|
284
|
+
/** Сменить данные своей сущности (цвет, разбита, сирена). */
|
|
285
|
+
update(id: string, data: D): void;
|
|
286
|
+
/** Перестать владеть: сущность исчезнет у всех. */
|
|
287
|
+
disown(id: string): void;
|
|
288
|
+
isMine(id: string): boolean;
|
|
289
|
+
/** Раз в кадр у всех: позы своих сущностей уходят не чаще `rate`. */
|
|
290
|
+
tick(): void;
|
|
291
|
+
/** Вошёл игрок: показать ему свои сущности. */
|
|
292
|
+
onJoin(userId: string): void;
|
|
293
|
+
/** Ушёл игрок: его копии исчезают. */
|
|
294
|
+
onLeave(userId: string): void;
|
|
295
|
+
/** Сглаженная поза копии на сейчас. */
|
|
296
|
+
sample(id: string): P | null;
|
|
297
|
+
replica(id: string): Replica<P, D> | undefined;
|
|
298
|
+
list(): Replica<P, D>[];
|
|
299
|
+
dispose(): void;
|
|
300
|
+
private numberOf;
|
|
301
|
+
private remoteSpawn;
|
|
302
|
+
private remotePoses;
|
|
303
|
+
private remoteGone;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
interface MemoryTransport extends NetTransport {
|
|
307
|
+
/** Сколько сообщений этот игрок отправил (для тестов трафика). */
|
|
308
|
+
readonly sent: number;
|
|
309
|
+
}
|
|
310
|
+
interface Packet {
|
|
311
|
+
to: string;
|
|
312
|
+
from: string;
|
|
313
|
+
channel: NetChannel;
|
|
314
|
+
data: Uint8Array;
|
|
315
|
+
}
|
|
316
|
+
declare class MemoryHub {
|
|
317
|
+
readonly topology: "Host" | "Mesh";
|
|
318
|
+
private readonly peers;
|
|
319
|
+
private queue;
|
|
320
|
+
hostId: string;
|
|
321
|
+
constructor(topology?: "Host" | "Mesh");
|
|
322
|
+
/** Войти в комнату. Первый вошедший: хост. */
|
|
323
|
+
join(userId: string): MemoryTransport;
|
|
324
|
+
/** Уйти как положено (выход из комнаты). Уходит хост: хостом становится `next` (или первый оставшийся). */
|
|
325
|
+
leave(userId: string, next?: string): void;
|
|
326
|
+
/**
|
|
327
|
+
* Пропасть без выхода (вкладка упала, сеть оборвалась): связи рвутся, но сервер ещё считает игрока
|
|
328
|
+
* в комнате, хоста никто не назначает. Роль хоста берут `claimHost`.
|
|
329
|
+
*/
|
|
330
|
+
vanish(userId: string): void;
|
|
331
|
+
/** Сколько раз просили роль хоста (тесты). */
|
|
332
|
+
claims: number;
|
|
333
|
+
/** Просьба роли хоста: даётся, только если хост пропал (`vanish`). */
|
|
334
|
+
claim(by: string): boolean;
|
|
335
|
+
private readonly gone;
|
|
336
|
+
private promote;
|
|
337
|
+
/** Доставить всё, что накопилось (и то, что появилось по ходу). */
|
|
338
|
+
flush(limit?: number): void;
|
|
339
|
+
private readonly jobs;
|
|
340
|
+
private later;
|
|
341
|
+
linked(a: string, b: string): boolean;
|
|
342
|
+
linksOf(userId: string): string[];
|
|
343
|
+
post(p: Packet): void;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export { ByteReader, ByteWriter, MemoryHub, type MemoryTransport, type NetChannel, type NetMember, type NetMessage, NetRoom, type NetRoomOptions, type NetTransport, type NetTransportEvents, type PoseLerp, type Replica, type ReplicaOptions, type ReplicaRoom, Replicator, SnapshotBuffer, decodeJson, decodeJsonSync, defineBinary, defineJson, encodeJson, encodeJsonSync, lerp, lerpAngle };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var g=new TextEncoder,y=new TextDecoder,h=class{buf;view;at=0;constructor(e=256){this.buf=new Uint8Array(e),this.view=new DataView(this.buf.buffer);}ensure(e){if(this.at+e<=this.buf.length)return;let t=this.buf.length*2;for(;t<this.at+e;)t*=2;let s=new Uint8Array(t);s.set(this.buf.subarray(0,this.at)),this.buf=s,this.view=new DataView(s.buffer);}u8(e){return this.ensure(1),this.view.setUint8(this.at,e),this.at+=1,this}u16(e){return this.ensure(2),this.view.setUint16(this.at,e),this.at+=2,this}i16(e){return this.ensure(2),this.view.setInt16(this.at,e),this.at+=2,this}u32(e){return this.ensure(4),this.view.setUint32(this.at,e>>>0),this.at+=4,this}i32(e){return this.ensure(4),this.view.setInt32(this.at,e|0),this.at+=4,this}f32(e){return this.ensure(4),this.view.setFloat32(this.at,e),this.at+=4,this}bytes(e){return this.ensure(e.byteLength),this.buf.set(e,this.at),this.at+=e.byteLength,this}angle(e){let t=e%(Math.PI*2);return t>Math.PI&&(t-=Math.PI*2),t<-Math.PI&&(t+=Math.PI*2),this.i16(Math.round(t*1e4))}str(e){let t=g.encode(e);return this.u16(t.byteLength),this.bytes(t)}fixed(e,t){return this.i16(Math.max(-32768,Math.min(32767,Math.round(e/t))))}unit(e){return this.u8(Math.max(0,Math.min(255,Math.round(e*255))))}get length(){return this.at}finish(){return this.buf.slice(0,this.at)}},l=class{constructor(e){this.buf=e;this.view=new DataView(e.buffer,e.byteOffset,e.byteLength);}buf;view;at=0;get left(){return this.buf.byteLength-this.at}need(e){if(this.at+e>this.buf.byteLength)throw new RangeError("Truncated message")}u8(){return this.need(1),this.view.getUint8(this.at++)}u16(){this.need(2);let e=this.view.getUint16(this.at);return this.at+=2,e}i16(){this.need(2);let e=this.view.getInt16(this.at);return this.at+=2,e}u32(){this.need(4);let e=this.view.getUint32(this.at);return this.at+=4,e}i32(){this.need(4);let e=this.view.getInt32(this.at);return this.at+=4,e}f32(){this.need(4);let e=this.view.getFloat32(this.at);return this.at+=4,e}angle(){return this.i16()/1e4}str(){let e=this.u16();this.need(e);let t=y.decode(this.buf.subarray(this.at,this.at+e));return this.at+=e,t}fixed(e){return this.i16()*e}unit(){return this.u8()/255}rest(){let e=this.buf.subarray(this.at);return this.at=this.buf.byteLength,e}},U=2048;async function N(i,e){let t=new Blob([i]).stream().pipeThrough(e);return new Uint8Array(await new Response(t).arrayBuffer())}var H=typeof CompressionStream<"u";async function _(i,e){let t=g.encode(JSON.stringify(e)),s=0;H&&t.byteLength>U&&(t=await N(t,new CompressionStream("deflate-raw")),s|=1);let r=new Uint8Array(t.byteLength+2);return r[0]=i,r[1]=s,r.set(t,2),r}function d(i,e){let t=g.encode(JSON.stringify(e)),s=new Uint8Array(t.byteLength+2);return s[0]=i,s[1]=0,s.set(t,2),s}async function D(i){try{let e=i[1]??0,t=i.subarray(2);return e&1&&(t=await N(t,new DecompressionStream("deflate-raw"))),JSON.parse(y.decode(t))}catch{return null}}function u(i){try{return (i[1]??0)&1?null:JSON.parse(y.decode(i.subarray(2)))}catch{return null}}var k=16;function C(i){if(!Number.isInteger(i)||i<k||i>255)throw new RangeError(`netplay: message type ${i} must be 16..255`)}function m(i,e="rel"){return C(i),{type:i,channel:e,encode:t=>d(i,t),decode:t=>u(t)}}function M(i,e,t,s="fast"){return C(i),{type:i,channel:s,encode(r){let n=new h(64).u8(i);return e(n,r),n.finish()},decode(r){try{let n=new l(r);return n.u8(),t(n)}catch{return null}}}}var P=1,A=2,R=3,v=4,x=5,L=6,E=5e3,J=2e4,B=3e3,b=2e3,W=3e4,w=class{constructor(e,t){this.transport=e;this.opts=t;this.selfId=e.selfId,this.members.set(this.selfId,{userId:this.selfId,name:t.name,meta:t.meta}),this.welcomed=this.isHost;let s=e;this.offs.push(s.on("message",r=>this.receive(r.from,r.data)),s.on("peerOpen",r=>this.peerOpen(r.peerId)),s.on("peerClose",r=>{!this.isHost&&r.peerId===s.hostId&&this.hostLinkSeen&&!this.hostLostAt&&(this.hostLostAt=this.now());}),s.on("memberLeft",r=>this.dropMember(r.userId)),s.on("hostChanged",r=>this.hostChanged(r.hostId)),s.on("left",()=>this.close("left")),s.on("removed",r=>this.close(r.reason||"removed")),s.on("roomClosed",()=>this.close("closed"))),!this.isHost&&s.isOpen(s.hostId)&&(this.hostLinkSeen=true,this.sendHello());}transport;opts;selfId;members=new Map;handlers=new Map;offs=[];welcomed;successor=null;closedFlag=false;hostLinkSeen=false;hostLostAt=0;nextClaimAt=0;claimRetry=b;now(){return this.opts.now?this.opts.now():Date.now()}get isHost(){return this.transport.hostId===this.selfId}get hostId(){return this.transport.hostId}get ready(){return this.welcomed}get closed(){return this.closedFlag}roster(){return [...this.members.values()]}member(e){return this.members.get(e)}setMeta(e){let t=this.members.get(this.selfId);t&&(t.meta=e),this.broadcastRaw(d(L,{meta:e}),"rel"),this.opts.onRoster?.(this.roster());}on(e,t){e.channel==="fast"&&this.fastTypes.add(e.type);let s=this.handlers.get(e.type)??new Set,r=(n,o)=>{let a=e.decode(n);a!==null&&t(a,o);};return s.add(r),this.handlers.set(e.type,s),()=>s.delete(r)}broadcast(e,t){e.channel==="fast"&&this.fastTypes.add(e.type),this.broadcastRaw(e.encode(t),e.channel);}sendTo(e,t,s){if(e===this.selfId)return;let r=t.encode(s),n=this.transport;if(n.topology==="Mesh"||this.isHost||e===n.hostId){n.send(e,t.channel,r);return}let o=new h(r.byteLength+32).u8(v).u8(1).str(e);o.bytes(r),n.send(n.hostId,t.channel,o.finish());}pickSuccessor(){if(!this.isHost)return;let e=this.transport,t=null,s=1/0;for(let r of e.openPeers()){if(!this.members.has(r))continue;let n=e.linkStats?.(r)?.rttMs||999;n<s&&(s=n,t=r);}t!==this.successor&&(this.successor=t,e.setSuccessor?.(t),this.broadcastRoster());}get successorId(){return this.successor}watchHost(){if(this.isHost||this.closedFlag||!this.hostLinkSeen)return;let e=this.transport;if(e.isOpen(e.hostId)){this.hostLostAt=0,this.claimRetry=b;return}let t=this.now();this.hostLostAt||(this.hostLostAt=t);let s=this.successor===this.selfId?E:J+this.claimRank()*B;t-this.hostLostAt<s||t<this.nextClaimAt||!e.claimHost||(this.nextClaimAt=t+this.claimRetry,this.claimRetry=Math.min(W,this.claimRetry*2),Promise.resolve(e.claimHost()).catch(()=>{}));}claimRank(){let e=[...this.members.keys()].filter(t=>t!==this.transport.hostId&&t!==this.successor).sort();return Math.max(0,e.indexOf(this.selfId))}dispose(){for(let e of this.offs.splice(0))e();this.handlers.clear();}broadcastRaw(e,t){let s=this.transport;if(s.topology==="Mesh"||this.isHost){s.broadcast(t,e);return}if(!s.isOpen(s.hostId))return;let r=new h(e.byteLength+2).u8(v).u8(0);r.bytes(e),s.send(s.hostId,t,r.finish());}receive(e,t){let s=t[0];if(s!==void 0)switch(s){case v:this.isHost&&this.relay(e,t);return;case x:{try{let r=new l(t);r.u8();let n=r.str();this.receive(n,r.rest());}catch{}return}case P:this.isHost&&this.onHello(e,t);return;case A:e===this.transport.hostId&&this.onWelcome(t);return;case R:e===this.transport.hostId&&this.onRoster(t);return;case L:{let r=u(t),n=this.members.get(e);r&&n&&(n.meta=r.meta,this.opts.onRoster?.(this.roster()));return}default:if(s<k)return;for(let r of this.handlers.get(s)??[])r(t,e);}}relay(e,t){let s,r=null;try{s=new l(t),s.u8(),s.u8()===1&&(r=s.str());}catch{return}let n=s.rest(),o="rel",a=()=>{let p=new h(n.byteLength+32).u8(x).str(e);return p.bytes(n),p.finish()};if(r){r===this.selfId?this.receive(e,n.slice()):this.transport.send(r,this.channelOf(n,o),a());return}let f=a(),O=this.channelOf(n,o);for(let p of this.transport.openPeers())p!==e&&this.transport.send(p,O,f);this.receive(e,n.slice());}channelOf(e,t){let s=e[0]??0;return this.fastTypes.has(s)?"fast":t}fastTypes=new Set;peerOpen(e){this.isHost||e!==this.transport.hostId||(this.hostLinkSeen=true,this.hostLostAt=0,this.welcomed||this.sendHello());}sendHello(){let e=this.members.get(this.selfId),t={name:e?.name??this.opts.name,meta:e?.meta??this.opts.meta};this.transport.send(this.transport.hostId,"rel",d(P,t));}onHello(e,t){let s=u(t);if(!s)return;let r=!this.members.has(e),n={userId:e,name:String(s.name??"").slice(0,40),meta:s.meta};this.members.set(e,n);let o={roster:this.roster(),state:this.opts.onWelcome?.(e)??null,successor:this.successor};this.transport.send(e,"rel",d(A,o)),this.broadcastRoster(),r&&this.opts.onJoin?.(n),this.opts.onRoster?.(this.roster());}onWelcome(e){let t=u(e);t&&(this.applyRoster(t.roster),this.successor=typeof t.successor=="string"?t.successor:null,this.welcomed=true,this.opts.onWelcomed?.(t.state));}onRoster(e){let t=u(e);t&&(this.successor=typeof t.successor=="string"?t.successor:null,this.applyRoster(t.roster));}applyRoster(e){let t=new Set;for(let s of e){if(!s||typeof s.userId!="string"||(t.add(s.userId),s.userId===this.selfId))continue;let r=this.members.has(s.userId),n={userId:s.userId,name:String(s.name??""),meta:s.meta};this.members.set(s.userId,n),r||this.opts.onJoin?.(n);}for(let s of [...this.members.keys()])s!==this.selfId&&!t.has(s)&&this.dropMember(s);this.opts.onRoster?.(this.roster());}broadcastRoster(){this.transport.broadcast("rel",d(R,{roster:this.roster(),successor:this.successor}));}dropMember(e){e===this.selfId||!this.members.delete(e)||(this.opts.onLeave?.(e),this.isHost&&this.broadcastRoster(),this.opts.onRoster?.(this.roster()));}hostChanged(e){let t=e===this.selfId;this.hostLostAt=0,this.nextClaimAt=0,this.claimRetry=b,this.hostLinkSeen=!t&&this.transport.isOpen(e),this.successor=null,t?(this.welcomed=true,this.broadcastRoster()):(this.welcomed=false,this.transport.isOpen(e)&&this.sendHello()),this.opts.onHostChanged?.(t,e);}close(e){this.closedFlag||(this.closedFlag=true,this.opts.onClosed?.(e),this.dispose());}};function K(i,e,t){let s=(e-i)%(Math.PI*2);return s>Math.PI&&(s-=Math.PI*2),s<-Math.PI&&(s+=Math.PI*2),i+s*t}function $(i,e,t){return i+(e-i)*t}var c=class{constructor(e,t=.12,s=32){this.mix=e;this.delay=t;this.capacity=s;}mix;delay;capacity;samples=[];push(e,t){let s=this.samples[this.samples.length-1];s&&e<s.t||(this.samples.push({t:e,pose:t}),this.samples.length>this.capacity&&this.samples.shift());}latest(){return this.samples[this.samples.length-1]?.pose??null}get size(){return this.samples.length}sample(e){let t=this.samples;if(!t.length)return null;let s=e-this.delay,r=t[0];if(s<=r.t)return r.pose;for(let n=t.length-1;n>0;n--){let o=t[n-1],a=t[n];if(s>=o.t){if(s>=a.t)return a.pose;let f=a.t-o.t;return f>0?this.mix(o.pose,a.pose,(s-o.t)/f):a.pose}}return t[t.length-1].pose}clear(){this.samples.length=0;}};var I=class{constructor(e,t){this.room=e;this.opts=t;let s=t.rate??15;this.interval=1/s,this.delay=t.delay??2/s,this.spawnMsg=m(t.baseType),this.poseMsg=M(t.baseType+1,(r,n)=>{r.u16(n.length);for(let o of n)r.u16(o.n),t.writePose(r,o.pose);},r=>{let n=[],o=r.u16();for(let a=0;a<o;a++)n.push({n:r.u16(),pose:t.readPose(r)});return n}),this.goneMsg=m(t.baseType+2),this.offs.push(e.on(this.spawnMsg,(r,n)=>this.remoteSpawn(n,r)),e.on(this.poseMsg,(r,n)=>this.remotePoses(n,r)),e.on(this.goneMsg,(r,n)=>{let o=`${n}/${r.n}`;if(r.update){let a=this.replicas.get(o);a&&r.data!==void 0&&(a.data=r.data,this.opts.onData?.(o,r.data));return}this.remoteGone(o);}));}room;opts;owned=new Map;replicas=new Map;nextN=1;lastSend=-1/0;spawnMsg;poseMsg;goneMsg;offs=[];interval;delay;own(e,t,s){let r=this.nextN++;for(this.nextN>65535&&(this.nextN=1);this.owned.has(r);)r=this.nextN++;return this.owned.set(r,{n:r,kind:e,data:t,pose:s}),this.room.broadcast(this.spawnMsg,{n:r,kind:e,data:t}),`${this.room.selfId}/${r}`}update(e,t){let s=this.owned.get(this.numberOf(e));s&&(s.data=t,this.room.broadcast(this.goneMsg,{n:s.n,data:t,update:true}));}disown(e){let t=this.numberOf(e);this.owned.delete(t)&&this.room.broadcast(this.goneMsg,{n:t});}isMine(e){return e.startsWith(this.room.selfId+"/")}tick(){let e=this.opts.now();if(e-this.lastSend<this.interval||!this.owned.size)return;this.lastSend=e;let t=[];for(let s of this.owned.values())t.push({n:s.n,pose:s.pose()});for(let s=0;s<t.length;s+=24)this.room.broadcast(this.poseMsg,t.slice(s,s+24));}onJoin(e){for(let t of this.owned.values())this.room.sendTo(e,this.spawnMsg,{n:t.n,kind:t.kind,data:t.data});}onLeave(e){for(let t of [...this.replicas.values()])t.owner===e&&this.remoteGone(t.id);}sample(e){return this.replicas.get(e)?.buffer.sample(this.opts.now())??null}replica(e){return this.replicas.get(e)}list(){return [...this.replicas.values()]}dispose(){for(let e of this.offs.splice(0))e();for(let e of [...this.replicas.values()])this.remoteGone(e.id);this.owned.clear();}numberOf(e){let t=e.lastIndexOf("/");return Number(e.slice(t+1))}remoteSpawn(e,t){if(typeof t.n!="number"||typeof t.kind!="string")return;let s=`${e}/${t.n}`,r=this.replicas.get(s);if(r){r.data=t.data,this.opts.onData?.(s,t.data);return}let n={id:s,owner:e,kind:t.kind,data:t.data,buffer:new c(this.opts.lerp,this.delay)};this.replicas.set(s,n),this.opts.onSpawn?.(s,e,t.kind,t.data);}remotePoses(e,t){let s=this.opts.now();for(let r of t)this.replicas.get(`${e}/${r.n}`)?.buffer.push(s,r.pose);}remoteGone(e){let t=this.replicas.get(e);t&&(this.replicas.delete(e),this.opts.onDespawn?.(e,t.owner));}};var T=class{constructor(e="Host"){this.topology=e;}topology;peers=new Map;queue=[];hostId="";join(e){this.hostId||(this.hostId=e);let t=new S(this,e);this.peers.set(e,t);for(let s of this.peers.values())s===t||!this.linked(e,s.selfId)||this.later(()=>{s.emit("peerOpen",{peerId:e}),t.emit("peerOpen",{peerId:s.selfId});});return t}leave(e,t){if(this.peers.delete(e)){for(let s of this.peers.values())s.emit("peerClose",{peerId:e,reason:"left"}),s.emit("memberLeft",{userId:e,kind:"left"});this.hostId===e&&this.promote(t??[...this.peers.keys()][0]??"");}}vanish(e){if(this.peers.delete(e)){this.gone.add(e);for(let t of this.peers.values())t.emit("peerClose",{peerId:e,reason:"lost"});}}claims=0;claim(e){if(this.claims++,!this.gone.has(this.hostId)||!this.peers.has(e))return false;let t=this.hostId;for(let s of this.peers.values())s.emit("memberLeft",{userId:t,kind:"timeout"});return this.promote(e),true}gone=new Set;promote(e){let t=this.hostId;this.hostId=e;let s=this.hostId;for(let r of this.peers.values())r.emit("hostChanged",{hostId:s,previousHostId:t});this.topology==="Host"&&this.later(()=>{let r=this.peers.get(s);for(let n of this.peers.values())n.selfId===s||!r||(n.emit("peerOpen",{peerId:s}),r.emit("peerOpen",{peerId:n.selfId}));});}flush(e=1e4){for(let t=0;t<e&&this.queue.length;t++){let s=this.queue;this.queue=[];for(let n of s)n.to!=="__later__"&&this.peers.get(n.to)?.emit("message",{from:n.from,channel:n.channel,data:n.data});let r=this.jobs.splice(0);for(let n of r)n();}}jobs=[];later(e){this.jobs.push(e),this.queue.push({to:"__later__",from:"",channel:"rel",data:new Uint8Array});}linked(e,t){return e===t||!this.peers.has(e)||!this.peers.has(t)?false:this.topology==="Mesh"||e===this.hostId||t===this.hostId}linksOf(e){return [...this.peers.keys()].filter(t=>this.linked(e,t))}post(e){this.queue.push({...e,data:e.data.slice()});}},S=class{constructor(e,t){this.hub=e;this.selfId=t;}hub;selfId;listeners={};sent=0;get hostId(){return this.hub.hostId}get topology(){return this.hub.topology}openPeers(){return this.hub.linksOf(this.selfId)}isOpen(e){return this.hub.linked(this.selfId,e)}send(e,t,s){return this.isOpen(e)?(this.sent++,this.hub.post({to:e,from:this.selfId,channel:t,data:s}),true):false}broadcast(e,t,s){let r=0;for(let n of this.openPeers())n!==s&&this.send(n,e,t)&&r++;return r}on(e,t){let s=this.listeners,r=s[e]??=new Set;return r.add(t),()=>r.delete(t)}emit(e,t){let s=this.listeners[e];for(let r of [...s??[]])r(t);}linkStats(){return {rttMs:20}}setSuccessor(){}claimHost(){this.hub.claim(this.selfId);}};export{l as ByteReader,h as ByteWriter,T as MemoryHub,w as NetRoom,I as Replicator,c as SnapshotBuffer,D as decodeJson,u as decodeJsonSync,M as defineBinary,m as defineJson,_ as encodeJson,d as encodeJsonSync,$ as lerp,K as lerpAngle};
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@idosgames/netplay",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "The network layer of iDosGames room games, engine-free: a binary codec, a room over any peer transport (the lobby's WebRTC session from @idosgames/core/realtime fits as is) with the roster, joining a running game, relaying through the host of a star room and the host handover, and entities owned by one player and replicated to the others with interpolation.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "iDos Games",
|
|
8
|
+
"homepage": "https://github.com/iDos-Games/iDosGamesSDK_TS#readme",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/iDos-Games/iDosGamesSDK_TS.git",
|
|
12
|
+
"directory": "packages/netplay"
|
|
13
|
+
},
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/iDos-Games/iDosGamesSDK_TS/issues"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"idosgames",
|
|
19
|
+
"multiplayer",
|
|
20
|
+
"netcode",
|
|
21
|
+
"webrtc",
|
|
22
|
+
"interpolation",
|
|
23
|
+
"co-op"
|
|
24
|
+
],
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public"
|
|
27
|
+
},
|
|
28
|
+
"sideEffects": false,
|
|
29
|
+
"main": "./dist/index.cjs",
|
|
30
|
+
"module": "./dist/index.js",
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"exports": {
|
|
33
|
+
".": {
|
|
34
|
+
"types": "./dist/index.d.ts",
|
|
35
|
+
"import": "./dist/index.js",
|
|
36
|
+
"require": "./dist/index.cjs"
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"dist",
|
|
41
|
+
"README.md",
|
|
42
|
+
"LICENSE"
|
|
43
|
+
],
|
|
44
|
+
"scripts": {
|
|
45
|
+
"build": "tsup",
|
|
46
|
+
"typecheck": "tsc --noEmit -p tsconfig.json"
|
|
47
|
+
},
|
|
48
|
+
"//": "No dependencies on purpose: the room talks to a structural NetTransport, so the package needs neither core nor an engine. A game passes the lobby's RealtimeSession (it already has that shape)."
|
|
49
|
+
}
|