@antha/multiplayer-p2p-lock-step 0.0.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-CC0 +121 -0
- package/LICENSE-MIT +21 -0
- package/README.md +3 -0
- package/dist/antha-multiplayer-p2p-lock-step.mod.d.ts +37 -0
- package/dist/antha-multiplayer-p2p-lock-step.mod.js +49 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/p2p-lock-step-multiplayer-controller.d.ts +229 -0
- package/dist/p2p-lock-step-multiplayer-controller.js +411 -0
- package/package.json +60 -0
package/LICENSE-CC0
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
CC0 1.0 Universal
|
|
2
|
+
|
|
3
|
+
Creative Commons Legal Code
|
|
4
|
+
|
|
5
|
+
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
|
|
6
|
+
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
|
|
7
|
+
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
|
|
8
|
+
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
|
|
9
|
+
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
|
|
10
|
+
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
|
|
11
|
+
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
|
|
12
|
+
HEREUNDER.
|
|
13
|
+
|
|
14
|
+
Statement of Purpose
|
|
15
|
+
|
|
16
|
+
The laws of most jurisdictions throughout the world automatically confer
|
|
17
|
+
exclusive Copyright and Related Rights (defined below) upon the creator
|
|
18
|
+
and subsequent owner(s) (each and all, an "owner") of an original work of
|
|
19
|
+
authorship and/or a database (each, a "Work").
|
|
20
|
+
|
|
21
|
+
Certain owners wish to permanently relinquish those rights to a Work for
|
|
22
|
+
the purpose of contributing to a commons of creative, cultural and
|
|
23
|
+
scientific works ("Commons") that the public can reliably and without fear
|
|
24
|
+
of later claims of infringement build upon, modify, incorporate in other
|
|
25
|
+
works, reuse and redistribute as freely as possible in any form whatsoever
|
|
26
|
+
and for any purposes, including without limitation commercial purposes.
|
|
27
|
+
These owners may contribute to the Commons to promote the ideal of a free
|
|
28
|
+
culture and the further production of creative, cultural and scientific
|
|
29
|
+
works, or to gain reputation or greater distribution for their Work in
|
|
30
|
+
part through the use and efforts of others.
|
|
31
|
+
|
|
32
|
+
For these and/or other purposes and motivations, and without any
|
|
33
|
+
expectation of additional consideration or compensation, the person
|
|
34
|
+
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
|
|
35
|
+
is an owner of Copyright and Related Rights in the Work, voluntarily
|
|
36
|
+
elects to apply CC0 to the Work and publicly distribute the Work under its
|
|
37
|
+
terms, with knowledge of his or her Copyright and Related Rights in the
|
|
38
|
+
Work and the meaning and intended legal effect of CC0 on those rights.
|
|
39
|
+
|
|
40
|
+
1. Copyright and Related Rights. A Work made available under CC0 may be
|
|
41
|
+
protected by copyright and related or neighboring rights ("Copyright and
|
|
42
|
+
Related Rights"). Copyright and Related Rights include, but are not
|
|
43
|
+
limited to, the following:
|
|
44
|
+
|
|
45
|
+
i. the right to reproduce, adapt, distribute, perform, display,
|
|
46
|
+
communicate, and translate a Work;
|
|
47
|
+
ii. moral rights retained by the original author(s) and/or performer(s);
|
|
48
|
+
iii. publicity and privacy rights pertaining to a person's image or
|
|
49
|
+
likeness depicted in a Work;
|
|
50
|
+
iv. rights protecting against unfair competition in regards to a Work,
|
|
51
|
+
subject to the limitations in paragraph 4(a), below;
|
|
52
|
+
v. rights protecting the extraction, dissemination, use and reuse of data
|
|
53
|
+
in a Work;
|
|
54
|
+
vi. database rights (such as those arising under Directive 96/9/EC of the
|
|
55
|
+
European Parliament and of the Council of 11 March 1996 on the legal
|
|
56
|
+
protection of databases, and under any national implementation
|
|
57
|
+
thereof, including any amended or successor version of such
|
|
58
|
+
directive); and
|
|
59
|
+
vii. other similar, equivalent or corresponding rights throughout the
|
|
60
|
+
world based on applicable law or treaty, and any national
|
|
61
|
+
implementations thereof.
|
|
62
|
+
|
|
63
|
+
2. Waiver. To the greatest extent permitted by, but not in contravention
|
|
64
|
+
of, applicable law, Affirmer hereby overtly, fully, permanently,
|
|
65
|
+
irrevocably and unconditionally waives, abandons, and surrenders all of
|
|
66
|
+
Affirmer's Copyright and Related Rights and associated claims and causes
|
|
67
|
+
of action, whether now known or unknown (including existing as well as
|
|
68
|
+
future claims and causes of action), in the Work (i) in all territories
|
|
69
|
+
worldwide, (ii) for the maximum duration provided by applicable law or
|
|
70
|
+
treaty (including future time extensions), (iii) in any current or future
|
|
71
|
+
medium and for any number of copies, and (iv) for any purpose whatsoever,
|
|
72
|
+
including without limitation commercial, advertising or promotional
|
|
73
|
+
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
|
|
74
|
+
member of the public at large and to the detriment of Affirmer's heirs and
|
|
75
|
+
successors, fully intending that such Waiver shall not be subject to
|
|
76
|
+
revocation, rescission, cancellation, termination, or any other legal or
|
|
77
|
+
equitable action to disrupt the quiet enjoyment of the Work by the public
|
|
78
|
+
as contemplated by Affirmer's express Statement of Purpose.
|
|
79
|
+
|
|
80
|
+
3. Public License Fallback. Should any part of the Waiver for any reason
|
|
81
|
+
be judged legally invalid or ineffective under applicable law, then the
|
|
82
|
+
Waiver shall be preserved to the maximum extent permitted taking into
|
|
83
|
+
account Affirmer's express Statement of Purpose. In addition, to the
|
|
84
|
+
extent the Waiver is so judged Affirmer hereby grants to each affected
|
|
85
|
+
person a royalty-free, non transferable, non sublicensable, non exclusive,
|
|
86
|
+
irrevocable and unconditional license to exercise Affirmer's Copyright and
|
|
87
|
+
Related Rights in the Work (i) in all territories worldwide, (ii) for the
|
|
88
|
+
maximum duration provided by applicable law or treaty (including future
|
|
89
|
+
time extensions), (iii) in any current or future medium and for any number
|
|
90
|
+
of copies, and (iv) for any purpose whatsoever, including without
|
|
91
|
+
limitation commercial, advertising or promotional purposes (the
|
|
92
|
+
"License"). The License shall be deemed effective as of the date CC0 was
|
|
93
|
+
applied by Affirmer to the Work. Should any part of the License for any
|
|
94
|
+
reason be judged legally invalid or ineffective under applicable law, such
|
|
95
|
+
partial invalidity or ineffectiveness shall not invalidate the remainder
|
|
96
|
+
of the License, and in such case Affirmer hereby affirms that he or she
|
|
97
|
+
will not (i) exercise any of his or her remaining Copyright and Related
|
|
98
|
+
Rights in the Work or (ii) assert any associated claims and causes of
|
|
99
|
+
action with respect to the Work, in either case contrary to Affirmer's
|
|
100
|
+
express Statement of Purpose.
|
|
101
|
+
|
|
102
|
+
4. Limitations and Disclaimers.
|
|
103
|
+
|
|
104
|
+
a. No trademark or patent rights held by Affirmer are waived, abandoned,
|
|
105
|
+
surrendered, licensed or otherwise affected by this document.
|
|
106
|
+
b. Affirmer offers the Work as-is and makes no representations or
|
|
107
|
+
warranties of any kind concerning the Work, express, implied,
|
|
108
|
+
statutory or otherwise, including without limitation warranties of
|
|
109
|
+
title, merchantability, fitness for a particular purpose, non
|
|
110
|
+
infringement, or the absence of latent or other defects, accuracy, or
|
|
111
|
+
the present or absence of errors, whether or not discoverable, all to
|
|
112
|
+
the greatest extent permissible under applicable law.
|
|
113
|
+
c. Affirmer disclaims responsibility for clearing rights of other persons
|
|
114
|
+
that may apply to the Work or any use thereof, including without
|
|
115
|
+
limitation any person's Copyright and Related Rights in the Work.
|
|
116
|
+
Further, Affirmer disclaims responsibility for obtaining any necessary
|
|
117
|
+
consents, permissions or other rights required for any use of the
|
|
118
|
+
Work.
|
|
119
|
+
d. Affirmer understands and acknowledges that Creative Commons is not a
|
|
120
|
+
party to this document and has no duty or obligation with respect to
|
|
121
|
+
this CC0 or use of the Work.
|
package/LICENSE-MIT
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 electrovir
|
|
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
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type ApiAndRoomConnectionState, type MultiplayerClientRooms } from '@antha/multiplayer-core';
|
|
2
|
+
import { type JsonCompatibleValue, type PartialWithUndefined, type SelectFrom } from '@augment-vir/common';
|
|
3
|
+
import { P2pLockStepMultiplayerController, type P2pLockStepMultiplayerControllerParams } from './p2p-lock-step-multiplayer-controller.js';
|
|
4
|
+
/**
|
|
5
|
+
* Engine state added by the p2p-lock-step multiplayer mod.
|
|
6
|
+
*
|
|
7
|
+
* @category Internal
|
|
8
|
+
*/
|
|
9
|
+
export type AnthaMultiplayerP2pLockStepState<MultiplayerPacket extends JsonCompatibleValue = any> = {
|
|
10
|
+
/** Enables verbose multiplayer debug logs. */
|
|
11
|
+
debugMultiplayer?: boolean | undefined;
|
|
12
|
+
/** P2p-lock-step controller state. */
|
|
13
|
+
multiplayerP2pLockStep: {
|
|
14
|
+
/** Controller used to drive singleplayer or multiplayer frame sync. */
|
|
15
|
+
multiplayerController: P2pLockStepMultiplayerController<MultiplayerPacket>;
|
|
16
|
+
/** Current backend API and room connection state. */
|
|
17
|
+
connectionState: ApiAndRoomConnectionState;
|
|
18
|
+
/** Rooms currently available for joining. */
|
|
19
|
+
availableRooms: MultiplayerClientRooms;
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Options for {@link createAnthaMultiplayerP2pLockStepMod}.
|
|
24
|
+
*
|
|
25
|
+
* @category Internal
|
|
26
|
+
*/
|
|
27
|
+
export type AnthaMultiplayerP2pLockStepOptions<MultiplayerPacket extends JsonCompatibleValue = any> = PartialWithUndefined<SelectFrom<P2pLockStepMultiplayerControllerParams<MultiplayerPacket>, {
|
|
28
|
+
acceptConnection: true;
|
|
29
|
+
debugMultiplayer: true;
|
|
30
|
+
gameId: true;
|
|
31
|
+
}>>;
|
|
32
|
+
/**
|
|
33
|
+
* Create the engine mod that owns p2p-lock-step multiplayer state.
|
|
34
|
+
*
|
|
35
|
+
* @category Main
|
|
36
|
+
*/
|
|
37
|
+
export declare function createAnthaMultiplayerP2pLockStepMod<const MultiplayerPacket extends JsonCompatibleValue = any>(options?: Readonly<AnthaMultiplayerP2pLockStepOptions<MultiplayerPacket>>): import("@antha/engine").AnthaMod<NoInfer<AnthaMultiplayerP2pLockStepState<NoInfer<MultiplayerPacket>>>>;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { defineAnthaMod } from '@antha/engine';
|
|
2
|
+
import { ControllerConnectionEvent, ControllerRoomListEvent, emptyApiAndRoomConnectionState, } from '@antha/multiplayer-core';
|
|
3
|
+
import { log, } from '@augment-vir/common';
|
|
4
|
+
import { P2pLockStepMultiplayerController, } from './p2p-lock-step-multiplayer-controller.js';
|
|
5
|
+
/**
|
|
6
|
+
* Create the engine mod that owns p2p-lock-step multiplayer state.
|
|
7
|
+
*
|
|
8
|
+
* @category Main
|
|
9
|
+
*/
|
|
10
|
+
export function createAnthaMultiplayerP2pLockStepMod(options = {}) {
|
|
11
|
+
return defineAnthaMod({
|
|
12
|
+
modName: 'antha-multiplayer-p2p-lock-step',
|
|
13
|
+
execute({ state }) {
|
|
14
|
+
if (options.debugMultiplayer == undefined) {
|
|
15
|
+
state.debugMultiplayer = options.debugMultiplayer;
|
|
16
|
+
}
|
|
17
|
+
if (!state.multiplayerP2pLockStep) {
|
|
18
|
+
log.if(!!state.debugMultiplayer).faint('[multiplayer] creating p2p-lock-step mod state');
|
|
19
|
+
state.multiplayerP2pLockStep = {
|
|
20
|
+
multiplayerController: new P2pLockStepMultiplayerController({
|
|
21
|
+
gameId: options.gameId || 'antha',
|
|
22
|
+
acceptConnection: options.acceptConnection,
|
|
23
|
+
debugMultiplayer: state.debugMultiplayer,
|
|
24
|
+
frameDuration: undefined,
|
|
25
|
+
}),
|
|
26
|
+
connectionState: emptyApiAndRoomConnectionState,
|
|
27
|
+
availableRooms: {},
|
|
28
|
+
};
|
|
29
|
+
state.multiplayerP2pLockStep.multiplayerController.listen(ControllerConnectionEvent, ({ detail: newConnectionState }) => {
|
|
30
|
+
if (!state.multiplayerP2pLockStep) {
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
log.if(!!state.debugMultiplayer).faint(`[multiplayer] mod connection state updated: api=${String(newConnectionState.api)} room=${String(newConnectionState.room)}`);
|
|
34
|
+
state.multiplayerP2pLockStep.connectionState = newConnectionState;
|
|
35
|
+
});
|
|
36
|
+
state.multiplayerP2pLockStep.multiplayerController.listen(ControllerRoomListEvent, ({ detail: rooms }) => {
|
|
37
|
+
if (!state.multiplayerP2pLockStep) {
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
state.multiplayerP2pLockStep.availableRooms = rooms;
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
cleanup({ state }) {
|
|
45
|
+
log.if(!!state.debugMultiplayer).faint('[multiplayer] cleaning up p2p-lock-step mod');
|
|
46
|
+
state.multiplayerP2pLockStep?.multiplayerController.destroy();
|
|
47
|
+
},
|
|
48
|
+
});
|
|
49
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { type ApiAndRoomConnectionState, type ClientId, ControllerClientEvent, ControllerConnectionEvent, ControllerRoomListEvent, type MultiplayerInitParams, type MultiplayerRoomConnection, MultiplayerRoomController, type RoomInput, RoomRejectionError } from '@antha/multiplayer-core';
|
|
2
|
+
import { type JsonCompatibleValue, type MaybePromise, type PartialWithUndefined } from '@augment-vir/common';
|
|
3
|
+
import { type AnyDuration } from 'date-vir';
|
|
4
|
+
import { ListenTarget, type TypedCustomEventInit } from 'typed-event-target';
|
|
5
|
+
/**
|
|
6
|
+
* Message type for {@link P2pLockStepMessage}.
|
|
7
|
+
*
|
|
8
|
+
* @category Internal
|
|
9
|
+
*/
|
|
10
|
+
export declare enum P2pLockStepMessageType {
|
|
11
|
+
Actions = "actions",
|
|
12
|
+
Frame = "frame"
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Data received from {@link ControllerFrameEvent}.
|
|
16
|
+
*
|
|
17
|
+
* @category Internal
|
|
18
|
+
*/
|
|
19
|
+
export type FrameEventDetail<MultiplayerPacket extends JsonCompatibleValue> = {
|
|
20
|
+
packet: MultiplayerPacket;
|
|
21
|
+
clientId: ClientId;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Message exchanged by p2p-lock-step clients.
|
|
25
|
+
*
|
|
26
|
+
* @category Internal
|
|
27
|
+
*/
|
|
28
|
+
export type P2pLockStepMessage<MultiplayerPacket extends JsonCompatibleValue> =
|
|
29
|
+
/** Sent from child clients to the host as actions happen. */
|
|
30
|
+
{
|
|
31
|
+
type: P2pLockStepMessageType.Actions;
|
|
32
|
+
sourceClientId: ClientId;
|
|
33
|
+
actions: MultiplayerPacket[];
|
|
34
|
+
} | {
|
|
35
|
+
type: P2pLockStepMessageType.Frame;
|
|
36
|
+
actions: FrameEventDetail<MultiplayerPacket>[];
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Constructor parameters for {@link P2pLockStepMultiplayerController}.
|
|
40
|
+
*
|
|
41
|
+
* @category Internal
|
|
42
|
+
*/
|
|
43
|
+
export type P2pLockStepMultiplayerControllerParams<Action extends JsonCompatibleValue> = {
|
|
44
|
+
/**
|
|
45
|
+
* A unique string id that represents your game so that your lobby server can serve multiple
|
|
46
|
+
* games at once. Your lobby server will need to know this game id ahead of time and match it to
|
|
47
|
+
* your frontend's origin.
|
|
48
|
+
*/
|
|
49
|
+
gameId: string;
|
|
50
|
+
} & PartialWithUndefined<{
|
|
51
|
+
/**
|
|
52
|
+
* This is fired when a WebRTC peer attempts to connect to the host client. Return `true` to
|
|
53
|
+
* accept the connection. Return `false` to reject it.
|
|
54
|
+
*
|
|
55
|
+
* @default accept all connections
|
|
56
|
+
*/
|
|
57
|
+
acceptConnection?: ((connectingClientId: ClientId, controller: P2pLockStepMultiplayerController<Action>) => MaybePromise<boolean>) | undefined;
|
|
58
|
+
/** Enables verbose multiplayer debug logs. */
|
|
59
|
+
debugMultiplayer?: boolean | undefined;
|
|
60
|
+
/**
|
|
61
|
+
* The duration between each frame. This should probably always be smaller than your supported
|
|
62
|
+
* render frame duration.
|
|
63
|
+
*
|
|
64
|
+
* @default {milliseconds: 10}
|
|
65
|
+
*/
|
|
66
|
+
frameDuration?: AnyDuration | undefined;
|
|
67
|
+
}>;
|
|
68
|
+
declare const ControllerFrameEvent_base: (new (eventInitDict: {
|
|
69
|
+
bubbles?: boolean;
|
|
70
|
+
cancelable?: boolean;
|
|
71
|
+
composed?: boolean;
|
|
72
|
+
detail: any;
|
|
73
|
+
}) => import("typed-event-target").TypedCustomEvent<any, "controller-frame">) & Pick<{
|
|
74
|
+
new (type: string, eventInitDict?: EventInit): Event;
|
|
75
|
+
prototype: Event;
|
|
76
|
+
readonly NONE: 0;
|
|
77
|
+
readonly CAPTURING_PHASE: 1;
|
|
78
|
+
readonly AT_TARGET: 2;
|
|
79
|
+
readonly BUBBLING_PHASE: 3;
|
|
80
|
+
}, "prototype" | "NONE" | "CAPTURING_PHASE" | "AT_TARGET" | "BUBBLING_PHASE"> & Pick<import("typed-event-target").TypedCustomEvent<any, "controller-frame">, "type">;
|
|
81
|
+
/**
|
|
82
|
+
* This is fired whenever a new p2p-lock-step frame is received from the host client.
|
|
83
|
+
*
|
|
84
|
+
* @category Events
|
|
85
|
+
*/
|
|
86
|
+
export declare class ControllerFrameEvent<MultiplayerPacket extends JsonCompatibleValue> extends ControllerFrameEvent_base {
|
|
87
|
+
detail: ReadonlyArray<FrameEventDetail<MultiplayerPacket>>;
|
|
88
|
+
constructor(eventInitDict: TypedCustomEventInit<ReadonlyArray<FrameEventDetail<MultiplayerPacket>>>);
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* All events emitted by this controller.
|
|
92
|
+
*
|
|
93
|
+
* @category Internal
|
|
94
|
+
*/
|
|
95
|
+
export type AllP2pLockStepMultiplayerControllerEvents<MultiplayerPacket extends JsonCompatibleValue> = ControllerFrameEvent<MultiplayerPacket> | ControllerRoomListEvent | ControllerClientEvent | ControllerConnectionEvent;
|
|
96
|
+
/**
|
|
97
|
+
* Listener callback for p2p-lock-step frame events.
|
|
98
|
+
*
|
|
99
|
+
* @category Internal
|
|
100
|
+
*/
|
|
101
|
+
export type ControllerFrameListener<MultiplayerPacket extends JsonCompatibleValue> = (event: Readonly<ControllerFrameEvent<MultiplayerPacket>>) => MaybePromise<void>;
|
|
102
|
+
/**
|
|
103
|
+
* An all-in-one controller for singleplayer or p2p-lock-step multiplayer game state.
|
|
104
|
+
*
|
|
105
|
+
* @category Main
|
|
106
|
+
*/
|
|
107
|
+
export declare class P2pLockStepMultiplayerController<MultiplayerPacket extends JsonCompatibleValue = any> extends ListenTarget<AllP2pLockStepMultiplayerControllerEvents<MultiplayerPacket>> {
|
|
108
|
+
protected readonly params: P2pLockStepMultiplayerControllerParams<MultiplayerPacket>;
|
|
109
|
+
/** The current data flow FPS. */
|
|
110
|
+
readonly currentFps: number;
|
|
111
|
+
/** All events emitted by this controller. */
|
|
112
|
+
static readonly events: {
|
|
113
|
+
ControllerFrameEvent: typeof ControllerFrameEvent;
|
|
114
|
+
};
|
|
115
|
+
/** All events emitted by this controller. */
|
|
116
|
+
readonly events: {
|
|
117
|
+
ControllerFrameEvent: typeof ControllerFrameEvent;
|
|
118
|
+
};
|
|
119
|
+
static readonly knownErrors: {
|
|
120
|
+
RoomRejectionError: typeof RoomRejectionError;
|
|
121
|
+
};
|
|
122
|
+
readonly knownErrors: {
|
|
123
|
+
RoomRejectionError: typeof RoomRejectionError;
|
|
124
|
+
};
|
|
125
|
+
/** Core multiplayer room controller that owns API, room polling, signaling, and transport. */
|
|
126
|
+
readonly roomController: MultiplayerRoomController<P2pLockStepMessage<MultiplayerPacket>>;
|
|
127
|
+
protected readonly localClientId: ClientId;
|
|
128
|
+
protected roomConnection: MultiplayerRoomConnection<P2pLockStepMessage<MultiplayerPacket>> | undefined;
|
|
129
|
+
protected clientsResponded: Record<ClientId, boolean>;
|
|
130
|
+
protected frameActions: FrameEventDetail<MultiplayerPacket>[];
|
|
131
|
+
protected timeoutId: ReturnType<typeof globalThis.setTimeout> | undefined;
|
|
132
|
+
protected frameTickReady: boolean;
|
|
133
|
+
protected frameMs: number | undefined;
|
|
134
|
+
protected lastFpsCalculation: {
|
|
135
|
+
timestamp: number;
|
|
136
|
+
frameCount: number;
|
|
137
|
+
};
|
|
138
|
+
protected singleplayer: boolean;
|
|
139
|
+
constructor(params: P2pLockStepMultiplayerControllerParams<MultiplayerPacket>);
|
|
140
|
+
/** Current p2p-lock-step connection, exposed for compatibility checks. */
|
|
141
|
+
get currentConnection(): this | undefined;
|
|
142
|
+
/** The current client id. */
|
|
143
|
+
get clientId(): ClientId;
|
|
144
|
+
/**
|
|
145
|
+
* Set to `false` to disable room updates, even when still not connected to a room in
|
|
146
|
+
* multiplayer mode.
|
|
147
|
+
*/
|
|
148
|
+
get enableRoomUpdates(): boolean;
|
|
149
|
+
/** Update whether room list polling is enabled while not connected to a room. */
|
|
150
|
+
set enableRoomUpdates(value: boolean);
|
|
151
|
+
/** Currently joined room id. If a room has not been joined yet, this will be empty. */
|
|
152
|
+
get roomId(): import("@antha/multiplayer-core").RoomId | undefined;
|
|
153
|
+
/** The current connection state of the controller's connection to a backend API. */
|
|
154
|
+
get apiConnectionState(): ApiAndRoomConnectionState['api'];
|
|
155
|
+
/** The current connection state of the controller's connection to a multiplayer room. */
|
|
156
|
+
get roomConnectionState(): ApiAndRoomConnectionState['room'];
|
|
157
|
+
/** The current multiplayer API client. This will be `undefined` if playing in single player. */
|
|
158
|
+
get multiplayerApiClient(): Readonly<import("@rest-vir/api").RestVirClient<{
|
|
159
|
+
apiName: string;
|
|
160
|
+
endpoints: Readonly<Record<"/" | "/health" | "/rooms", Readonly<import("@rest-vir/api").EndpointDefinition>>>;
|
|
161
|
+
webSockets: Readonly<Record<"/connect", Readonly<import("@rest-vir/api").WebSocketDefinition>>>;
|
|
162
|
+
}>> | undefined;
|
|
163
|
+
/**
|
|
164
|
+
* Get the current client's WebRTC client id. This will return `undefined` if there is no
|
|
165
|
+
* current connection.
|
|
166
|
+
*/
|
|
167
|
+
getClientId(): ClientId | undefined;
|
|
168
|
+
/**
|
|
169
|
+
* Get all connected client ids.
|
|
170
|
+
*
|
|
171
|
+
* - For host clients, this indicates how many member clients are connected to the host client,
|
|
172
|
+
* _not_ including the host itself.
|
|
173
|
+
* - For non-host clients, this only lists the local connection used to reach the host.
|
|
174
|
+
*/
|
|
175
|
+
getConnectedClientIds(): ClientId[];
|
|
176
|
+
/**
|
|
177
|
+
* Get all room client ids.
|
|
178
|
+
*
|
|
179
|
+
* - For host clients, this indicates how many clients are connected to the room, including the
|
|
180
|
+
* host client itself.
|
|
181
|
+
* - For non-host clients, this includes the member client and the host client once connected.
|
|
182
|
+
*/
|
|
183
|
+
getAllClientIds(): ClientId[];
|
|
184
|
+
/** Start multiplayer mode. This delegates API connectivity and room polling to multiplayer core. */
|
|
185
|
+
initMultiplayer(params: Readonly<MultiplayerInitParams>): Promise<void>;
|
|
186
|
+
/** Start singleplayer mode. */
|
|
187
|
+
startSingleplayer(): void;
|
|
188
|
+
/**
|
|
189
|
+
* Manually run the next frame.
|
|
190
|
+
*
|
|
191
|
+
* @throws Error if `frameDuration` has been set.
|
|
192
|
+
*/
|
|
193
|
+
runFrame(actions?: ReadonlyArray<MultiplayerPacket> | undefined): void;
|
|
194
|
+
/** The current FPS of the data flow. */
|
|
195
|
+
getFps(): number;
|
|
196
|
+
/** Fire an action. This will be sent to all clients in the room so they can process it. */
|
|
197
|
+
act(actions: MultiplayerPacket | ReadonlyArray<MultiplayerPacket>): void;
|
|
198
|
+
/** Detects if this controller is the room host or not. */
|
|
199
|
+
isHost(): boolean;
|
|
200
|
+
/** Detects if this controller is connected to a room or not. */
|
|
201
|
+
isConnected(): boolean;
|
|
202
|
+
/** Cleanup everything. */
|
|
203
|
+
destroy(): void;
|
|
204
|
+
/**
|
|
205
|
+
* Join or create a room.
|
|
206
|
+
*
|
|
207
|
+
* @throws `Error` if this controller is already connected to a room.
|
|
208
|
+
*/
|
|
209
|
+
joinOrCreateRoom(room: Readonly<RoomInput>): Promise<void>;
|
|
210
|
+
/** Leave the current room or single player connection. */
|
|
211
|
+
leaveRoom(): void;
|
|
212
|
+
/** Forward core room-controller events into this frame-sync controller. */
|
|
213
|
+
protected listenToRoomController(): void;
|
|
214
|
+
/** Attach an established room transport and publish initial frame readiness. */
|
|
215
|
+
protected attachMultiplayerRoomConnection(roomConnection: Readonly<MultiplayerRoomConnection<P2pLockStepMessage<MultiplayerPacket>>>): void;
|
|
216
|
+
/** Send an empty frame to a newly connected member so it can join the frame flow. */
|
|
217
|
+
protected syncNewMember(clientId: ClientId): void;
|
|
218
|
+
/** Apply received member actions on the host or received frames on member clients. */
|
|
219
|
+
protected handleReceivedMessage(sourceClientId: ClientId, message: Readonly<P2pLockStepMessage<MultiplayerPacket>>): void;
|
|
220
|
+
/** Recalculate the current data-flow FPS from completed frames. */
|
|
221
|
+
protected calculateFps(): void;
|
|
222
|
+
/** Complete the current frame and schedule the next automatic frame when configured. */
|
|
223
|
+
protected finishFrame(): void;
|
|
224
|
+
/** Complete a frame when this host has reached its configured readiness conditions. */
|
|
225
|
+
protected maybeFinishFrame(): void;
|
|
226
|
+
/** Write a multiplayer debug log when debug logging is enabled. */
|
|
227
|
+
protected debugLog(message: string): void;
|
|
228
|
+
}
|
|
229
|
+
export {};
|
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
import { ControllerClientEvent, ControllerConnectionEvent, ControllerMessageEvent, ControllerRoomListEvent, createMultiplayerId, emptyApiAndRoomConnectionState, MultiplayerConnectionState, MultiplayerRoomController, RoomRejectionError, } from '@antha/multiplayer-core';
|
|
2
|
+
import { ensureArray, log, makeWritable, } from '@augment-vir/common';
|
|
3
|
+
import { convertDuration } from 'date-vir';
|
|
4
|
+
import { defineTypedCustomEvent, ListenTarget } from 'typed-event-target';
|
|
5
|
+
/**
|
|
6
|
+
* Message type for {@link P2pLockStepMessage}.
|
|
7
|
+
*
|
|
8
|
+
* @category Internal
|
|
9
|
+
*/
|
|
10
|
+
export var P2pLockStepMessageType;
|
|
11
|
+
(function (P2pLockStepMessageType) {
|
|
12
|
+
P2pLockStepMessageType["Actions"] = "actions";
|
|
13
|
+
P2pLockStepMessageType["Frame"] = "frame";
|
|
14
|
+
})(P2pLockStepMessageType || (P2pLockStepMessageType = {}));
|
|
15
|
+
/**
|
|
16
|
+
* This is fired whenever a new p2p-lock-step frame is received from the host client.
|
|
17
|
+
*
|
|
18
|
+
* @category Events
|
|
19
|
+
*/
|
|
20
|
+
export class ControllerFrameEvent extends defineTypedCustomEvent()('controller-frame') {
|
|
21
|
+
constructor(eventInitDict) {
|
|
22
|
+
super(eventInitDict);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
const defaultFrameDuration = {
|
|
26
|
+
milliseconds: 10,
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* An all-in-one controller for singleplayer or p2p-lock-step multiplayer game state.
|
|
30
|
+
*
|
|
31
|
+
* @category Main
|
|
32
|
+
*/
|
|
33
|
+
export class P2pLockStepMultiplayerController extends ListenTarget {
|
|
34
|
+
params;
|
|
35
|
+
/** The current data flow FPS. */
|
|
36
|
+
currentFps = 0;
|
|
37
|
+
/** All events emitted by this controller. */
|
|
38
|
+
static events = {
|
|
39
|
+
ControllerFrameEvent,
|
|
40
|
+
};
|
|
41
|
+
/** All events emitted by this controller. */
|
|
42
|
+
events = P2pLockStepMultiplayerController.events;
|
|
43
|
+
static knownErrors = {
|
|
44
|
+
RoomRejectionError,
|
|
45
|
+
};
|
|
46
|
+
knownErrors = P2pLockStepMultiplayerController.knownErrors;
|
|
47
|
+
/** Core multiplayer room controller that owns API, room polling, signaling, and transport. */
|
|
48
|
+
roomController;
|
|
49
|
+
localClientId = createMultiplayerId.client();
|
|
50
|
+
roomConnection;
|
|
51
|
+
clientsResponded = {};
|
|
52
|
+
frameActions = [];
|
|
53
|
+
timeoutId;
|
|
54
|
+
frameTickReady = true;
|
|
55
|
+
frameMs;
|
|
56
|
+
lastFpsCalculation = {
|
|
57
|
+
timestamp: 0,
|
|
58
|
+
frameCount: 0,
|
|
59
|
+
};
|
|
60
|
+
singleplayer = false;
|
|
61
|
+
constructor(params) {
|
|
62
|
+
super();
|
|
63
|
+
this.params = params;
|
|
64
|
+
this.debugLog(`constructing controller for game '${params.gameId}'`);
|
|
65
|
+
const frameDuration = params.frameDuration || defaultFrameDuration;
|
|
66
|
+
this.frameMs = convertDuration(frameDuration, {
|
|
67
|
+
milliseconds: true,
|
|
68
|
+
}).milliseconds;
|
|
69
|
+
this.roomController = new MultiplayerRoomController({
|
|
70
|
+
gameId: params.gameId,
|
|
71
|
+
acceptConnection: params.acceptConnection
|
|
72
|
+
? (connectingClientId) => {
|
|
73
|
+
this.debugLog(`checking incoming connection from ${connectingClientId}`);
|
|
74
|
+
return params.acceptConnection?.(connectingClientId, this) ?? true;
|
|
75
|
+
}
|
|
76
|
+
: undefined,
|
|
77
|
+
});
|
|
78
|
+
this.listenToRoomController();
|
|
79
|
+
}
|
|
80
|
+
/** Current p2p-lock-step connection, exposed for compatibility checks. */
|
|
81
|
+
get currentConnection() {
|
|
82
|
+
return this.isConnected() ? this : undefined;
|
|
83
|
+
}
|
|
84
|
+
/** The current client id. */
|
|
85
|
+
get clientId() {
|
|
86
|
+
return this.roomConnection?.clientId || this.localClientId;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Set to `false` to disable room updates, even when still not connected to a room in
|
|
90
|
+
* multiplayer mode.
|
|
91
|
+
*/
|
|
92
|
+
get enableRoomUpdates() {
|
|
93
|
+
return this.roomController.enableRoomUpdates;
|
|
94
|
+
}
|
|
95
|
+
/** Update whether room list polling is enabled while not connected to a room. */
|
|
96
|
+
set enableRoomUpdates(value) {
|
|
97
|
+
this.roomController.enableRoomUpdates = value;
|
|
98
|
+
}
|
|
99
|
+
/** Currently joined room id. If a room has not been joined yet, this will be empty. */
|
|
100
|
+
get roomId() {
|
|
101
|
+
return this.roomController.roomId;
|
|
102
|
+
}
|
|
103
|
+
/** The current connection state of the controller's connection to a backend API. */
|
|
104
|
+
get apiConnectionState() {
|
|
105
|
+
return this.roomController.apiConnectionState;
|
|
106
|
+
}
|
|
107
|
+
/** The current connection state of the controller's connection to a multiplayer room. */
|
|
108
|
+
get roomConnectionState() {
|
|
109
|
+
return this.roomController.roomConnectionState;
|
|
110
|
+
}
|
|
111
|
+
/** The current multiplayer API client. This will be `undefined` if playing in single player. */
|
|
112
|
+
get multiplayerApiClient() {
|
|
113
|
+
return this.roomController.multiplayerApiClient;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Get the current client's WebRTC client id. This will return `undefined` if there is no
|
|
117
|
+
* current connection.
|
|
118
|
+
*/
|
|
119
|
+
getClientId() {
|
|
120
|
+
if (this.singleplayer) {
|
|
121
|
+
return this.localClientId;
|
|
122
|
+
}
|
|
123
|
+
return this.roomConnection?.clientId || this.roomController.getClientId();
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Get all connected client ids.
|
|
127
|
+
*
|
|
128
|
+
* - For host clients, this indicates how many member clients are connected to the host client,
|
|
129
|
+
* _not_ including the host itself.
|
|
130
|
+
* - For non-host clients, this only lists the local connection used to reach the host.
|
|
131
|
+
*/
|
|
132
|
+
getConnectedClientIds() {
|
|
133
|
+
return this.roomConnection?.getConnectedClientIds() || [];
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Get all room client ids.
|
|
137
|
+
*
|
|
138
|
+
* - For host clients, this indicates how many clients are connected to the room, including the
|
|
139
|
+
* host client itself.
|
|
140
|
+
* - For non-host clients, this includes the member client and the host client once connected.
|
|
141
|
+
*/
|
|
142
|
+
getAllClientIds() {
|
|
143
|
+
if (this.singleplayer) {
|
|
144
|
+
return [
|
|
145
|
+
this.localClientId,
|
|
146
|
+
];
|
|
147
|
+
}
|
|
148
|
+
return this.roomConnection?.getAllClientIds() || [];
|
|
149
|
+
}
|
|
150
|
+
/** Start multiplayer mode. This delegates API connectivity and room polling to multiplayer core. */
|
|
151
|
+
async initMultiplayer(params) {
|
|
152
|
+
this.debugLog(`initializing multiplayer with backend ${params.backendOrigin}`);
|
|
153
|
+
await this.roomController.initMultiplayer(params);
|
|
154
|
+
this.debugLog('multiplayer API initialized');
|
|
155
|
+
}
|
|
156
|
+
/** Start singleplayer mode. */
|
|
157
|
+
startSingleplayer() {
|
|
158
|
+
if (this.currentConnection) {
|
|
159
|
+
throw new Error('Cannot start singleplayer with a connection already present.');
|
|
160
|
+
}
|
|
161
|
+
this.debugLog('starting singleplayer connection');
|
|
162
|
+
this.singleplayer = true;
|
|
163
|
+
this.finishFrame();
|
|
164
|
+
this.dispatch(new ControllerConnectionEvent({
|
|
165
|
+
detail: {
|
|
166
|
+
...emptyApiAndRoomConnectionState,
|
|
167
|
+
api: MultiplayerConnectionState.Connected,
|
|
168
|
+
},
|
|
169
|
+
}));
|
|
170
|
+
this.debugLog(`singleplayer connection ready with client ${this.getClientId() || 'unknown'}`);
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Manually run the next frame.
|
|
174
|
+
*
|
|
175
|
+
* @throws Error if `frameDuration` has been set.
|
|
176
|
+
*/
|
|
177
|
+
runFrame(actions) {
|
|
178
|
+
this.debugLog(`runFrame called with ${actions?.length || 0} actions`);
|
|
179
|
+
if (this.frameMs != undefined) {
|
|
180
|
+
throw new Error('Cannot manually run frame when frameDuration has been set.');
|
|
181
|
+
}
|
|
182
|
+
if (actions) {
|
|
183
|
+
this.act(actions);
|
|
184
|
+
}
|
|
185
|
+
if (this.isHost()) {
|
|
186
|
+
this.frameTickReady = true;
|
|
187
|
+
this.maybeFinishFrame();
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/** The current FPS of the data flow. */
|
|
191
|
+
getFps() {
|
|
192
|
+
return this.currentFps;
|
|
193
|
+
}
|
|
194
|
+
/** Fire an action. This will be sent to all clients in the room so they can process it. */
|
|
195
|
+
act(actions) {
|
|
196
|
+
if (!this.currentConnection || !this.currentConnection.isConnected()) {
|
|
197
|
+
throw new Error('Cannot perform action: not connected to a room.');
|
|
198
|
+
}
|
|
199
|
+
const actionArray = ensureArray(actions);
|
|
200
|
+
this.debugLog(`act called with ${actionArray.length} actions`);
|
|
201
|
+
this.frameActions = [
|
|
202
|
+
...this.frameActions,
|
|
203
|
+
...actionArray.map((packet) => {
|
|
204
|
+
return {
|
|
205
|
+
clientId: this.clientId,
|
|
206
|
+
packet,
|
|
207
|
+
};
|
|
208
|
+
}),
|
|
209
|
+
];
|
|
210
|
+
}
|
|
211
|
+
/** Detects if this controller is the room host or not. */
|
|
212
|
+
isHost() {
|
|
213
|
+
return this.singleplayer || this.roomConnection?.isHost() || false;
|
|
214
|
+
}
|
|
215
|
+
/** Detects if this controller is connected to a room or not. */
|
|
216
|
+
isConnected() {
|
|
217
|
+
return this.singleplayer || this.roomConnection?.isConnected() || false;
|
|
218
|
+
}
|
|
219
|
+
/** Cleanup everything. */
|
|
220
|
+
destroy() {
|
|
221
|
+
this.debugLog('destroying controller');
|
|
222
|
+
globalThis.clearTimeout(this.timeoutId);
|
|
223
|
+
this.roomConnection = undefined;
|
|
224
|
+
this.singleplayer = false;
|
|
225
|
+
this.roomController.destroy();
|
|
226
|
+
super.destroy();
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Join or create a room.
|
|
230
|
+
*
|
|
231
|
+
* @throws `Error` if this controller is already connected to a room.
|
|
232
|
+
*/
|
|
233
|
+
async joinOrCreateRoom(room) {
|
|
234
|
+
if (this.currentConnection) {
|
|
235
|
+
throw new Error('Cannot join room: connection already established.');
|
|
236
|
+
}
|
|
237
|
+
this.debugLog(`joining or creating room '${room.roomName}' (${room.roomId})`);
|
|
238
|
+
try {
|
|
239
|
+
await this.roomController.joinOrCreateRoom(room);
|
|
240
|
+
this.debugLog(`room controller joined room '${room.roomName}' (${room.roomId}); client=${this.roomController.getClientId() || 'unknown'} host=${this.roomController.isHost()}`);
|
|
241
|
+
if (!this.roomController.currentConnection) {
|
|
242
|
+
throw new Error('Cannot start p2p-lock-step multiplayer: room connection is missing.');
|
|
243
|
+
}
|
|
244
|
+
this.attachMultiplayerRoomConnection(this.roomController.currentConnection);
|
|
245
|
+
this.debugLog(`attached p2p-lock-step connection; client=${this.getClientId() || 'unknown'} host=${this.isHost()} connected=${this.isConnected()}`);
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
this.debugLog(`join room failed: ${String(error)}`);
|
|
249
|
+
this.roomConnection = undefined;
|
|
250
|
+
throw error;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
/** Leave the current room or single player connection. */
|
|
254
|
+
leaveRoom() {
|
|
255
|
+
if (!this.currentConnection) {
|
|
256
|
+
this.debugLog('leaveRoom called without a current connection');
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
this.debugLog(`leaving room '${this.roomId || 'unknown'}'`);
|
|
260
|
+
globalThis.clearTimeout(this.timeoutId);
|
|
261
|
+
this.roomConnection = undefined;
|
|
262
|
+
this.singleplayer = false;
|
|
263
|
+
this.roomController.leaveRoom();
|
|
264
|
+
}
|
|
265
|
+
/** Forward core room-controller events into this frame-sync controller. */
|
|
266
|
+
listenToRoomController() {
|
|
267
|
+
this.roomController.listen(ControllerRoomListEvent, (event) => {
|
|
268
|
+
this.dispatch(event);
|
|
269
|
+
});
|
|
270
|
+
this.roomController.listen(ControllerConnectionEvent, (event) => {
|
|
271
|
+
this.debugLog(`connection event received: api=${String(event.detail.api)} room=${String(event.detail.room)}`);
|
|
272
|
+
this.dispatch(event);
|
|
273
|
+
});
|
|
274
|
+
this.roomController.listen(ControllerClientEvent, (event) => {
|
|
275
|
+
this.debugLog(`client event received: ${JSON.stringify(event.detail)}`);
|
|
276
|
+
if ('newMember' in event.detail) {
|
|
277
|
+
this.syncNewMember(event.detail.newMember);
|
|
278
|
+
}
|
|
279
|
+
this.dispatch(event);
|
|
280
|
+
});
|
|
281
|
+
this.roomController.listen((ControllerMessageEvent), (event) => {
|
|
282
|
+
this.debugLog(`message event received from ${event.sourceClientId}: type=${event.detail.type}`);
|
|
283
|
+
this.handleReceivedMessage(event.sourceClientId, event.detail);
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
/** Attach an established room transport and publish initial frame readiness. */
|
|
287
|
+
attachMultiplayerRoomConnection(roomConnection) {
|
|
288
|
+
this.debugLog(`attached room connection; client=${roomConnection.clientId} host=${roomConnection.isHost()} connected=${roomConnection.isConnected()} connectedClients=${roomConnection.getConnectedClientIds().length} allClients=${roomConnection.getAllClientIds().length}`);
|
|
289
|
+
this.roomConnection = roomConnection;
|
|
290
|
+
if (roomConnection.isHost()) {
|
|
291
|
+
this.finishFrame();
|
|
292
|
+
}
|
|
293
|
+
else {
|
|
294
|
+
this.debugLog('attached as member; sending initial readiness actions to host');
|
|
295
|
+
roomConnection.sendMessage({
|
|
296
|
+
actions: [],
|
|
297
|
+
sourceClientId: this.clientId,
|
|
298
|
+
type: P2pLockStepMessageType.Actions,
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
/** Send an empty frame to a newly connected member so it can join the frame flow. */
|
|
303
|
+
syncNewMember(clientId) {
|
|
304
|
+
this.debugLog(`syncNewMember called for ${clientId}; host=${this.isHost()}`);
|
|
305
|
+
if (this.roomConnection && this.isHost()) {
|
|
306
|
+
this.roomConnection.sendToOnlyOneClient(clientId, {
|
|
307
|
+
type: P2pLockStepMessageType.Frame,
|
|
308
|
+
actions: [],
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
/** Apply received member actions on the host or received frames on member clients. */
|
|
313
|
+
handleReceivedMessage(sourceClientId, message) {
|
|
314
|
+
this.debugLog(`received lock-step message from ${sourceClientId}: type=${message.type} host=${this.isHost()}`);
|
|
315
|
+
if (!this.roomConnection) {
|
|
316
|
+
this.debugLog('ignored message because no room connection is attached');
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
if (this.isHost() && message.type === P2pLockStepMessageType.Actions) {
|
|
320
|
+
this.debugLog(`host received ${message.actions.length} actions from ${sourceClientId}`);
|
|
321
|
+
this.clientsResponded = {
|
|
322
|
+
...this.clientsResponded,
|
|
323
|
+
[sourceClientId]: true,
|
|
324
|
+
};
|
|
325
|
+
this.frameActions = [
|
|
326
|
+
...this.frameActions,
|
|
327
|
+
...message.actions.map((packet) => {
|
|
328
|
+
return {
|
|
329
|
+
clientId: sourceClientId,
|
|
330
|
+
packet,
|
|
331
|
+
};
|
|
332
|
+
}),
|
|
333
|
+
];
|
|
334
|
+
this.maybeFinishFrame();
|
|
335
|
+
}
|
|
336
|
+
else if (!this.isHost() && message.type === P2pLockStepMessageType.Frame) {
|
|
337
|
+
this.debugLog(`member received frame with ${message.actions.length} actions; sending ${this.frameActions.length} local actions back to host`);
|
|
338
|
+
const currentFrameActions = this.frameActions;
|
|
339
|
+
this.frameActions = [];
|
|
340
|
+
this.calculateFps();
|
|
341
|
+
this.roomConnection.sendMessage({
|
|
342
|
+
actions: currentFrameActions.map(({ packet }) => {
|
|
343
|
+
return packet;
|
|
344
|
+
}),
|
|
345
|
+
sourceClientId: this.clientId,
|
|
346
|
+
type: P2pLockStepMessageType.Actions,
|
|
347
|
+
});
|
|
348
|
+
this.dispatch(new ControllerFrameEvent({
|
|
349
|
+
detail: message.actions,
|
|
350
|
+
}));
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
/** Recalculate the current data-flow FPS from completed frames. */
|
|
354
|
+
calculateFps() {
|
|
355
|
+
const now = Date.now();
|
|
356
|
+
const diff = Date.now() - this.lastFpsCalculation.timestamp;
|
|
357
|
+
if (diff > 1000) {
|
|
358
|
+
makeWritable(this).currentFps = this.lastFpsCalculation.frameCount / (diff / 1000);
|
|
359
|
+
this.lastFpsCalculation = {
|
|
360
|
+
frameCount: 0,
|
|
361
|
+
timestamp: now,
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
else {
|
|
365
|
+
this.lastFpsCalculation = {
|
|
366
|
+
...this.lastFpsCalculation,
|
|
367
|
+
frameCount: this.lastFpsCalculation.frameCount + 1,
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
/** Complete the current frame and schedule the next automatic frame when configured. */
|
|
372
|
+
finishFrame() {
|
|
373
|
+
const currentFrameActions = this.frameActions;
|
|
374
|
+
this.frameActions = [];
|
|
375
|
+
this.roomConnection?.sendMessage({
|
|
376
|
+
type: P2pLockStepMessageType.Frame,
|
|
377
|
+
actions: currentFrameActions,
|
|
378
|
+
});
|
|
379
|
+
this.dispatch(new ControllerFrameEvent({
|
|
380
|
+
detail: currentFrameActions,
|
|
381
|
+
}));
|
|
382
|
+
this.frameTickReady = false;
|
|
383
|
+
this.calculateFps();
|
|
384
|
+
if (this.frameMs) {
|
|
385
|
+
this.timeoutId = globalThis.setTimeout(() => {
|
|
386
|
+
this.frameTickReady = true;
|
|
387
|
+
this.maybeFinishFrame();
|
|
388
|
+
}, this.frameMs);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
/** Complete a frame when this host has reached its configured readiness conditions. */
|
|
392
|
+
maybeFinishFrame() {
|
|
393
|
+
if (!this.isHost()) {
|
|
394
|
+
this.debugLog('maybeFinishFrame skipped because this client is not host');
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
const clientsReady = this.singleplayer ||
|
|
398
|
+
this.roomConnection?.getConnectedClientIds().every((clientId) => {
|
|
399
|
+
return this.clientsResponded[clientId];
|
|
400
|
+
});
|
|
401
|
+
if (!this.frameTickReady || !clientsReady) {
|
|
402
|
+
this.debugLog(`maybeFinishFrame waiting: frameTickReady=${this.frameTickReady} clientsReady=${!!clientsReady}`);
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
this.finishFrame();
|
|
406
|
+
}
|
|
407
|
+
/** Write a multiplayer debug log when debug logging is enabled. */
|
|
408
|
+
debugLog(message) {
|
|
409
|
+
log.if(!!this.params.debugMultiplayer).faint(`[multiplayer] ${message}`);
|
|
410
|
+
}
|
|
411
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@antha/multiplayer-p2p-lock-step",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Multiplayer mod for the Antha engine.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"vir",
|
|
7
|
+
"antha",
|
|
8
|
+
"WebRTC",
|
|
9
|
+
"signal server",
|
|
10
|
+
"multiplayer",
|
|
11
|
+
"gaming"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://github.com/electrovir/antha",
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/electrovir/antha/issues"
|
|
16
|
+
},
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/electrovir/antha.git"
|
|
20
|
+
},
|
|
21
|
+
"license": "(MIT OR CC0-1.0)",
|
|
22
|
+
"author": {
|
|
23
|
+
"name": "electrovir",
|
|
24
|
+
"url": "https://github.com/electrovir"
|
|
25
|
+
},
|
|
26
|
+
"sideEffects": false,
|
|
27
|
+
"type": "module",
|
|
28
|
+
"main": "dist/index.js",
|
|
29
|
+
"module": "dist/index.js",
|
|
30
|
+
"types": "dist/index.d.ts",
|
|
31
|
+
"scripts": {
|
|
32
|
+
"compile": "virmator compile",
|
|
33
|
+
"docs": "virmator docs",
|
|
34
|
+
"test": "virmator test web",
|
|
35
|
+
"test:coverage": "npm test coverage",
|
|
36
|
+
"test:docs": "virmator docs check"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@augment-vir/assert": "^31.73.1",
|
|
40
|
+
"@augment-vir/common": "^31.73.1",
|
|
41
|
+
"date-vir": "^8.5.0",
|
|
42
|
+
"typed-event-target": "^4.3.1"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@augment-vir/test": "^31.73.1",
|
|
46
|
+
"@web/dev-server-esbuild": "^1.0.5",
|
|
47
|
+
"@web/test-runner": "^0.20.2",
|
|
48
|
+
"@web/test-runner-playwright": "^0.11.1",
|
|
49
|
+
"istanbul-smart-text-reporter": "^1.1.5"
|
|
50
|
+
},
|
|
51
|
+
"peerDependencies": {
|
|
52
|
+
"@antha/multiplayer-core": "^0.0.1"
|
|
53
|
+
},
|
|
54
|
+
"engines": {
|
|
55
|
+
"node": ">=22"
|
|
56
|
+
},
|
|
57
|
+
"publishConfig": {
|
|
58
|
+
"access": "public"
|
|
59
|
+
}
|
|
60
|
+
}
|