" +
107 | this.model.history.map(item => item.html).join(" ");
108 | textOut.scrollTop = Math.max(10000, textOut.scrollHeight);
109 | }
110 | }
111 |
112 | Multisynq.Session.join({
113 | appId: "io.codepen.multisynq.chat",
114 | apiKey: "234567_Paste_Your_Own_API_Key_Here_7654321",
115 | name: "public",
116 | password: "none",
117 | model: ChatModel,
118 | view: ChatView
119 | });
--------------------------------------------------------------------------------
/examples/hello_typescript/public/multisynq.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/client/teatime/src/node-html.js:
--------------------------------------------------------------------------------
1 | import urlOptions from "./node-urlOptions";
2 | import { toBase64url } from "./hashing";
3 |
4 | // this is the default App.messageFunction
5 | export function showMessageInConsole(msg, options = {}) {
6 | const level = options.level;
7 | console.log(`${level === 'status' ? "" : (level + ": ")} ${msg}`);
8 | }
9 |
10 | export function displayError(msg, options={}) {
11 | return msg && App.showMessage(msg, { ...options, level: 'error' });
12 | }
13 |
14 | export function displayWarning(msg, options={}) {
15 | return msg && App.showMessage(msg, { ...options, level: 'warning' });
16 | }
17 |
18 | export function displayStatus(msg, options={}) {
19 | return msg && App.showMessage(msg, { ...options, level: 'status' });
20 | }
21 |
22 | export function displayAppError(where, error, level = "error") {
23 | console.error(`Error during ${where}`, error);
24 | const userStack = (error.stack || '').split("\n").filter(l => !l.match(/multisynq-.*\.min.js/)).join('\n');
25 | App.showMessage(`Error during ${where}: ${error.message}\n\n${userStack}`, {
26 | level,
27 | duration: level === "error" ? 10000 : undefined,
28 | stopOnFocus: true,
29 | });
30 | }
31 |
32 | export const App = {
33 | get libName() { return "Multisynq" },
34 |
35 | sessionURL: null,
36 | root: false, // root for messages, the sync spinner, and the info dock (defaults to document.body)
37 | sync: false, // whether to show the sync spinner while starting a session, or catching up
38 | messages: false, // whether to show status messages (e.g., as toasts)
39 |
40 | // the following can take a DOM element, an element ID, or false (to suppress)
41 | badge: false, // the two-colour session badge and 5-letter moniker
42 | stats: false, // the frame-by-frame stats display
43 | qrcode: false,
44 |
45 | // make a fancy collapsible dock of info widgets (currently badge, qrcode, stats).
46 | // disable any widget by setting e.g. { stats: false } in the options.
47 | makeWidgetDock() { },
48 |
49 | // build widgets in accordance with latest settings for root, badge, stats, and qrcode.
50 | // called internally immediately after a session is established.
51 | // can be called by an app at any time, to take account of changes in the settings.
52 | makeSessionWidgets() { },
53 |
54 | // make a canvas painted with the qr code for the currently set sessionURL (if there is one).
55 | makeQRCanvas() { return null; },
56 |
57 | clearSessionMoniker() { },
58 |
59 | showSyncWait(_bool) { },
60 |
61 | // messageFunction(msg, options) - where options from internally generated messages will include { level: 'status' | 'warning' | 'error' }
62 | messageFunction: showMessageInConsole,
63 |
64 | showMessage(msg, options={}) {
65 | // thin layer on top of messageFunction, to discard messages if there's nowhere
66 | // (or no permission) to show them
67 | if (urlOptions.nomessages || App.root === false || App.messages === false || !App.messageFunction) {
68 | if (options.level === "warning") console.warn(msg);
69 | if (options.level === "error") console.error(msg);
70 | return null;
71 | }
72 |
73 | return App.messageFunction(msg, options);
74 | },
75 |
76 | // this is also used in prerelease.js [or is it?]
77 | isMultisynqHost(hostname) {
78 | return hostname.endsWith("multisynq.io")
79 | || ["localhost", "127.0.0.1", "[::1]"].includes(hostname)
80 | || hostname.endsWith("ngrok.io");
81 | },
82 |
83 | // sanitized session URL (always without @user:password and #hash, and without query if not same-origin as multisynq.io)
84 | referrerURL() {
85 | return "http://localhost/node.html";
86 | },
87 |
88 | // session name is typically `${app}/${fragment}` where
89 | // "app" is constant and "fragment" comes from this autoSession
90 | autoSession(options = { key: 'q' }) {
91 | if (typeof options === "string") options = { key: options };
92 | if (!options) options = {};
93 | const key = options.key || 'q';
94 | let fragment = urlOptions[key] || '';
95 | if (fragment) try { fragment = decodeURIComponent(fragment); } catch (ex) { /* ignore */ }
96 | // if not found, create random fragment
97 | else {
98 | fragment = Math.floor(Math.random() * 36**10).toString(36);
99 | console.warn(`no ${App.libName} session name provided, using "${fragment}"`);
100 | }
101 | if (urlOptions.has("debug", "session")) console.log(`${App.libName}.App.autoSession: "${fragment}"`);
102 | // return Promise for future-proofing
103 | const retVal = Promise.resolve(fragment);
104 | // warn about using it directly
105 | retVal[Symbol.toPrimitive] = () => {
106 | console.warn(`Deprecated: ${App.libName}.App.autoSession() return value used directly. It returns a promise now!`);
107 | return fragment;
108 | };
109 | return retVal;
110 | },
111 |
112 | autoPassword(options = { key: 'pw' }) {
113 | const key = options.key || 'pw';
114 | let password = urlOptions[key] || '';
115 | // create random password if none provided
116 | if (!password) {
117 | const buffer = require('crypto').randomBytes(16); // eslint-disable-line global-require
118 | password = toBase64url(buffer);
119 | console.warn(`no ${App.libName} session password provided, using "${password}"`);
120 | }
121 | if (urlOptions.has("debug", "session")) console.log(`${App.libName}.App.autoPassword: "${password}"`);
122 | // return Promise for future-proofing
123 | const retVal = Promise.resolve(password);
124 | // warn about using it directly
125 | retVal[Symbol.toPrimitive] = () => {
126 | console.warn(`Deprecated: ${App.libName}.App.autoPassword() return value used directly. It returns a promise now!`);
127 | return password;
128 | };
129 | return retVal;
130 | },
131 | };
132 |
--------------------------------------------------------------------------------
/client/teatime/src/realms.js:
--------------------------------------------------------------------------------
1 | import urlOptions from "./_URLOPTIONS_MODULE_"; // eslint-disable-line import/no-unresolved
2 | import { viewDomain } from "./domain";
3 |
4 |
5 | let DEBUG = {
6 | get subscribe() {
7 | // replace with static value on first call
8 | DEBUG = { subscribe: urlOptions.has("debug", "subscribe", false) };
9 | return DEBUG.subscribe;
10 | }
11 | };
12 |
13 |
14 | class ModelRealm {
15 | constructor(vm) {
16 | /** @type import('./vm').default */
17 | this.vm = vm;
18 | }
19 | register(model) {
20 | return this.vm.registerModel(model);
21 | }
22 | deregister(model) {
23 | this.vm.deregisterModel(model.id);
24 | }
25 | publish(event, data, scope) {
26 | this.vm.publishFromModel(scope, event, data);
27 | }
28 | subscribe(model, scope, event, methodName) {
29 | if (DEBUG.subscribe) console.log(`Model.subscribe("${scope}:${event}", ${model} ${(""+methodName).replace(/\([\s\S]*/, '')})`);
30 | return this.vm.addSubscription(model, scope, event, methodName);
31 | }
32 | unsubscribe(model, scope, event, methodName='*') {
33 | if (DEBUG.subscribe) console.log(`Model.unsubscribe(${scope}:${event}", ${model} ${(""+methodName).replace(/\([\s\S]*/, '')})`);
34 | this.vm.removeSubscription(model, scope, event, methodName);
35 | }
36 | unsubscribeAll(model) {
37 | if (DEBUG.subscribe) console.log(`Model.unsubscribeAll(${model} ${model.id})`);
38 | this.vm.removeAllSubscriptionsFor(model);
39 | }
40 |
41 | future(model, tOffset, methodName, methodArgs) {
42 | if (__currentRealm && __currentRealm.equal(this)) {
43 | return this.vm.future(model, tOffset, methodName, methodArgs);
44 | }
45 | throw Error(`Model.future() called from outside: ${model}`);
46 | }
47 |
48 | cancelFuture(model, methodOrMessage) {
49 | if (__currentRealm && __currentRealm.equal(this)) {
50 | return this.vm.cancelFuture(model, methodOrMessage);
51 | }
52 | throw Error(`Model.cancelFuture() called from outside: ${model}`);
53 | }
54 |
55 | random() {
56 | return this.vm.random();
57 | }
58 |
59 | now() {
60 | return this.vm.time;
61 | }
62 |
63 | equal(otherRealm) {
64 | return otherRealm instanceof ModelRealm && otherRealm.vm === this.vm;
65 | }
66 |
67 | isViewRealm() { return false; }
68 | }
69 |
70 | class ViewRealm {
71 | constructor(vm) {
72 | /** @type import('./vm').default */
73 | this.vd = viewDomain;
74 | this.vm = vm; // if vm !== controller.vm, this view is invalid
75 | this.controller = vm.controller; // controller stays the same even across reconnects
76 | }
77 |
78 | valid() {
79 | return this.vm === this.controller.vm;
80 | }
81 |
82 | register(view) {
83 | return viewDomain.register(view);
84 | }
85 |
86 | deregister(view) {
87 | viewDomain.deregister(view);
88 | }
89 |
90 | publish(event, data, scope) {
91 | this.vm.publishFromView(scope, event, data);
92 | }
93 | subscribe(event, subscriberId, callback, scope, handling="queued") {
94 | if (DEBUG.subscribe) console.log(`View[${subscriberId}].subscribe("${scope}:${event}" ${callback ? callback.name || (""+callback).replace(/\([\s\S]*/, '') : ""+callback} [${handling}])`);
95 | viewDomain.addSubscription(scope, event, subscriberId, callback, handling);
96 | }
97 | unsubscribe(event, subscriberId, callback=null, scope) {
98 | if (DEBUG.subscribe) console.log(`View[${subscriberId}].unsubscribe("${scope}:${event}" ${callback ? callback.name || (""+callback).replace(/\([\s\S]*/, '') : "*"})`);
99 | viewDomain.removeSubscription(scope, event, subscriberId, callback);
100 | }
101 | unsubscribeAll(subscriberId) {
102 | if (DEBUG.subscribe) console.log(`View[${subscriberId}].unsubscribeAll()`);
103 | viewDomain.removeAllSubscriptionsFor(subscriberId);
104 | }
105 |
106 | future(view, tOffset) {
107 | const vm = this.vm;
108 | return new Proxy(view, {
109 | get(_target, property) {
110 | if (typeof view[property] === "function") {
111 | const methodProxy = new Proxy(view[property], {
112 | apply(_method, _this, args) {
113 | setTimeout(() => { if (view.id) inViewRealm(vm, () => view[property](...args), true); }, tOffset);
114 | }
115 | });
116 | return methodProxy;
117 | }
118 | throw Error("Tried to call " + property + "() on future of " + Object.getPrototypeOf(view).constructor.name + " which is not a function");
119 | }
120 | });
121 | }
122 |
123 | random() {
124 | return Math.random();
125 | }
126 |
127 | now() {
128 | return this.vm.time;
129 | }
130 |
131 | externalNow() {
132 | return this.controller.reflectorTime;
133 | }
134 |
135 | extrapolatedNow() {
136 | return this.controller.extrapolatedTime;
137 | }
138 |
139 | isSynced() {
140 | return !!this.controller.synced;
141 | }
142 |
143 | equal(otherRealm) {
144 | return otherRealm instanceof ViewRealm && otherRealm.vm === this.vm;
145 | }
146 |
147 | isViewRealm() { return true; }
148 | }
149 |
150 | let __currentRealm = null;
151 |
152 | /** @returns {ModelRealm | ViewRealm} */
153 | export function currentRealm(errorIfNoRealm="Tried to execute code that requires realm outside of realm.") {
154 | if (!__currentRealm && errorIfNoRealm) {
155 | throw Error(errorIfNoRealm);
156 | }
157 | return __currentRealm;
158 | }
159 |
160 | export function inModelRealm(vm, callback) {
161 | if (__currentRealm !== null) {
162 | throw Error("Can't switch realms from inside realm");
163 | }
164 | try {
165 | __currentRealm = new ModelRealm(vm);
166 | return callback();
167 | } finally {
168 | __currentRealm = null;
169 | }
170 | }
171 |
172 | export function inViewRealm(vm, callback, force=false) {
173 | if (__currentRealm !== null && !force) {
174 | throw Error("Can't switch realms from inside realm");
175 | }
176 | const prevRealm = __currentRealm;
177 | try {
178 | __currentRealm = new ViewRealm(vm);
179 | return callback();
180 | } finally {
181 | __currentRealm = prevRealm;
182 | }
183 | }
184 |
--------------------------------------------------------------------------------
/client/teatime/index.js:
--------------------------------------------------------------------------------
1 | // official exports
2 | export { default as Model } from "./src/model";
3 | export { default as View } from "./src/view";
4 | export { default as Data } from "./src/data";
5 | export { Session, Constants, deprecatedStartSession as startSession } from "./src/session";
6 | export { App } from "./src/_HTML_MODULE_"; // eslint-disable-line import/no-unresolved
7 |
8 | // unofficial exports
9 | export { default as Controller, MULTISYNQ_VERSION as VERSION } from "./src/controller";
10 | export { currentRealm } from "./src/realms";
11 | export { Messenger } from "./src/_MESSENGER_MODULE_"; // eslint-disable-line import/no-unresolved
12 |
13 | // putting event documentation here because JSDoc errors when parsing controller.js at the moment
14 |
15 | /**
16 | * **Published when a new user enters the session, or re-enters after being temporarily disconnected.**
17 | *
18 | * This is a model-only event, meaning views can not handle it directly.
19 | *
20 | * The event's payload will be the joining view's `viewId`. However, if
21 | * `viewData` was passed to [Session.join]{@link Session.join}, the event payload will
22 | * be an object `{viewId, viewData}`.
23 | *
24 | * **Note:** Each `"view-join"` event is guaranteed to be followed by a [`"view-exit"` event]{@link event:view-exit}
25 | * when that user leaves the session, or when the session is cold-started from a persistent snapshot.
26 | *
27 | * Hint: In the view, you can access the local viewId as [this.viewId]{@link View#viewId}, and compare
28 | * it to the argument in this event, e.g. to associate the view side with an avatar on the model side.
29 | *
30 | * @example
31 | * class MyModel extends Multisynq.Model {
32 | * init() {
33 | * this.userData = {};
34 | * this.subscribe(this.sessionId, "view-join", this.addUser);
35 | * this.subscribe(this.sessionId, "view-exit", this.deleteUser);
36 | * }
37 | * addUser(viewId) {
38 | * this.userData[viewId] = { start: this.now() };
39 | * this.publish(this.sessionId, "user-added", viewId);
40 | * }
41 | * deleteUser(viewId) {
42 | * const time = this.now() - this.userData[viewId].start;
43 | * delete this.userData[viewId];
44 | * this.publish(this.sessionId, "user-deleted", {viewId, time});
45 | * }
46 | * }
47 | * MyModel.register("MyModel");
48 | * class MyView extends Multisynq.View {
49 | * constructor(model) {
50 | * super(model);
51 | * for (const viewId of Object.keys(model.userData)) this.userAdded(viewId);
52 | * this.subscribe(this.sessionId, "user-added", this.userAdded);
53 | * this.subscribe(this.sessionId, "user-deleted", this.userDeleted);
54 | * }
55 | * userAdded(viewId) {
56 | * console.log(`${ this.viewId === viewId ? "local" : "remote"} user ${viewId} came in`);
57 | * }
58 | * userDeleted({viewId, time}) {
59 | * console.log(`${ this.viewId === viewId ? "local" : "remote"} user ${viewId} left after ${time / 1000} seconds`);
60 | * }
61 | * }
62 | * @event view-join
63 | * @property {String} scope - [this.sessionId]{@link Model#sessionId}
64 | * @property {String} event - `"view-join"`
65 | * @property {String|Object} viewId - the joining user's local `viewId`, or an object `{viewId, viewData}`
66 | * @public
67 | */
68 |
69 | /**
70 | * **Published when a user leaves the session, or is disconnected.**
71 | *
72 | * This is a model-only event, meaning views can not handle it directly.
73 | *
74 | * This event will be published when a view tab is closed, or is disconnected due
75 | * to network interruption or inactivity. A view is deemed to be inactive if
76 | * 10 seconds pass without an execution of the Multisynq [main loop]{@link Session.join};
77 | * this will happen if, for example, the browser tab is hidden. As soon as the tab becomes
78 | * active again the main loop resumes, and the session will reconnect, causing
79 | * a [`"view-join"` event]{@link event:view-join} to be published. The `viewId`
80 | * will be the same as before.
81 | *
82 | * If `viewData` was passed to [Session.join]{@link Session.join}, the event payload will
83 | * be an object `{viewId, viewData}`.
84 | *
85 | * **Note:** when starting a new session from a snapshot, `"view-exit"` events will be
86 | * generated for all of the previous users before the first [`"view-join"` event]{@link event:view-join}
87 | * of the new session.
88 | *
89 | * #### Example
90 | * See [`"view-join"` event]{@link event:view-join}
91 | * @event view-exit
92 | * @property {String} scope - [this.sessionId]{@link Model#sessionId}
93 | * @property {String} event - `"view-exit"`
94 | * @property {String|Object} viewId - the user's `viewId`, or an object `{viewId, viewData}`
95 | * @public
96 | */
97 |
98 | /**
99 | * **Published when the session backlog crosses a threshold.** (see {@link View#externalNow} for backlog)
100 | *
101 | * This is a non-synchronized view-only event.
102 | *
103 | * If this is the main session, it also indicates that the scene was revealed (if data is `true`)
104 | * or hidden behind the overlay (if data is `false`).
105 | * ```js
106 | * this.subscribe(this.viewId, "synced", this.handleSynced);
107 | * ```
108 | * The default loading overlay is a CSS-only animation.
109 | * You can either customize the appearance, or disable it completely and show your own in response to the `"synced"` event.
110 | *
111 | * **Customizing the default loading animation**
112 | *
113 | * The overlay is structured as
114 | * ```html
115 | *
116 | *
117 | *
118 | * ```
119 | * so you can customize the appearance via CSS using
120 | * ```css
121 | * #multisynq_spinnerOverlay { ... }
122 | * #multisynq_loader:before { ... }
123 | * #multisynq_loader { ... }
124 | * #multisynq_loader:after { ... }
125 | * ```
126 | * where the _overlay_ is the black background and the _loader_ with its `:before` and `:after` elements is the three animating dots.
127 | *
128 | * The overlay `
10 |
11 |
12 |
13 | ## **Try it out!**
14 | The first thing to do is click or scan the QR code above. This will launch a new Codepen instance of this session. If you compare the two sessions, you will see that the animated simulations are identical. The balls all move and bounce exactly the same. You can stop and start any ball by clicking on it, which will start or stop it in every session. You can't stop the rounded rectangle - it is just like a regular ball but ignores user actions. Any reader of this documentation can start or stop the balls while they are animating. You may notice that this is happening. It just means there is someone else out there working with the tutorial at the same time as you.
15 |
16 | There are three things we will learn here.
17 |
18 | 1. Creating a simulation model.
19 | 2. Creating an interactive view.
20 | 3. How to safely communicate between them.
21 |
22 |
23 | ## Simple Animation Model
24 |
25 | Our application uses two Multisynq Model subclasses, MyModel and BallModel. Both these classes need to be registered with Multisynq.
26 |
27 | In addition, this app makes use of [Multisynq.Constants]{@link Constants}.
28 | Although models must not use global variables, global constants are fine.
29 | To ensure that all users in a session use the same value of these constants, add them to the Multisynq.Constants object.
30 | Multisynq.Constants is recursively frozen once a session has started, to avoid accidental modification.
31 | Here we assign Multisynq.Constants into the variable Q as a shorthand.
32 |
33 | ```
34 | const Q = Multisynq.Constants;
35 | Q.BALL_NUM = 25; // how many balls do we want?
36 | Q.STEP_MS = 1000 / 30; // bouncing ball tick interval in ms
37 | Q.SPEED = 10; // max speed on a dimension, in units/s
38 | ```
39 |
40 | MyModel is the root model, and is therefore what will be passed into [Multisynq.Session.join]{@link Session.join}.
41 | In this app, MyModel also creates and stores the BallModel objects, holding them in the array MyModel.children.
42 |
43 | A BallModel is the model for a shaped, colored, bouncing ball. The model itself has no direct say in the HTML that will be used to display the ball. For the shape, for example, the model records just a string - either `'circle'` or `'roundRect'` - that the view will use to generate a visual element that (by the workings of the app's CSS) will be displayed as the appropriate shape. The BallModel also initializes itself with a random color, position, and speed vector.
44 |
45 | ```this.subscribe(this.id, 'touch-me', this.startStop);```
46 |
47 | The BallModel [subscribes]{@link Model#subscribe} to the `'touch-me'` event, to which it will respond by stopping or restarting its motion. Each BallModel object individually subscribes to this event type, but only for events that are published using the BallModel's own ID as scope. Each ball's dedicated BallView object keeps a record of its model's ID, for use when publishing the `'touch-me'` events in response to user touches.
48 |
49 | ```this.future(Q.STEP_MS).step();```
50 |
51 | Having completed its initialization, the BallModel [schedules]{@link Model#future} the first invocation of its own `step()` method. This is the same pattern as seen in the previous tutorial; `step()` will continue the stepping by re-scheduling itself each time.
52 |
53 | Worth noting here is that the step invocation applies just to one ball, with each BallModel taking care of its own update tick. That may seem like a lot of future messages for the system to handle (25 balls ticking at 30Hz will generate 750 messages per second) - but future messages are very efficient, involving little overhead beyond the basic method invocation.
54 |
55 | ```
56 | BallModel.step() {
57 | if (this.alive) this.moveBounce();
58 | this.future(Q.STEP_MS).step();
59 | }
60 | ```
61 |
62 | If the `alive` flag is set, the `step()` function will call `moveBounce()`. In any case, `step()` schedules the next step, the appropriate number of milliseconds in the future.
63 |
64 | ```
65 | BallModel.moveBounce() {
66 | const [x, y] = this.pos;
67 | if (x<=0 || x>=1000 || y<=0 || y>=1000)
68 | this.speed = this.randomSpeed();
69 | this.moveTo([x + this.speed[0], y + this.speed[1]]);
70 | }
71 | ```
72 |
73 | `BallModel.moveBounce()` has the job of updating the position of a ball object, including bouncing off container walls when necessary. It embodies a simple strategy: if the ball is found to be outside the container bounds, `moveBounce()` replaces the ball's speed with a new speed vector `BallModel.randomSpeed()`. Because the new speed is random, it might turn out to take the ball a little further out of bounds - but in that case the ball will just try again, with another random speed, on the next `moveBounce`.
74 |
75 | ```
76 | randomSpeed() {
77 | const xs = this.random() * 2 - 1;
78 | const ys = this.random() * 2 - 1;
79 | const speedScale = Q.SPEED / (Math.sqrt(xs*xs + ys*ys));
80 | return [xs * speedScale, ys * speedScale];
81 | }
82 | ```
83 |
84 | The generation of new speed vectors is an example of our use of a replicated random-number generator. Every instance of this session will compute exactly the same sequence of random numbers. Therefore, when a ball bounces, every instance will come up with exactly the same new speed.
85 |
86 | ## Simple Animation View
87 |
88 | Like the Model, the View in this app comprises two classes: MyView and BallView.
89 |
90 | ### MyView
91 |
92 | MyView.constructor(model) will be called when an app session instance starts up. It is passed the MyModel object as an argument. The constructor's job is to build the visual representation of the model for this instance of the session. The root of that representation, in this app, is a "div" element that will serve as the balls' container.
93 |
94 | ```model.children.forEach(child => this.attachChild(child));```
95 |
96 | The MyModel has children - the BallModel objects - for which MyView must also create a visual representation. It does so by accessing the model's children collection and creating a new view object for each child.
97 |
98 | Note that although it is fine for the view to access the model directly here to read its state - in this case, the children - the view **MUST NOT** modify the model (or its child models) in any way.
99 |
100 | ```
101 | MyView.attachChild(child) {
102 | this.element.appendChild(new BallView(child).element);
103 | }
104 | ```
105 |
106 | For each child BallModel a new BallView object is created. The BallView creates a document element to serve as the visual representation of the bouncing ball; the MyView object adds the element for each BallView as a child of its own element, the containing div.
107 |
108 | MyView also listens for "resize" events from the browser, and uses them to set a suitable size for the view by setting its scale (which also sets the scale for the children - i.e., the balls). When there are multiple users watching multiple instances of this app on browser windows of different sizes, the rescaling ensures that everyone still sees the same overall scene.
109 |
110 | ```
111 | MyView.detach() {
112 | super.detach();
113 | let child;
114 | while (child = this.element.firstChild) this.element.removeChild(child);
115 | }
116 | ```
117 |
118 | When a session instance is shut down (including the reversible shutdown that happens if a tab is hidden for ten seconds or more), its root view is destroyed. If the instance is re-started, a completely new root view will be built. Therefore, on shutdown, the root view is sent `detach` to give it the chance to clean up its resources. MyView handles this by destroying all the child views that it has added to the `"animation"` `div` element during this session.
119 |
120 | ### BallView
121 |
122 | The BallView tracks the associated BallModel.
123 |
124 | BallView constructs a document element based on the type and color properties held by the BallModel, and sets the element's initial position using the model's pos property.
125 |
126 | ```this.subscribe(model.id, { event: 'pos-changed', handling: "oncePerFrame" }, this.move);```
127 |
128 | The BallView subscribes to the 'pos-changed' event, which the BallModel publishes each time it updates the ball position. Like the 'touch-me' event, these events are sent in the scope of the individual BallModel's ID. No other ball's model or view will pay any attention to the events, which makes their distribution highly efficient. As a further efficiency consideration, the `handling: "oncePerFrame"` flag is used to ensure that even if multiple events for a given ball arrive within the same rendering frame, only one (the latest) will be passed to the subscribed handler.
129 |
130 | ```this.enableTouch();```
131 |
132 | ```
133 | BallView.enableTouch() {
134 | const el = this.element;
135 | if (TOUCH) el.ontouchstart = start => {
136 | start.preventDefault();
137 | this.publish(el.id, 'touch-me');
138 | }; else el.onmousedown = start => {
139 | start.preventDefault();
140 | this.publish(el.id, 'touch-me');
141 | };
142 | }
143 | ```
144 | BallView.enableTouch sets up the BallView element to publish a 'touch-me' event when the element is clicked on.
145 | The BallModel subscribes to the 'touch-me' event and toggles the ball motion on and off.
146 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2019-2025 Croquet Labs
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/docs/tutorials/5 3D Animation/script.js:
--------------------------------------------------------------------------------
1 | // Multisynq Tutorial 5
2 | // 3D Animation Demo
3 | // Croquet Labs (C) 2025
4 |
5 | const Q = Multisynq.Constants;
6 | // Pseudo-globals
7 | Q.NUM_BALLS = 12; // number of bouncing balls
8 | Q.BALL_RADIUS = 0.25;
9 | Q.CENTER_SPHERE_RADIUS = 1.5; // a large sphere to bounce off
10 | Q.CENTER_SPHERE_NEUTRAL = 0xaaaaaa; // color of sphere before any bounces
11 | Q.CONTAINER_SIZE = 4; // edge length of invisible containing cube
12 | Q.STEP_MS = 1000 / 20; // step time in ms
13 | Q.SPEED = 1.5; // max speed on a dimension, in units/s
14 |
15 | class MyModel extends Multisynq.Model {
16 |
17 | init(options) {
18 | // force init 14
19 | super.init(options);
20 | this.centerSphereRadius = Q.CENTER_SPHERE_RADIUS;
21 | this.centerSpherePos = [0, 0, -Q.CONTAINER_SIZE/2]; // embedded half-way into the back wall
22 | this.children = [];
23 | for (let i = 0; i < Q.NUM_BALLS; i++) this.children.push(BallModel.create({ sceneModel: this }));
24 | this.subscribe(this.id, 'sphere-drag', this.centerSphereDragged); // someone is dragging the center sphere
25 | this.subscribe(this.id, 'reset', this.resetCenterSphere); // someone has clicked the center sphere
26 | }
27 |
28 | centerSphereDragged(pos) {
29 | this.centerSpherePos = pos;
30 | this.publish(this.id, 'sphere-pos-changed', pos);
31 | }
32 |
33 | resetCenterSphere() {
34 | this.publish(this.id, 'recolor-center-sphere', Q.CENTER_SPHERE_NEUTRAL);
35 | }
36 | }
37 |
38 | MyModel.register("MyModel");
39 |
40 | class BallModel extends Multisynq.Model {
41 |
42 | init(options={}) {
43 | super.init();
44 | this.sceneModel = options.sceneModel;
45 |
46 | const rand = range => Math.floor(range * Math.random()); // integer random less than range
47 | this.radius = Q.BALL_RADIUS;
48 | this.color = `hsl(${rand(360)},${rand(50)+50}%,50%)`;
49 | this.resetPosAndSpeed();
50 |
51 | this.subscribe(this.sceneModel.id, 'reset', this.resetPosAndSpeed); // the reset event will be sent using the model id as scope
52 |
53 | this.future(Q.STEP_MS).step();
54 | }
55 |
56 | // a ball resets itself by positioning at the center of the center-sphere
57 | // and giving itself a randomized velocity
58 | resetPosAndSpeed() {
59 | const srand = range => range * 2 * (Math.random() - 0.5); // float random between -range and +range
60 | this.pos = this.sceneModel.centerSpherePos.slice();
61 | const speedRange = Q.SPEED * Q.STEP_MS / 1000; // max speed per step
62 | this.speed = [ srand(speedRange), srand(speedRange), srand(speedRange) ];
63 | }
64 |
65 | step() {
66 | this.moveBounce();
67 | this.future(Q.STEP_MS).step(); // arrange to step again
68 | }
69 |
70 | moveBounce() {
71 | this.bounceOffContainer();
72 | this.bounceOffCenterSphere();
73 | const pos = this.pos;
74 | const speed = this.speed;
75 | this.moveTo([ pos[0] + speed[0], pos[1] + speed[1], pos[2] + speed[2] ]);
76 | }
77 |
78 | bounceOffCenterSphere() {
79 | const pos = this.pos;
80 | const spherePos = this.sceneModel.centerSpherePos; // a model is allowed to read state of another model
81 | const distFromCenter = posArray => {
82 | let sq = 0;
83 | posArray.forEach((p, i) => {
84 | const diff = spherePos[i] - p;
85 | sq += diff * diff;
86 | });
87 | return Math.sqrt(sq);
88 | };
89 | const speed = this.speed;
90 | const threshold = Q.CENTER_SPHERE_RADIUS + this.radius;
91 | const distBefore = distFromCenter(pos);
92 | const distAfter = distFromCenter([ pos[0] + speed[0], pos[1] + speed[1], pos[2] + speed[2] ]);
93 | if (distBefore >= threshold && distAfter < threshold) {
94 | const unitToCenter = pos.map((p, i) => (spherePos[i] - p)/distBefore);
95 | const speedAcrossBoundary = speed[0] * unitToCenter[0] + speed[1] * unitToCenter[1] + speed[2] * unitToCenter[2];
96 | this.speed = this.speed.map((v, i) => v - 2 * speedAcrossBoundary * unitToCenter[i]);
97 | this.publish(this.sceneModel.id, 'recolor-center-sphere', this.color);
98 | }
99 | }
100 |
101 | bounceOffContainer() {
102 | const pos = this.pos;
103 | const speed = this.speed;
104 | pos.forEach((p, i) => {
105 | if (Math.abs(p) > Q.CONTAINER_SIZE/2 - this.radius) speed[i] = Math.abs(speed[i]) * -Math.sign(p);
106 | });
107 | }
108 |
109 | // the ball moves by recording its new position, then publishing that
110 | // position in an event that its view is expected to have subscribed to
111 | moveTo(pos) {
112 | this.pos = pos;
113 | this.publish(this.id, 'pos-changed', this.pos);
114 | }
115 | }
116 |
117 | BallModel.register("BallModel");
118 |
119 | // one-time function to set up Three.js, with a simple lit scene
120 | function setUpScene() {
121 | const scene = new THREE.Scene();
122 | scene.add(new THREE.AmbientLight(0xffffff, 0.5));
123 | const light = new THREE.PointLight(0xffffff, 1);
124 | light.position.set(50, 50, 50);
125 | scene.add(light);
126 |
127 | const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 10000);
128 | camera.position.set(0, 0, 4);
129 | const threeCanvas = document.getElementById("three");
130 | const renderer = new THREE.WebGLRenderer({ canvas: threeCanvas });
131 | renderer.setClearColor(0xaa4444);
132 |
133 | function onWindowResize() {
134 | camera.aspect = window.innerWidth / window.innerHeight;
135 | camera.updateProjectionMatrix();
136 | renderer.setSize(window.innerWidth, window.innerHeight);
137 | }
138 | window.addEventListener('resize', onWindowResize, false);
139 | onWindowResize();
140 |
141 | // utility objects for managing pointer interaction
142 | const raycaster = new THREE.Raycaster();
143 | let dragObject = null;
144 | let dragged;
145 | const dragOffset = new THREE.Vector3();
146 | const dragPlane = new THREE.Plane();
147 | const mouse = new THREE.Vector2();
148 | const THROTTLE_MS = 1000 / 20; // minimum delay between pointer-move events that we'll handle
149 | let lastTime = 0;
150 | function setMouse(event) {
151 | mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
152 | mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
153 | }
154 |
155 | function onPointerDown(event) {
156 | event.preventDefault();
157 | setMouse(event); // convert from window coords to relative (-1 to +1 on each of x, y)
158 | raycaster.setFromCamera(mouse, camera);
159 | const intersects = raycaster.intersectObjects(scene.children);
160 | for (let i = 0; i < intersects.length && !dragObject; i++) {
161 | const intersect = intersects[i];
162 | const threeObj = intersect.object;
163 | if (threeObj.q_draggable) { // a flag that we set on just the central sphere
164 | dragObject = threeObj;
165 | dragged = false; // so we can detect a non-dragging click
166 | dragOffset.subVectors(dragObject.position, intersect.point); // position relative to pointer
167 | // set up for drag in vertical plane perpendicular to camera direction
168 | dragPlane.setFromNormalAndCoplanarPoint(camera.getWorldDirection(new THREE.Vector3()), intersect.point);
169 | }
170 | }
171 | }
172 | threeCanvas.addEventListener('pointerdown', onPointerDown);
173 |
174 | function onPointerMove(event) {
175 | event.preventDefault();
176 |
177 | // ignore if there is no drag happening
178 | if (!dragObject) return;
179 |
180 | // ignore if the event is too soon after the last one
181 | if (event.timeStamp - lastTime < THROTTLE_MS) return;
182 | lastTime = event.timeStamp;
183 |
184 | const lastMouse = {...mouse};
185 | setMouse(event);
186 | // ignore if the event is too close on the screen to the last one
187 | if (Math.abs(mouse.x-lastMouse.x) < 0.01 && Math.abs(mouse.y - lastMouse.y) < 0.01) return;
188 |
189 | raycaster.setFromCamera(mouse, camera);
190 | const dragPoint = raycaster.ray.intersectPlane(dragPlane, new THREE.Vector3());
191 | dragObject.q_onDrag(new THREE.Vector3().addVectors(dragPoint, dragOffset));
192 | dragged = true; // a drag has happened (so don't treat the pointerup as a click)
193 | }
194 | threeCanvas.addEventListener('pointermove', onPointerMove);
195 |
196 | function onPointerUp(event) {
197 | event.preventDefault();
198 | if (dragObject) {
199 | if (!dragged && dragObject.q_onClick) dragObject.q_onClick();
200 | dragObject = null;
201 | }
202 | }
203 | threeCanvas.addEventListener('pointerup', onPointerUp);
204 |
205 | // function that the app must invoke when ready to render the scene
206 | // on each animation frame.
207 | function sceneRender() { renderer.render(scene, camera); }
208 |
209 | return { scene, sceneRender };
210 | }
211 |
212 | class MyView extends Multisynq.View {
213 |
214 | constructor(model) {
215 | super(model);
216 | this.sceneModel = model;
217 | const sceneSpec = setUpScene(); // { scene, sceneRender }
218 | this.scene = sceneSpec.scene;
219 | this.sceneRender = sceneSpec.sceneRender;
220 | this.centerSphere = new THREE.Mesh(
221 | new THREE.SphereGeometry(model.centerSphereRadius, 16, 16),
222 | new THREE.MeshStandardMaterial({ color: Q.CENTER_SPHERE_NEUTRAL, roughness: 0.7 }));
223 | this.centerSphere.position.fromArray(model.centerSpherePos);
224 | this.scene.add(this.centerSphere);
225 | // set Multisynq app-specific properties for handling events
226 | this.centerSphere.q_onClick = () => this.publish(model.id, 'reset');
227 | this.centerSphere.q_draggable = true;
228 | this.centerSphere.q_onDrag = posVector => this.posFromSphereDrag(posVector.toArray());
229 | this.subscribe(model.id, 'sphere-pos-changed', this.moveSphere);
230 | this.subscribe(model.id, 'recolor-center-sphere', this.recolorSphere);
231 | model.children.forEach(childModel => this.attachChild(childModel));
232 | }
233 |
234 | posFromSphereDrag(pos) {
235 | const limit = Q.CONTAINER_SIZE / 2;
236 | // constrain x and y to container (z isn't expected to be changing)
237 | [0, 1].forEach(i => { if (Math.abs(pos[i]) > limit) pos[i] = limit * Math.sign(pos[i]); });
238 | this.publish(this.sceneModel.id, 'sphere-drag', pos);
239 | }
240 |
241 | moveSphere(pos) {
242 | // this method just moves the view of the sphere
243 | this.centerSphere.position.fromArray(pos);
244 | }
245 |
246 | recolorSphere(color) {
247 | this.centerSphere.material.color.copy(new THREE.Color(color));
248 | }
249 |
250 | attachChild(childModel) {
251 | this.scene.add(new BallView(childModel).object3D);
252 | }
253 |
254 | update(time) {
255 | this.sceneRender();
256 | }
257 | }
258 |
259 | class BallView extends Multisynq.View {
260 |
261 | constructor(model) {
262 | super(model);
263 | this.object3D = new THREE.Mesh(
264 | new THREE.SphereGeometry(model.radius, 12, 12),
265 | new THREE.MeshStandardMaterial({ color: model.color })
266 | );
267 | this.move(model.pos);
268 | this.subscribe(model.id, { event: 'pos-changed', handling: 'oncePerFrame' }, this.move);
269 | }
270 |
271 | move(pos) {
272 | this.object3D.position.fromArray(pos);
273 | }
274 | }
275 |
276 | Multisynq.Session.join({
277 | appId: "io.codepen.multisynq.threed_anim",
278 | apiKey: "234567_Paste_Your_Own_API_Key_Here_7654321",
279 | name: "public",
280 | password: "none",
281 | model: MyModel,
282 | view: MyView,
283 | });
--------------------------------------------------------------------------------