Up-in-the-Air – blob

You can use Git to clone the repository via the web URL. Download snapshot (zip)
1d0d94e06fc9a00c4f33f5ddb9750567f157beae
[Up-in-the-Air] /
1 "use strict";
2 // SPDX-License-Identifier: GPL-3.0-or-later
3 /**
4  * Up in the Air
5  * – a browser game created for FediJam 2024 –
6  * https://fietkau.media/up_in_the_air
7  *
8  * Copyright (c) Julian Fietkau
9  * See README.txt for details.
10  *
11  *******************************************************************************
12  *
13  * This program is free software: you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation, either version 3 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
25  *
26  */
28 import * as THREE from 'three';
29 import { FontLoader } from 'three/addons/loaders/FontLoader.js';
30 import { TextGeometry } from 'three/addons/geometries/TextGeometry.js';
33 window['startUpInTheAirGame'] = (game) => {
35 if(!game.hasOwnProperty('deploymentOptions')) {
36   game['deploymentOptions'] = {};
37 }
38 const deploymentDefaults = {
39   'assetUrlPrefix': '',
40 };
41 for(let k in deploymentDefaults) {
42   if(!game['deploymentOptions'].hasOwnProperty(k)) {
43     game['deploymentOptions'][k] = deploymentDefaults[k];
44   }
45 }
47 game['fn'] = {};
49 game['fn'].playRandomSound = () => {
50   if(!game.view || !game.view.audioListener) {
51     return;
52   }
53   if(!game.view.lastSoundsCache) {
54     game.view.lastSoundsCache = [];
55   }
56   let index;
57   // We remember the last two notes played and make sure not to repeat one of those.
58   do {
59     index = 1 + Math.floor(Math.random() * 5);
60   } while(game.view.lastSoundsCache.includes(index));
61   game.view.lastSoundsCache.push(index);
62   if(game.view.lastSoundsCache.length > 2) {
63     game.view.lastSoundsCache.splice(0, 1);
64   }
65   let sound = new THREE.Audio(game.view.audioListener);
66   sound.setBuffer(game.assets['audio']['sound' + index + '-' + game.settings['audio']['theme']]);
67   sound.setVolume(game.settings['audio']['sounds']);
68   if(!game.view.muted && game.settings['audio']['sounds'] > 0) {
69     sound.play();
70   }
71 }
73 game['fn'].easeInOut = (val) => {
74   return -0.5 * Math.cos(val * Math.PI) + 0.5;
75 }
77 game['fn'].lerp = (start, end, progress) => {
78   return (1.0 - progress) * start + progress * end;
79 }
81 game['fn'].loadAllAssets = (renderProgressCallback) => {
82   game.assets = {};
83   game.assets.words = {
84     'thanks': ['thank you', 'thanks'],
85     'sorry': ['sorry', 'apologize'],
86     'emotion': ['blessed', 'fortunate', 'glad', 'happy', 'joyous', 'lucky', 'overjoyed', 'thankful'],
87     'verb_general': ['adore', 'appreciate', 'cherish', 'enjoy', 'like', 'love', 'treasure', 'value'],
88     'verb_person': ['admire', 'honor', 'love', 'respect', 'treasure', 'value'],
89     'trait': ['amazing', 'compassionate', 'delightful', 'genuine', 'generous', 'incredible', 'joyful', 'kind', 'passionate', 'patient', 'principled', 'refreshing', 'sweet'],
90   };
91   game.assets.wordList = [...new Set([].concat.apply([], Object.values(game.assets.words)))]; // no need to be sorted
92   game.assets.sentences = [
93     '{thanks} for always listening.',
94     '{thanks} for being there.',
95     '{thanks} for helping me when I needed it most.',
96     '{thanks} for being with me.',
97     '{thanks} for believing in me.',
98     '{thanks} for not giving up.',
99     '{thanks} for believing in me when I myself couldn’t.',
100     '{thanks} for standing by my side.',
101     '{sorry} for what I said.',
102     '{sorry} for not being there.',
103     '{sorry} for forgetting.',
104     '{sorry} for not telling you.',
105     '{sorry} for what I did.',
106     '{sorry} for back then.',
107     '{sorry} for not being honest.',
108     'Just being around you makes me feel {emotion}.',
109     'I have no words for how {emotion} you make me feel.',
110     'I always feel {emotion} in your presence.',
111     'I’m honestly {emotion}.',
112     'I feel {emotion} just for knowing you.',
113     'Every moment with you makes me feel {emotion}.',
114     'I {verb_person} you.',
115     'I {verb_person} you more than anything.',
116     'I deeply {verb_person} you.',
117     'I honestly {verb_person} you.',
118     'I really do {verb_person} you.',
119     'I {verb_general} every moment with you.',
120     'I {verb_general} the way you see the world.',
121     'I {verb_general} you the way you are.',
122     'I {verb_general} how {trait} you are.',
123     'I {verb_general} how {trait} you are.',
124     'I {verb_general} how {trait} you are.',
125     'I always {verb_general} how {trait} you are.',
126     'I deeply {verb_general} how {trait} you are.',
127     'Thinking about how {trait} you are always improves my mood.',
128     'You are the most {trait} person I know.',
129     'You are the most {trait} person I know.',
130     'Your {trait} personality always makes my day.',
131     'Your {trait} personality is my sunshine.',
132     'Your {trait} personality gives me strength.',
133     'I’m astonished how {trait} you are.',
134     'I hope I can learn to be as {trait} as you.',
135   ];
136   return new Promise((resolve, reject) => {
137     let todoList = {
138       'audio/wind.ogg': 72482,
139       'fonts/cookie.json': 37866,
140       'textures/cloud0a.png': 568,
141       'textures/cloud0b.png': 569,
142       'textures/cloud0c.png': 568,
143       'textures/cloud1a.png': 6932,
144       'textures/cloud1b.png': 6932,
145       'textures/cloud1c.png': 6933,
146       'textures/cloud2a.png': 4365,
147       'textures/cloud2b.png': 4364,
148       'textures/cloud2c.png': 4365,
149       'textures/cloud3a.png': 4000,
150       'textures/cloud3b.png': 3999,
151       'textures/cloud3c.png': 4001,
152       'textures/cloud4a.png': 3183,
153       'textures/cloud4b.png': 3182,
154       'textures/cloud4c.png': 3184,
155       'textures/cloud5a.png': 2066,
156       'textures/cloud5b.png': 2065,
157       'textures/cloud5c.png': 2066,
158       'textures/feather-black.png': 1026,
159       'textures/feather-blue.png': 1026,
160       'textures/feather-brown.png': 1027,
161       'textures/feather-green.png': 1028,
162       'textures/feather-orange.png': 1028,
163       'textures/feather-purple.png': 1028,
164       'textures/feather-red.png': 1024,
165       'textures/highcontrast-backdrop.png': 500,
166       'textures/pinwheel.png': 904,
167       'textures/house-day-1.png': 17819,
168       'textures/house-day-2.png': 598,
169       'textures/house-day-3.png': 646,
170       'textures/house-evening-1.png': 16939,
171       'textures/house-evening-2.png': 597,
172       'textures/house-evening-3.png': 646,
173     };
174     for(let unlockable of game.settings['unlocks']) {
175       if(unlockable == 'golden') {
176         todoList['textures/feather-golden.png'] = 1027;
177       } else if(unlockable == 'ghost') {
178         todoList['textures/feather-ghost.png'] = 1023;
179       } else {
180         let unlock = game['fn'].unlockWithKey('NIbp2kW5' + unlockable + 'e2ZDFl5Y');
181         if(unlock && unlock['type'] == 'feather') {
182           todoList['data:textures/feather-' + unlock['name']] = unlock['url'];
183         }
184       }
185     }
186     game.assets.audiothemes = [];
187     const audioThemes = {
188       'classical': [1636930, 34002, 34629, 25399, 16426, 26122],
189     }
190     for(let theme of Object.keys(audioThemes)) {
191       todoList['audio/music-' + theme + '.ogg'] = audioThemes[theme][0];
192       todoList['audio/sound1-' + theme + '.ogg'] = audioThemes[theme][1];
193       todoList['audio/sound2-' + theme + '.ogg'] = audioThemes[theme][2];
194       todoList['audio/sound3-' + theme + '.ogg'] = audioThemes[theme][3];
195       todoList['audio/sound4-' + theme + '.ogg'] = audioThemes[theme][4];
196       todoList['audio/sound5-' + theme + '.ogg'] = audioThemes[theme][5];
197       game.assets.audiothemes.push(theme);
198     }
199     let total = Object.keys(todoList).filter(k => !k.startsWith('data:')).map(k => todoList[k]).reduce((a, b) => a + b, 0);
200     let progress = {};
201     const loader = {
202       'audio': new THREE.AudioLoader(),
203       'fonts': new FontLoader(),
204       'textures': new THREE.TextureLoader(),
205     };
206     for(let todo in todoList) {
207       let isDataUri = todo.startsWith('data:');
208       if(isDataUri) {
209         todo = todo.slice(5);
210       } else {
211         progress[todo] = 0;
212       }
213       let segments = todo.split('/');
214       if(!(segments[0] in game.assets)) {
215         game.assets[segments[0]] = {};
216       }
217       if(!(segments[0] in loader)) {
218         reject('Unsupported resource: ' + todo);
219       }
220       let url = todo;
221       if(isDataUri) {
222         url = todoList['data:' + todo];
223       } else {
224         url = game['deploymentOptions']['assetUrlPrefix'] + url;
225       }
226       loader[segments[0]].load(url, (result) => {
227         if(segments[0] == 'textures') {
228           result.colorSpace = THREE.SRGBColorSpace;
229           result.minFilter = THREE.NearestFilter;
230           result.magFilter = THREE.NearestFilter;
231           if(segments[1].split('.')[0].startsWith('feather-')) {
232             result.repeat = new THREE.Vector2(1, -1);
233             result.wrapT = THREE.RepeatWrapping;
234           } else if(segments[1].split('.')[0] == 'highcontrast-backdrop') {
235             result.repeat = new THREE.Vector2(25, 25);
236             result.wrapS = THREE.RepeatWrapping;
237             result.wrapT = THREE.RepeatWrapping;
238           }
239         }
240         game.assets[segments[0]][segments[1].split('.')[0]] = result;
241         if(todo in progress) {
242           progress[todo] = todoList[todo];
243           if(renderProgressCallback) {
244             renderProgressCallback(Object.keys(progress).map(k => progress[k]).reduce((a, b) => a + b, 0) / total);
245           }
246         }
247       }, (xhr) => {
248         if(todo in progress) {
249           progress[todo] = xhr.loaded;
250           if(renderProgressCallback) {
251             renderProgressCallback(Object.keys(progress).map(k => progress[k]).reduce((a, b) => a + b, 0) / total);
252           }
253         }
254       }, (err) => {
255         reject('Error while loading ' + todo + ': ' + err);
256       });
257     }
258     const loadingHeartbeat = () => {
259       let totalProgress = Object.keys(progress).map(k => progress[k]).reduce((a, b) => a + b, 0);
260       if(totalProgress == total) {
261         resolve(totalProgress);
262       } else {
263         setTimeout(loadingHeartbeat, 100);
264       }
265     };
266     setTimeout(loadingHeartbeat, 100);
267   });
270 game['fn'].applyForceToFeather = (vector) => {
271   game.objects.feather.speed.add(vector);
274 game['fn'].initializeGame = (canvas) => {
275   game.timeProgress = 0;
276   game.timeTotal = 258;
277   game.courseRadius = 50;
279   game.objects = {};
280   game.view = {};
281   game.view.muted = false;
282   game.view.canvas = canvas;
283   game.ui.virtualInput = canvas.closest('.upInTheAirGame').querySelector('.virtual-input-widget');
285   const scene = new THREE.Scene();
286   game.view.camera = new THREE.PerspectiveCamera(75, canvas.width / canvas.height, 0.1, 1000);
287   game.view.camera.position.z = 5;
288   game.view.ambientLight = new THREE.AmbientLight(0xffffff, 2);
289   scene.add(game.view.ambientLight);
290   game.view.directionalLight1 = new THREE.DirectionalLight(0xffffff, 1);
291   game.view.directionalLight1.position.set(1, 1, 1);
292   scene.add(game.view.directionalLight1);
293   game.view.directionalLight2 = new THREE.DirectionalLight(0xffffff, 1);
294   game.view.directionalLight2.position.set(-1, -1, 1);
295   scene.add(game.view.directionalLight2);
296   game.view.directionalLight3 = new THREE.DirectionalLight(0xffffff, 1);
297   game.view.directionalLight3.position.set(0, -1, 1);
298   scene.add(game.view.directionalLight3);
299   game.view.renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: false });
300   game.view.renderer.setSize(canvas.width, canvas.height);
301   game.view.renderer.setClearColor(0x808080, 1);
302   let resolution = Math.round(3200 / Math.pow(2, game.settings['graphics']));
303   game.view.canvas.width = resolution;
304   game.view.canvas.height = resolution;
305   game.view.camera.updateProjectionMatrix();
306   game.view.renderer.setSize(game.view.canvas.width, game.view.canvas.height);
307   game.view.clock = new THREE.Clock();
308   game.view.clock.previousTime = 0;
309   game.view.clock.getDeltaTime = () => {
310     const elapsedTime = game.view.clock.getElapsedTime();
311     const deltaTime = elapsedTime - game.view.clock.previousTime;
312     game.view.clock.previousTime = elapsedTime;
313     return deltaTime;
314   };
316   const pinwheelGeometry = new THREE.BoxGeometry(.9, .9, 0.01);
317   const pinwheelMaterial = new THREE.MeshPhongMaterial({
318     map: game.assets.textures.pinwheel,
319     transparent: true,
320     alphaTest: 0.5,
321     opacity: 0.0,
322   });
323   game.objects.pinwheel = new THREE.Mesh(pinwheelGeometry, [null, null, null, null, pinwheelMaterial, null]);
324   game.objects.pinwheel.position.setY(2);
325   game.objects.pinwheel.position.setZ(-1);
326   game.objects.pinwheel.opacity = 0;
327   scene.add(game.objects.pinwheel);
329   for(let time of ['day', 'evening']) {
330     game.objects[time + 'House'] = new THREE.Group();
331     for(let layer of [1, 2, 3]) {
332       let material = new THREE.MeshBasicMaterial({
333         map: game.assets['textures']['house-' + time + '-' + layer],
334         transparent: true,
335         alphaTest: 0.5,
336       });
337       let dimensions;
338       if(layer == 1) {
339         dimensions = [14, 14, 0, 0, -2];
340       } else if(layer == 2) {
341         dimensions = [6, 3.4455, -1.4, -3.6, -3];
342       } else if(layer == 3) {
343         dimensions = [10, 10, -4, -2, -6];
344       }
345       let mesh = new THREE.Mesh(new THREE.PlaneGeometry(dimensions[0], dimensions[1]), material);
346       mesh.position.set(dimensions[2], dimensions[3], dimensions[4]);
347       if(time == 'evening') {
348         mesh.position.setX(-mesh.position.x);
349       }
350       game.objects[time + 'House'].add(mesh);
351     }
352     game.objects[time + 'House'].position.set(-11.5, -game.courseRadius - 4, -7);
353     if(time == 'evening') {
354       game.objects[time + 'House'].position.x *= -1;
355     }
356   }
358   game.view.camera.position.set(-5, -game.courseRadius, game.view.camera.position.z);
359   game.view.scene = scene;
361   game['fn'].createMeshes();
362   game['fn'].createFeather();
363   game['fn'].reset();
365   function pinwheelPositionUpdate(game, viewportX, viewportY) {
366     const vFOV = THREE.MathUtils.degToRad(game.view.camera.fov);
367     const viewportHeight = 2 * Math.tan(vFOV / 2) * (game.view.camera.position.z - game.objects.pinwheel.position.z);
368     game.controls.positionX = viewportHeight * viewportX;
369     game.controls.positionY = - viewportHeight * viewportY;
370   }
372   function cursorMoveEvent(game, target, viewportLocalX, viewportLocalY, pressed) {
373     if(game.settings['controls'] == 'mouse' || game.settings['controls'] == 'touchpad') {
374       let sensorElem = game.view.canvas;
375       if(game.settings['controls'] == 'touchpad') {
376         sensorElem = game.ui.virtualInput;
377       }
378       let bbox = sensorElem.getBoundingClientRect();
379       // Intentional division by height instead of width in the following line, since
380       // three.js controls the vertical FOV. So if we ever change the aspect ratio from 1:1,
381       // y will still be in range (-0.5, 0.5), but the range for x will be smaller or larger.
382       let x = (viewportLocalX - bbox.x - (bbox.width / 2)) / bbox.height;
383       let y = (viewportLocalY - bbox.y - (bbox.height / 2)) / bbox.height;
384       if(game.settings['controls'] == 'touchpad') {
385         sensorElem.children[0].style.left = ((0.5 + x) * 100) + '%';
386         sensorElem.children[0].style.top = ((0.5 + y) * 100) + '%';
387       }
388       if(game.settings['controls'] == 'touchpad') {
389         x *= 1.05;
390         y *= 1.05;
391       }
392       // The pinwheel gets to go a little bit past the edge of the playing field.
393       const maxDist = 0.55;
394       if(game.settings['controls'] == 'mouse' || (pressed && Math.abs(x) <= maxDist && Math.abs(y) <= maxDist)) {
395         pinwheelPositionUpdate(game, x, y);
396       }
397     }
398     if(game.settings['controls'] == 'thumbstick') {
399       if(!game.ui.virtualInput.inProgress) {
400         return;
401       }
402       let bbox = game.ui.virtualInput.getBoundingClientRect();
403       let x, y;
404       if(pressed) {
405         x = (viewportLocalX - bbox.x - (bbox.width / 2)) / bbox.height;
406         y = (viewportLocalY - bbox.y - (bbox.height / 2)) / bbox.height;
407         let vLen = Math.sqrt(4 * x * x + 4 * y * y);
408         x = x / Math.max(vLen, 0.6);
409         y = y / Math.max(vLen, 0.6);
410       } else {
411         x = 0;
412         y = 0;
413       }
414       let speedScale = 7.0;
415       let deadZone = 0.2;
416       let speedX = x * 2;
417       if(Math.abs(speedX) < deadZone) {
418         speedX = 0.0;
419       }
420       let speedY = y * 2;
421       if(Math.abs(speedY) < deadZone) {
422         speedY = 0.0;
423       }
424       game.controls.speedX = speedScale * speedX;
425       game.controls.speedY = -1 * speedScale * speedY;
426       x *= 0.6;
427       y *= 0.6;
428       game.ui.virtualInput.children[0].style.left = ((0.5 + x) * 100) + '%';
429       game.ui.virtualInput.children[0].style.top = ((0.5 + y) * 100) + '%';
430     }
431   }
433   function keyboardEvent(game, key, motion) {
434     if(game.settings['controls'] != 'keyboard') {
435       return;
436     }
437     if(motion == 'down') {
438       if(game.controls.heldKeys.includes(key)) {
439         return;
440       }
441       game.controls.heldKeys.push(key);
442     } else {
443       if(game.controls.heldKeys.includes(key)) {
444         game.controls.heldKeys.splice(game.controls.heldKeys.indexOf(key), 1);
445       }
446     }
447     if(game.settings['keyboard']['tapmode']) {
448       if(motion != 'down') {
449         return;
450       }
451       if(game.settings['keyboard']['up'].includes(key)) {
452         game.controls.speedY = Math.max(0.0, game.controls.speedY + 2.0);
453       }
454       if(game.settings['keyboard']['down'].includes(key)) {
455         game.controls.speedY = Math.min(0.0, game.controls.speedY - 2.0);
456       }
457       if(game.settings['keyboard']['right'].includes(key)) {
458         game.controls.speedX = Math.max(0.0, game.controls.speedX + 2.0);
459       }
460       if(game.settings['keyboard']['left'].includes(key)) {
461         game.controls.speedX = Math.min(0.0, game.controls.speedX - 2.0);
462       }
463       return;
464     }
465     if(motion == 'down' && game.settings['keyboard']['up'].includes(key)) {
466       game.controls.accelY = 15.0;
467       game.controls.speedY = 0.0;
468     }
469     if(motion == 'down' && game.settings['keyboard']['down'].includes(key)) {
470       game.controls.accelY = -15.0;
471       game.controls.speedY = 0.0;
472     }
473     if(motion == 'down' && game.settings['keyboard']['right'].includes(key)) {
474       game.controls.accelX = 15.0;
475       game.controls.speedX = 0.0;
476     }
477     if(motion == 'down' && game.settings['keyboard']['left'].includes(key)) {
478       game.controls.accelX = -15.0;
479       game.controls.speedX = 0.0;
480     }
481     if(motion == 'up' && game.settings['keyboard']['up'].includes(key)) {
482       game.controls.accelY = Math.min(0.0, game.controls.accelY);
483       game.controls.speedY = Math.min(0.0, game.controls.speedY);
484     }
485     if(motion == 'up' && game.settings['keyboard']['down'].includes(key)) {
486       game.controls.accelY = Math.max(0.0, game.controls.accelY);
487       game.controls.speedY = Math.max(0.0, game.controls.speedY);
488     }
489     if(motion == 'up' && game.settings['keyboard']['right'].includes(key)) {
490       game.controls.accelX = Math.min(0.0, game.controls.accelX);
491       game.controls.speedX = Math.min(0.0, game.controls.speedX);
492     }
493     if(motion == 'up' && game.settings['keyboard']['left'].includes(key)) {
494       game.controls.accelX = Math.max(0.0, game.controls.accelX);
495       game.controls.speedX = Math.max(0.0, game.controls.speedX);
496     }
497   }
499   document.body.addEventListener('mousemove', e => cursorMoveEvent(game, e.target, e.clientX, e.clientY, (e.buttons % 2 == 1)));
500   document.body.addEventListener('mousedown', e => {
501     if(game.settings['controls'] == 'touchpad' || game.settings['controls'] == 'thumbstick') {
502       if(e.target.closest('.virtual-input-widget') == game.ui.virtualInput) {
503         game.ui.virtualInput.inProgress = true;
504         game.ui.virtualInput.children[0].style.display = 'block';
505         e.preventDefault();
506       } else {
507         game.ui.virtualInput.inProgress = false;
508         if(game.settings['controls'] == 'touchpad') {
509           game.ui.virtualInput.children[0].style.display = 'none';
510         }
511       }
512     }
513     cursorMoveEvent(game, e.target, e.clientX, e.clientY, (e.buttons % 2 == 1));
514   });
515   document.body.addEventListener('mouseup', e => {
516     cursorMoveEvent(game, e.target, e.clientX, e.clientY, (e.buttons % 2 == 1));
517     if(game.settings['controls'] == 'touchpad' || game.settings['controls'] == 'thumbstick') {
518       game.ui.virtualInput.inProgress = false;
519       if(game.settings['controls'] == 'touchpad') {
520         game.ui.virtualInput.children[0].style.display = 'none';
521       } else {
522         game.ui.virtualInput.children[0].style.transitionDuration = '50ms';
523         setTimeout(() => { game.ui.virtualInput.children[0].style.transitionDuration = '0ms'; }, 75);
524       }
525       cursorMoveEvent(game, e.target, 0, 0, false);
526     }
527   });
528   document.body.addEventListener('touchmove', e => cursorMoveEvent(game, e.target, e.touches[0].clientX, e.touches[0].clientY, true));
529   document.body.addEventListener('touchstart', e => {
530     if(game.settings['controls'] == 'touchpad' || game.settings['controls'] == 'thumbstick') {
531       if(e.target.closest('.virtual-input-widget') == game.ui.virtualInput) {
532         game.ui.virtualInput.inProgress = true;
533         game.ui.virtualInput.children[0].style.display = 'block';
534         e.preventDefault();
535       } else {
536         game.ui.virtualInput.inProgress = false;
537         if(game.settings['controls'] == 'touchpad') {
538           game.ui.virtualInput.children[0].style.display = 'none';
539         }
540       }
541     }
542     cursorMoveEvent(game, e.target, e.touches[0].clientX, e.touches[0].clientY, true);
543   });
544   document.body.addEventListener('touchend', e => {
545     if(e.target.closest('.ui-container') && game.settings['controls'] != 'mouse' && ['gameplay', 'openingcutscene', 'endingcutscene'].includes(game.ui.currentPage)) {
546       game['fn'].moveToPage('pause', true);
547       e.preventDefault();
548     }
549     if(game.settings['controls'] == 'touchpad' || game.settings['controls'] == 'thumbstick') {
550       game.ui.virtualInput.inProgress = false;
551       if(game.settings['controls'] == 'touchpad') {
552         game.ui.virtualInput.children[0].style.display = 'none';
553       } else {
554         game.ui.virtualInput.children[0].style.transitionDuration = '50ms';
555         setTimeout(() => { game.ui.virtualInput.children[0].style.transitionDuration = '0ms'; }, 75);
556       }
557       cursorMoveEvent(game, e.target, 0, 0, false);
558     }
559   });
560   document.body.addEventListener('keydown', e => keyboardEvent(game, e.key, 'down'));
561   document.body.addEventListener('keyup', e => keyboardEvent(game, e.key, 'up'));
563   // All vectors used by the game loop (no allocations inside)
564   game.var = {};
565   game.var.featherLocalPos = new THREE.Vector3();
566   game.var.featherBorderForce = new THREE.Vector3();
567   game.var.pinwheelDistance = new THREE.Vector3();
568   game.var.pinwheelRotationSpeed = 0;
569   game.var.notCollectedPos = new THREE.Vector3();
570   game.var.collectedPos = new THREE.Vector3();
571   game.var.endingEntryTrajectory = new THREE.Vector3();
572   game.var.endingExitTrajectory = new THREE.Vector3();
573   game.var.endingEntryRotation = new THREE.Vector3();
574   game.var.endingExitRotation = new THREE.Vector3();
575   game.view.renderer.setAnimationLoop(() => { game['fn'].animate(scene); });
578 game['fn'].prepareWordMesh = (word) => {
579   while(word.children.length > 0) {
580     word.remove(word.children[0]);
581   }
582   if(game.settings['graphics'] <= 2 && !game.settings['highcontrast']) {
583     for(let letter of word.text) {
584       let geometry = game.assets.fonts.geometry[letter];
585       let material = game.view.materials.letter;
586       if(geometry.customMaterial) {
587         material = geometry.customMaterial;
588       }
589       let mesh = new THREE.Mesh(geometry, material);
590       // We wrap each letter in a surrounding group in order to move the center point
591       // from the corner of the letter to its center. This makes rotations easier.
592       let container = new THREE.Group();
593       mesh.position.set(-game.assets.fonts.geometry[letter].dx, -game.assets.fonts.geometry[letter].dy, 0);
594       container.add(mesh);
595       word.add(container);
596     }
597   } else if(game.settings['graphics'] == 3 || game.settings['highcontrast']) {
598     let mesh = new THREE.Mesh(Object.values(game.assets.fonts.geometry)[0], game.view.materials.letter);
599     word.add(mesh);
600   }
603 game['fn'].reset = () => {
604   game.controls = {};
605   game.controls.positionX = 0;
606   game.controls.positionY = 0;
607   game.controls.speedX = 0;
608   game.controls.speedY = 0;
609   game.controls.accelX = 0;
610   game.controls.accelY = 0;
611   game.controls.heldKeys = [];
612   game.ui.reachedEnd = false;
613   if(game.settings['graphics'] <= 2 && !game.settings['highcontrast']) {
614     for(let i = 0; i < 6; i++) {
615      game.view.materials['cloud' + i].uniforms.lerp.value = 0.0;
616     }
617   }
618   game.view.scene.add(game.objects.dayHouse);
619   game.view.scene.remove(game.objects.eveningHouse);
620   game.objects.feather.position.set(-11.45, -game.courseRadius - 4.2, -9.9);
621   game.objects.feather.rotation.set(Math.PI, 0, Math.PI / 2.1);
622   game.objects.pinwheel.material[4].opacity = 0.0;
623   setTimeout(() => {
624     game.ui.root.querySelector('.ui-page.title').classList.remove('end');
625   }, 500);
627   if(game.objects.words) {
628     for(let word of game.objects.words) {
629       game.view.scene.remove(word);
630     }
631   }
632   game.objects.words = [];
633   game.objects.words.collectedCount = 0;
634   game.ui.hud.children[1].innerText = '0';
635   const interWordDistance = new THREE.Vector3();
636   let placementSuccess;
637   let wordList = [];
638   for(let i = 0; i < 100; i++) {
639     let angleInCourse;
640     let clusteringFunction = (val) => Math.max(0.15 + val / 2, 0.7 - 3 * Math.pow(0.75 - 2 * val, 2), 1 - 3 * Math.pow(1 - val, 2));
641     do {
642       angleInCourse = Math.random();
643     } while(clusteringFunction(angleInCourse) < Math.random());
644     angleInCourse = (0.08 + 0.87 * angleInCourse);
645     if(i == 0) {
646       angleInCourse = 0.05;
647     }
648     let randomCameraX = game.courseRadius * Math.sin(angleInCourse * 2 * Math.PI);
649     let randomCameraY = game.courseRadius * -Math.cos(angleInCourse * 2 * Math.PI);
650     let word = new THREE.Group();
651     if(wordList.length == 0) {
652       wordList.push(...game.assets.wordList);
653     }
654     let wordIndex = Math.floor(Math.random() * wordList.length);
655     word.text = wordList.splice(wordIndex, 1)[0];
656     game['fn'].prepareWordMesh(word);
657     word.randomAnimOffset = Math.random();
658     const vFOV = THREE.MathUtils.degToRad(game.view.camera.fov);
659     let attempts = 0;
660     do {
661       let randomPlacementRadius = Math.min(0.8, angleInCourse) * Math.tan(vFOV / 2) * Math.abs(word.position.z - game.view.camera.position.z);
662       if(i == 0) {
663         randomPlacementRadius = 0;
664       }
665       let randomPlacementAngle = Math.random() * 2 * Math.PI;
666       let randomPlacementX = Math.sin(randomPlacementAngle) * randomPlacementRadius;
667       let randomPlacementY = Math.cos(randomPlacementAngle) * randomPlacementRadius;
668       word.position.set(randomCameraX + randomPlacementX, randomCameraY + randomPlacementY, 0);
669       placementSuccess = true;
670       for(let j = 0; j < i; j++) {
671         if(interWordDistance.subVectors(word.position, game.objects.words[j].position).length() <= 1.2) {
672           placementSuccess = false;
673           break;
674         }
675       }
676       attempts += 1;
677       if(attempts >= 10) {
678         angleInCourse = 0.04 + 0.92 * Math.random();
679         attempts = 0;
680       }
681     } while(!placementSuccess);
682     game.view.scene.add(word);
683     game.objects.words.push(word);
684   }
687 game['fn'].animate = (scene) => {
688   if(!('startTime' in game)) {
689     game.startTime = game.view.clock.getElapsedTime();
690   }
691   if(game.ui.currentPage == 'pause') {
692     return;
693   }
694   let delta = Math.min(game.view.clock.getDeltaTime(), 1 / 12);
695   if(game.ui.currentPage == 'gameplay') {
696     delta = delta * (game.settings['difficulty']['speed'] / 100);
697   }
698   game.timeProgress = (game.timeProgress + delta);
700   if(game.settings['controls'] == 'gamepad') {
701     let speedScale = 7.0;
702     let deadZone = 0.2;
703     let speedX = [];
704     let speedY = [];
705     for(let gamepad of game.ui.gamepads) {
706       let sx = gamepad.axes[0];
707       if(Math.abs(sx) < deadZone) {
708         sx = 0.0;
709       }
710       speedX.push(sx);
711       let sy = gamepad.axes[1];
712       if(Math.abs(sy) < deadZone) {
713         sy = 0.0;
714       }
715       speedY.push(sy);
716     }
717     if(speedX.length > 0) {
718       speedX = speedX.reduce((s, a) => s + a, 0) / speedX.length;
719     } else {
720       speedX = 0;
721     }
722     if(speedY.length > 0) {
723       speedY = speedY.reduce((s, a) => s + a, 0) / speedY.length;
724     } else {
725       speedY = 0;
726     }
727     game.controls.speedX = speedScale * speedX;
728     game.controls.speedY = -1 * speedScale * speedY;
729   }
731   const maxPinwheelSpeed = 8.0;
732   const maxPinwheelDistance = 5.0;
733   game.controls.speedX += delta * game.controls.accelX;
734   game.controls.speedY += delta * game.controls.accelY;
735   game.controls.speedX = Math.min(maxPinwheelSpeed, Math.max(-maxPinwheelSpeed, game.controls.speedX));
736   game.controls.speedY = Math.min(maxPinwheelSpeed, Math.max(-maxPinwheelSpeed, game.controls.speedY));
737   game.controls.positionX += delta * game.controls.speedX;
738   game.controls.positionY += delta * game.controls.speedY;
739   if(game.controls.positionX > maxPinwheelDistance) {
740     game.controls.positionX = maxPinwheelDistance;
741     game.controls.speedX = Math.max(0.0, game.controls.speedX);
742     game.controls.accelX = Math.max(0.0, game.controls.accelX);
743   } else if(game.controls.positionX < -maxPinwheelDistance) {
744     game.controls.positionX = -maxPinwheelDistance;
745     game.controls.speedX = Math.min(0.0, game.controls.speedX);
746     game.controls.accelX = Math.min(0.0, game.controls.accelX);
747   }
748   if(game.controls.positionY > maxPinwheelDistance) {
749     game.controls.positionY = maxPinwheelDistance;
750     game.controls.speedY = Math.max(0.0, game.controls.speedY);
751     game.controls.accelY = Math.max(0.0, game.controls.accelY);
752   } else if(game.controls.positionY < -maxPinwheelDistance) {
753     game.controls.positionY = -maxPinwheelDistance;
754     game.controls.speedY = Math.min(0.0, game.controls.speedY);
755     game.controls.accelY = Math.min(0.0, game.controls.accelY);
756   }
758   if(game.ui.currentPage != 'gameplay') {
759     let cameraSwayFactor = 1;
760     if(game.settings['graphics'] == 3) {
761       cameraSwayFactor = 0;
762     }
763     let cameraX, cameraY;
764     if(['options', 'credits', 'outro', 'unlock'].includes(game.ui.currentPage)) {
765       cameraX = game.ui.reachedEnd ? 5 : -5;
766       cameraY = 0;
767     }
768     if(game.ui.currentPage == 'title') {
769       cameraX = -5;
770       cameraY = 0;
771       if(!game.ui.reachedEnd) {
772         game.objects.feather.position.set(cameraX - 8.45, -game.courseRadius - 6.4, -9.9);
773         game.objects.feather.rotation.set(Math.PI, 0, Math.PI / 2.1);
774       } else {
775         cameraX = 5;
776       }
777       if(!game.ui.reachedStart) {
778         if(game.timeProgress < 1) {
779           game.ui.root.querySelector('.ui-page.title h1').style.opacity = '0';
780           game.ui.root.querySelectorAll('.ui-page.title > button').forEach((btn) => {
781             btn.disabled = true;
782             btn.style.position = 'relative';
783             btn.style.left = '10em';
784             btn.style.opacity = '0';
785           });
786           game.ui.root.querySelector('.ui-page.title .footer').style.opacity = '0';
787           game.ui.root.querySelector('.ui-page.title .system-buttons').style.opacity = '0';
788           cameraX += Math.max(0.0, 1 - game['fn'].easeInOut(0.5 + game.timeProgress / 2));
789           cameraY += Math.max(0.0, 10 * Math.pow(0.5 - game.timeProgress / 2, 2));
790         } else if(game.timeProgress >= 1.0 && game.timeProgress <= 2.1) {
791           game.ui.root.querySelector('.ui-page.title h1').style.opacity = Math.min(1.0, game.timeProgress - 1.0).toFixed(2);
792         }
793         if(game.timeProgress >= 1.5 && game.timeProgress <= 3.0) {
794           game.ui.root.querySelectorAll('.ui-page.title > button').forEach((btn) => {
795             let timeOffset = Array.from(btn.parentNode.children).indexOf(btn) - 2;
796             btn.style.left = 10 * game['fn'].easeInOut(Math.max(0.0, Math.min(1.0, 0.3 * timeOffset + 2.5 - game.timeProgress))).toFixed(2) + 'em';
797             let opacity = game['fn'].easeInOut(Math.max(0.0, Math.min(1.0, -0.3 * timeOffset + game.timeProgress - 1.5)));
798             btn.style.opacity = opacity.toFixed(2);
799             if(opacity == 1.0) {
800               btn.disabled = false;
801             }
802           });
803         }
804         if(game.timeProgress >= 3.0 && game.timeProgress <= 4.0) {
805           game.ui.root.querySelector('.ui-page.title .footer').style.opacity = game['fn'].easeInOut(Math.max(0.0, Math.min(1.0, game.timeProgress - 3.0))).toFixed(2);
806           game.ui.root.querySelector('.ui-page.title .system-buttons').style.opacity = game['fn'].easeInOut(Math.max(0.0, Math.min(1.0, game.timeProgress - 3.0))).toFixed(2);
807         }
808         if(game.timeProgress > 4.0 && !game.ui.reachedStart) {
809           game.ui.root.querySelector('.ui-page.title h1').removeAttribute('style');
810           game.ui.root.querySelectorAll('.ui-page.title > button').forEach(btn => { btn.disabled = false; btn.removeAttribute('style'); });
811           game.ui.root.querySelector('.ui-page.title .footer').removeAttribute('style');
812           game.ui.root.querySelector('.ui-page.title .system-buttons').removeAttribute('style');
813           game.ui.reachedStart = true;
814         }
815       }
816     } else if(game.ui.currentPage == 'openingcutscene') {
817       cameraX = -5;
818       cameraY = 0;
819       if(game.ui.reachedEnd) {
820         game['fn'].reset();
821       }
822       if(game.timeProgress < 0.1 && !game.view.windSound.isPlaying) {
823         game.view.windSound.stop();
824         game.objects.feather.position.set(cameraX - 8.45, -game.courseRadius - 6.4, -9.9);
825         game.objects.feather.rotation.set(Math.PI, 0, Math.PI / 2.1);
826       }
827       if(game.timeProgress > 1.0 && game.timeProgress <= 1.1 && !game.ui.root.querySelector('.gameplay p')) {
828         const lines = ['Why are the simplest words…', '…often the most difficult to write?'];
829         for(let line of lines) {
830           let elem = document.createElement('p');
831           elem.innerText = line;
832           elem.style.left = (1.5 + 2 * lines.indexOf(line)) + 'em';
833           elem.style.top = (1 + 1.2 * lines.indexOf(line)) + 'em';
834           elem.style.opacity = '0';
835           document.querySelector('.ui-page.gameplay').appendChild(elem);
836         }
837         if(!game.view.windSound.isPlaying) {
838           game.view.windSound.setVolume(game.settings['audio']['sounds']);
839           game.view.windSound.offset = 0;
840           if(!game.view.muted) {
841             game.view.windSound.play();
842           }
843         }
844       }
845       if(game.timeProgress > 1.0 && game.timeProgress <= 5.0) {
846         game.ui.root.querySelectorAll('.ui-page.gameplay p').forEach((elem) => {
847           let opacity = Math.max(0.0, Math.min(1.0, game.timeProgress - (elem.nextSibling ? 1.0 : 3.5)));
848           elem.style.transform = 'translateX(' + (Math.pow(1.0 - opacity, 2) * 10).toFixed(2) + 'em)';
849           elem.style.opacity = opacity.toFixed(2);
850         });
851       }
852       if(game.timeProgress >= 1.0 && game.timeProgress <= 3.0) {
853         let windStrength = 0.5 * (1 + Math.cos((game.timeProgress - 2.0) * Math.PI));
854         game.objects.feather.position.x = cameraX - 8.45 + 0.15 * windStrength;
855         game.objects.feather.rotation.z = Math.PI / 2.1 - 0.2 * windStrength;
856       }
857       if(game.timeProgress >= 3.0) {
858         let windStrength = Math.max(0.5 * (1 + Math.cos((game.timeProgress - 4.0) * Math.PI)), Math.min(2 * (game.timeProgress - 4.2), 1.2));
859         game.objects.feather.position.x = cameraX - 8.45 + 0.15 * windStrength + 13.45 * Math.min(1.0, Math.max(0.0, 1 - Math.pow(Math.max(0.0, 6.0 - game.timeProgress), 2)));
860         game.objects.feather.position.y = -game.courseRadius - 6.4 + 6.4 * game['fn'].easeInOut(Math.min(1,Math.max(0, game.timeProgress - 5.0) / 2));
861         game.objects.feather.position.y += (Math.cos((Math.max(5.0, Math.min(8.0, game.timeProgress)) - 5.0) * 2 * Math.PI / 3) - 1) * 2 * Math.sin(game.timeProgress * 2);
862         game.objects.feather.position.z = -9.9 + 9.9 * Math.min(1.0, Math.max(0.0, 1 - Math.pow(Math.max(0.0, 6.0 - game.timeProgress), 2)));
863         game.objects.feather.rotation.z = Math.PI / 2.1 - 0.2 * windStrength + 1.45 * Math.max(0.0, game.timeProgress - 5.0);
864         game.objects.feather.rotation.x = Math.PI + Math.max(0.0, game.timeProgress - 4.5) * Math.sin(Math.pow(game.timeProgress - 4.5, 2));
865       }
866       if(game.timeProgress > 7.0) {
867         game.ui.root.querySelectorAll('.ui-page.gameplay p').forEach((elem) => {
868           let opacity = Math.max(0.0, Math.min(1.0, 8.0 - game.timeProgress));
869           elem.style.opacity = opacity.toFixed(2);
870         });
871       }
872       cameraSwayFactor = cameraSwayFactor * (1 - (game.timeProgress / 8));
873       cameraX = -5 + Math.pow(Math.max(0, game.timeProgress - 3) / 5, 1.6) * 5;
875       if(game.timeProgress > 6.0 && game.timeProgress < 7.0 && game.settings['controls'] != 'mouse') {
876         game.controls.positionX = 0;
877         game.controls.positionY = -3;
878       }
879       game.objects.pinwheel.material[4].opacity = game['fn'].easeInOut(Math.max(0, (game.timeProgress - 7)));
880       if(game.timeProgress >= 8.0) {
881         game.ui.root.querySelectorAll('.ui-page.gameplay p').forEach((elem) => {
882           let opacity = Math.max(0.0, Math.min(1.0, 8.0 - game.timeProgress));
883           elem.style.opacity = opacity.toFixed(2);
884         });
885         game.view.music.offset = 0;
886         if(!game.view.muted) {
887           game.view.music.play();
888         }
889         game['fn'].moveToPage('gameplay', true);
890       }
891     } else if(game.ui.currentPage == 'endingcutscene') {
892       cameraX = -5;
893       cameraY = 0;
894       cameraSwayFactor = cameraSwayFactor * game.timeProgress / 8;
895       cameraX = 5 - Math.pow(Math.max(0, 5 - game.timeProgress) / 5, 1.6) * 5;
896       let trajectoryLerpValue = game['fn'].easeInOut(Math.min(6.0, game.timeProgress) / 6);
897       game.var.endingEntryTrajectory.addScaledVector(game.objects.feather.speed, delta);
898       game.var.endingExitTrajectory.setX(11.2 * game['fn'].easeInOut(Math.min(1, 1 - Math.max(0, 4 - game.timeProgress) / 4)));
899       game.var.endingExitTrajectory.setY(-game.courseRadius - 7.6 * game['fn'].easeInOut(Math.min(1, 1 - Math.max(0, 4 - game.timeProgress) / 4)));
900       game.var.endingExitTrajectory.setZ(-8.9 * game['fn'].easeInOut(Math.min(1, 1 - Math.max(0, 4 - game.timeProgress) / 4)));
901       game.objects.feather.rotation.x = game['fn'].lerp(game.var.endingEntryRotation.x, game.var.endingExitRotation.x, trajectoryLerpValue);
902       game.objects.feather.rotation.y = game['fn'].lerp(game.var.endingEntryRotation.y, game.var.endingExitRotation.y, trajectoryLerpValue);
903       game.objects.feather.rotation.z = game['fn'].lerp(game.var.endingEntryRotation.z, game.var.endingExitRotation.z, trajectoryLerpValue);
904       game.objects.feather.position.lerpVectors(game.var.endingEntryTrajectory, game.var.endingExitTrajectory, trajectoryLerpValue);
905       game.objects.pinwheel.material[4].opacity = game['fn'].easeInOut(Math.max(0, (1 - game.timeProgress)));
906       if(!game.settings['highcontrast']) {
907         let letterScale = game['fn'].lerp(0.3, 0.0, game['fn'].easeInOut(Math.max(0, Math.min(1, game.timeProgress - 6))));
908         for(let i = 0; i < game.objects.words.length; i++) {
909           let word = game.objects.words[i];
910           if(!word.collected) {
911             continue;
912           }
913           let x, y, z;
914           let collectionAnimationDuration = 1.0;
915           for(let j = 0; j < word.children.length; j++) {
916             let letter = word.children[j];
917             let animationProgress = (((game.timeProgress + 5 * word.randomAnimOffset) % 5) / 5 + j / 37) % 1;
918             x = game.objects.feather.scale.x * 0.5 * Math.cos(animationProgress * 1 * Math.PI * 2);
919             y = 0.2 * Math.sin(animationProgress * 7 * Math.PI * 2);
920             z = 0.2 * Math.cos(animationProgress * 7 * Math.PI * 2);
921             x = x * Math.cos(game.objects.feather.rotation.z) - y * Math.sin(game.objects.feather.rotation.z);
922             y = y * Math.cos(game.objects.feather.rotation.z) + x * Math.sin(game.objects.feather.rotation.z);
923             x += game.objects.feather.position.x - word.position.x;
924             y += game.objects.feather.position.y - word.position.y;
925             z += game.objects.feather.position.z - word.position.z;
926             if(i == 0 && !word.collected) {
927               // If we don't catch this edge case here, the manually placed first word might be visible
928               // in the closing cutscene if it is not collected.
929               x = 9999;
930             }
931             letter.position.set(x, y, z);
932             let rotation = (game.timeProgress * 3 + 2 * Math.PI * word.randomAnimOffset) % (2 * Math.PI);
933             letter.rotation.set(rotation + j, rotation + 2*j, rotation + 3*j);
934             letter.scale.set(letterScale, letterScale, letterScale);
935           }
936         }
937       }
938       if(game.timeProgress >= 8) {
939         game.ui.root.querySelector('.ui-page.title').classList.add('end');
940         game['fn'].moveToPage('outro', true);
941       }
942     } else if(game.ui.reachedEnd) {
943       cameraX = 5;
944       cameraY = 0;
945     }
946     if(typeof(cameraX) == 'number' && typeof(cameraY) == 'number') {
947       game.view.camera.position.setY(cameraY - game.courseRadius + 0.07 * cameraSwayFactor * Math.sin(game.view.clock.getElapsedTime() * 0.5));
948       game.view.camera.position.setX(cameraX + 0.05 * cameraSwayFactor * Math.sin(game.view.clock.getElapsedTime() * 0.7));
949     }
950     game.view.renderer.render(scene, game.view.camera);
951     return;
952   }
953   if(game.settings['enablehud']) {
954     if(game.timeProgress < 0.5) {
955       game.ui.hud.style.opacity = Math.min(1, game.timeProgress * 4).toFixed(2);
956     }
957     const failsafe = 0.0001;
958     const radiusOuter = 0.5;
959     const radiusInner = 0.4;
960     const progress = Math.max(failsafe, Math.min(1 - failsafe, game.timeProgress / game.timeTotal));
961     const xOuter = (0.5 + radiusOuter * Math.sin(progress * 2 * Math.PI)).toFixed(4);
962     const yOuter = (0.5 + radiusOuter * Math.cos(progress * 2 * Math.PI)).toFixed(4);
963     const xInner = (0.5 + radiusInner * Math.sin(progress * 2 * Math.PI)).toFixed(4);
964     const yInner = (0.5 + radiusInner * Math.cos(progress * 2 * Math.PI)).toFixed(4);
965     for(let segment of [0, 1]) {
966       let p = 'M' + xOuter + ',' + yOuter;
967       p += 'A' + radiusOuter + ',' + radiusOuter + ' 0 ' + ((progress >= 0.5) ? (1 - segment) : segment) + ' ' + (1 - segment) + ' .5,' + (0.5 + radiusOuter);
968       p += 'V' + (0.5 + radiusInner);
969       p += 'A' + radiusInner + ',' + radiusInner + ' 0 ' + ((progress >= 0.5) ? (1 - segment) : segment) + ' ' + segment + ' ' + xInner + ',' + yInner;
970       p += 'z';
971       game.ui.hud.children[0].children[segment].setAttribute('d', p);
972     }
973     if(game.timeProgress > game.timeTotal - 0.5) {
974       game.ui.hud.style.opacity = Math.max(0, (game.timeTotal - game.timeProgress - 0.25) * 4).toFixed(2);
975     }
976   }
977   if(game.ui.root.querySelector('.ui-page.gameplay p')) {
978     game.ui.root.querySelectorAll('.ui-page.gameplay p').forEach(elem => elem.remove());
979   }
980   if(game.timeProgress / game.timeTotal >= 1.0) {
981     game.ui.reachedEnd = true;
982     game.var.endingEntryTrajectory.set(game.objects.feather.position.x, game.objects.feather.position.y, game.objects.feather.position.z);
983     game.var.endingEntryRotation.x = game.objects.feather.rotation.x;
984     game.var.endingEntryRotation.y = game.objects.feather.rotation.y;
985     game.var.endingEntryRotation.z = game.objects.feather.rotation.z;
986     game.var.endingExitRotation.set(-0.2, 0, -0.2);
987     game['fn'].moveToPage('endingcutscene', true);
988   }
990   if(game.settings['audio']['music'] > 0.0 && game.view.music && !game.view.music.isPlaying) {
991     const remainingRealTime = (game.timeTotal - game.timeProgress) / (game.settings['difficulty']['speed'] / 100);
992     if(remainingRealTime >= game.assets['audio']['music-' + game.settings['audio']['theme']].duration - 2) {
993       game.view.music.offset = 0;
994       if(!game.view.muted) {
995         game.view.music.play();
996       }
997     }
998   }
1000   const angle = 2 * Math.PI * (game.timeProgress / game.timeTotal);
1001   game.view.camera.position.x = game.courseRadius * Math.sin(angle);
1002   game.view.camera.position.y = - game.courseRadius * Math.cos(angle);
1004   if(!game.settings['highcontrast']) {
1005     let sunsetValue = 2.0;
1006     if(!game.ui.reachedEnd) {
1007       sunsetValue = sunsetValue * game['fn'].easeInOut(Math.min(1, Math.max(0, ((game.timeProgress / game.timeTotal) - 0.3) / 0.6)));
1008     }
1009     if(game.settings['graphics'] <= 2) {
1010       for(let i = 0; i < 6; i++) {
1011         game.view.materials['cloud' + i].uniforms.lerp.value = sunsetValue;
1012       }
1013     } else {
1014       let cloudMaterialVariant = null;
1015       if(sunsetValue < 0.5 && !game.objects.clouds.children[0].material.name.endsWith('a')) {
1016         cloudMaterialVariant = 'a';
1017       } else if(sunsetValue >= 0.5 && sunsetValue < 1.5 && !game.objects.clouds.children[0].material.name.endsWith('b')) {
1018         cloudMaterialVariant = 'b';
1019       } else if(sunsetValue >= 1.5 && !game.objects.clouds.children[0].material.name.endsWith('c')) {
1020         cloudMaterialVariant = 'c';
1021       }
1022       if(cloudMaterialVariant) {
1023         for(let cloud of game.objects.clouds.children) {
1024           cloud.material = game.view.materials[cloud.material.name.slice(0, -1) + cloudMaterialVariant];
1025         }
1026         game.objects.backdrop.material = game.view.materials['cloud0' + cloudMaterialVariant];
1027       }
1028     }
1029   }
1031   if(game.timeProgress / game.timeTotal > 0.5 && game.objects.dayHouse.parent == scene) {
1032     scene.remove(game.objects.dayHouse);
1033     scene.add(game.objects.eveningHouse);
1034   }
1036   game.var.featherLocalPos.subVectors(game.objects.feather.position, game.view.camera.position).setZ(0);
1037   game.var.featherBorderForce.set(0, 0, 0);
1038   for(let coord of [0, 1]) {
1039     if(Math.abs(game.var.featherLocalPos.getComponent(coord)) > 3) {
1040       game.var.featherBorderForce.setComponent(coord, 3 * Math.sign(game.var.featherLocalPos.getComponent(coord)) - game.var.featherLocalPos.getComponent(coord));
1041     }
1042   }
1043   game['fn'].applyForceToFeather(game.var.featherBorderForce);
1044   const tiltedGravity = game.gravity.clone();
1045   game.var.pinwheelDistance.subVectors(game.objects.feather.position, game.objects.pinwheel.position).setZ(0);
1047   const pinwheelRotationTargetSpeed = 1 + Math.max(0, 2 - game.var.pinwheelDistance.length());
1048   game.var.pinwheelRotationSpeed = Math.max(1, pinwheelRotationTargetSpeed, game.var.pinwheelRotationSpeed - 2 * delta);
1049   game.objects.pinwheel.rotation.z -= game.var.pinwheelRotationSpeed * 5 * delta;
1050   game.objects.pinwheel.position.x = game.view.camera.position.x + game.controls.positionX;
1051   game.objects.pinwheel.position.y = game.view.camera.position.y + game.controls.positionY;
1053   const pinwheelForce = 0.5 * Math.max(0, Math.pow(game.var.pinwheelDistance.length(), - 0.5) - 0.5);
1054   game['fn'].applyForceToFeather(game.var.pinwheelDistance.normalize().multiplyScalar(pinwheelForce));
1055   if(pinwheelForce < 0.2) {
1056     if(game.objects.feather.swayDirection > 0 && game.objects.feather.speed.x > 1.5) {
1057       game.objects.feather.swayDirection *= -1;
1058     } else if(game.objects.feather.swayDirection < 0 && game.objects.feather.speed.x < -1.5) {
1059       game.objects.feather.swayDirection *= -1;
1060     }
1061     tiltedGravity.x += game.objects.feather.swayDirection;
1062   }
1063   if(game.objects.feather.speed.y > -1) {
1064     game['fn'].applyForceToFeather(tiltedGravity);
1065   }
1066   game.objects.feather.rotation.z = -0.1 * game.objects.feather.speed.x * game.settings['difficulty']['speed'] / 100;
1067   game.objects.feather.position.addScaledVector(game.objects.feather.speed, delta * game.settings['difficulty']['speed'] / 100);
1069   if(pinwheelForce > 0.2) {
1070     if(game.objects.feather.twistSpeed < 0.0001) {
1071       game.objects.feather.twistSpeed = (Math.random() - 0.5) * 0.01;
1072     }
1073     game.objects.feather.twistSpeed = Math.sign(game.objects.feather.twistSpeed) * 0.1 * game.objects.feather.speed.length();
1074   } else {
1075     game.objects.feather.twistSpeed = 0.98 * game.objects.feather.twistSpeed;
1076     if(Math.abs(game.objects.feather.twistSpeed < 0.1)) {
1077       let rotationDelta = game.objects.feather.rotation.x;
1078       if(rotationDelta >= Math.PI) {
1079         rotationDelta -= 2 * Math.PI;
1080       }
1081       game.objects.feather.twistSpeed -= rotationDelta * 0.02;
1082     }
1083   }
1085   game.objects.feather.twistSpeed = Math.min(0.13, game.objects.feather.twistSpeed) * game.settings['difficulty']['speed'] / 100;
1086   game.objects.feather.rotation.x = (game.objects.feather.rotation.x + game.objects.feather.twistSpeed) % (2 * Math.PI);
1088   let collectedScale = 0.0;
1089   if(!game.settings['highcontrast'] && game.settings['graphics'] <= 2) {
1090     collectedScale = game['fn'].lerp(0.6, 0.3, 1 - Math.pow(1 - game.objects.words.collectedCount / game.objects.words.length, 2));
1091   } else if(!game.settings['highcontrast'] && game.settings['graphics'] == 3) {
1092     collectedScale = 0.3;
1093   }
1094   const collectingRadius = - 0.5 + 1.5 * game.settings['difficulty']['collectingradius'];
1095   for(let i = 0; i < game.objects.words.length; i++) {
1096     let word = game.objects.words[i];
1097     if(!word.collected && new THREE.Vector3().subVectors(word.position, game.objects.feather.position).length() < collectingRadius) {
1098       word.collected = game.view.clock.getElapsedTime();
1099       game.objects.words.collectedCount += 1;
1100       game.ui.hud.children[1].innerText = game.objects.words.collectedCount;
1101       game['fn'].playRandomSound();
1102     }
1103     if(word.parent != game.view.scene) {
1104       // All that happens in here is the positional animation for the word, which
1105       // we can skip if it is no longer visible.
1106       continue;
1107     }
1108     let x, y, z;
1109     let collectionAnimationDuration = 1.0;
1110     for(let j = 0; j < word.children.length; j++) {
1111       game.var.notCollectedPos.set(0, 0, 0);
1112       game.var.collectedPos.set(0, 0, 0);
1113       let letter = word.children[j];
1114       let animationProgress = (((game.timeProgress + 5 * word.randomAnimOffset) % 5) / 5 + j / 37) % 1;
1115       if(!word.collected || game.view.clock.getElapsedTime() - word.collected <= collectionAnimationDuration) {
1116         x = word.position.x;
1117         y = word.position.y;
1118         z = 0;
1119         if(game.settings['graphics'] <= 2 && !game.settings['highcontrast']) {
1120           const wordAnimationRadius = 0.2;
1121           x += wordAnimationRadius * Math.cos(animationProgress * 5 * Math.PI * 2);
1122           y += wordAnimationRadius * Math.sin(animationProgress * 4 * Math.PI * 2);
1123           z += wordAnimationRadius * Math.sin(animationProgress * 6 * Math.PI * 2);
1124         }
1125         game.var.notCollectedPos.set(x, y, z);
1126       }
1127       if(word.collected) {
1128         if(!game.settings['highcontrast']) {
1129           x = game.objects.feather.scale.x * 0.5 * Math.cos(animationProgress * 1 * Math.PI * 2);
1130           y = 0.2 * Math.sin(animationProgress * 7 * Math.PI * 2);
1131           z = 0.2 * Math.cos(animationProgress * 7 * Math.PI * 2);
1132           x = x * Math.cos(game.objects.feather.rotation.z) - y * Math.sin(game.objects.feather.rotation.z);
1133           y = y * Math.cos(game.objects.feather.rotation.z) + x * Math.sin(game.objects.feather.rotation.z);
1134           x += game.objects.feather.position.x;
1135           y += game.objects.feather.position.y;
1136           z += game.objects.feather.position.z;
1137         } else {
1138           x = game.objects.feather.position.x;
1139           y = game.objects.feather.position.y;
1140           z = game.objects.feather.position.z;
1141         }
1142         game.var.collectedPos.set(x, y, z);
1143       }
1144       if(game.var.notCollectedPos.length() > 0 && game.var.collectedPos.length() > 0) {
1145         let collectingProgress = game['fn'].easeInOut(Math.max(0.0, Math.min(1.0, (game.view.clock.getElapsedTime() - word.collected) / collectionAnimationDuration)));
1146         letter.position.lerpVectors(game.var.notCollectedPos, game.var.collectedPos, collectingProgress);
1147         let scale = game['fn'].lerp(1.0, collectedScale, collectingProgress);
1148         letter.scale.set(scale, scale, scale);
1149       } else if(game.var.notCollectedPos.length() > 0) {
1150         letter.position.set(game.var.notCollectedPos.x, game.var.notCollectedPos.y, game.var.notCollectedPos.z);
1151       } else if(game.var.collectedPos.length() > 0) {
1152         letter.position.set(game.var.collectedPos.x, game.var.collectedPos.y, game.var.collectedPos.z);
1153         if(game.settings['highcontrast']) {
1154           // Special case because in high contrast mode, collected words vanish entirely.
1155           game.view.scene.remove(word);
1156         }
1157       }
1158       letter.position.sub(word.position);
1159       if(!game.settings['highcontrast']) {
1160         let rotation = (game.timeProgress * 3 + 2 * Math.PI * word.randomAnimOffset) % (2 * Math.PI);
1161         letter.rotation.set(rotation + j, rotation + 2*j, rotation + 3*j);
1162       }
1163     }
1164   }
1166   game.view.renderer.render(scene, game.view.camera);
1169 game['fn'].loadSettings = () => {
1170   let settings = {
1171     'controls': null, // set during first time launch depending on device
1172     'virtualinputleft': false,
1173     'enablehud': false,
1174     'graphics': 1,
1175     'audio': {
1176       'music': 0.5,
1177       'sounds': 0.5,
1178       'theme': null, // actual default value determined after asset loading
1179     },
1180     'feather': 'blue',
1181     'unlocks': [],
1182     'highcontrast': false,
1183     'font': 'standard',
1184     'difficulty': {
1185       'collectingradius': 1,
1186       'speed': 100,
1187     },
1188     'keyboard': {
1189       'up': ['ArrowUp', 'w'],
1190       'right': ['ArrowRight', 'd'],
1191       'down': ['ArrowDown', 's'],
1192       'left': ['ArrowLeft', 'a'],
1193       'tapmode': false,
1194     },
1195   };
1196   let stored;
1197   try {
1198     stored = window['localStorage'].getItem('upInTheAirGameSettings');
1199     game.ui.root.querySelector('.ui-page.options .warning.storage').style.display = 'none';
1200   } catch(error) {
1201     game.ui.root.querySelector('.ui-page.options .warning.storage').style.display = 'block';
1202   }
1203   if(stored) {
1204     let merge = (source, target) => {
1205       for(let k of Object.keys(source)) {
1206         if(source[k] != null && typeof(source[k]) == 'object' && typeof(target[k]) == 'object' && !Array.isArray(target[k])) {
1207           merge(source[k], target[k]);
1208         } else if(k in target) {
1209           target[k] = source[k];
1210         }
1211       }
1212     };
1213     stored = JSON.parse(stored);
1214     merge(stored, settings);
1215   }
1216   const ui = game.ui.root.querySelector('.ui-page.options');
1217   game.ui.hud.style.display = settings['enablehud'] ? 'flex' : 'none';
1218   if(settings['controls']) {
1219     ui.querySelector('.controls input[value="' + settings['controls'] + '"]').checked = true;
1220     ui.querySelector('.controls .leftside input').checked = settings['virtualinputleft'];
1221     ui.querySelector('.controls .leftside').style.display = (['touchpad', 'thumbstick'].includes(settings['controls'])) ? 'block' : 'none';
1222     ui.querySelectorAll('.controls p span:not(.' + settings['controls'] + ')').forEach(span => span.style.display = 'none');
1223     ui.querySelector('.controls span.' + settings['controls']).style.display = 'block';
1224   }
1225   ui.querySelector('.graphics input[value="' + settings['graphics'] + '"]').checked = true;
1226   for(let audioCategory of ['music', 'sounds']) {
1227     let newValue = Math.max(0, Math.min(100, Math.round(100 * settings['audio'][audioCategory])));
1228     game.ui.root.querySelectorAll('.ui-page .audio input[type=range].' + audioCategory).forEach((elem) => {
1229       elem.value = newValue;
1230       elem.parentNode.nextElementSibling.innerText = newValue;
1231     });
1232   }
1233   let audioThemeRadio = ui.querySelector('.audiotheme input[value="' + settings['audio']['theme'] + '"]');
1234   if(audioThemeRadio) {
1235     audioThemeRadio.checked = true;
1236   }
1237   // Custom hash function that ensures our unlockables get stored in the same order,
1238   // regardless of the order in which they get unlocked.
1239   let miniHash = (input) => {
1240     return 4 * input.charCodeAt(0) + 0.1 * input.charCodeAt(1) + 3 * input.charCodeAt(2) + 2 * input.charCodeAt(3);
1241   }
1242   settings['unlocks'].sort((u1, u2) => miniHash(u1) > miniHash(u2));
1243   for(let unlockedFeather of settings['unlocks']) {
1244     if(!game.ui.root.querySelector('.ui-page.options .feather input[value="' + unlockedFeather + '"]')) {
1245       let radio = document.createElement('input');
1246       radio.type = 'radio';
1247       radio.name = 'upInTheAirGame-feather';
1248       radio.value = unlockedFeather;
1249       let img = document.createElement('img');
1250       if(unlockedFeather == 'golden' || unlockedFeather == 'ghost') {
1251         img.src = game['deploymentOptions']['assetUrlPrefix'] + 'textures/feather-' + unlockedFeather + '.png';
1252       } else {
1253         let unlock = game['fn'].unlockWithKey('NIbp2kW5' + unlockedFeather + 'e2ZDFl5Y');
1254         if(unlock && unlock['type'] == 'feather') {
1255           img.src = unlock['url'];
1256         } else {
1257           continue;
1258         }
1259       }
1260       img.alt = unlockedFeather[0].toUpperCase() + unlockedFeather.slice(1) + ' feather';
1261       let label = document.createElement('label');
1262       label.appendChild(radio);
1263       label.appendChild(img);
1264       game.ui.root.querySelector('.ui-page.options .feather').appendChild(label);
1265     }
1266   }
1267   if(!ui.querySelector('.feather input[value="' + settings['feather'] + '"]')) {
1268     settings['feather'] = 'blue';
1269   }
1270   ui.querySelector('.feather input[value=' + settings['feather'] + ']').checked = true;
1271   ui.querySelector('input[value="highcontrast"]').checked = !!settings['highcontrast'];
1272   ui.querySelector('.font input[value=' + settings['font'] + ']').checked = true;
1273   ui.querySelector('.difficulty select.collectingradius option[value="' + settings['difficulty']['collectingradius'] + '"]').selected = true;
1274   ui.querySelector('.difficulty select.speed option[value="' + settings['difficulty']['speed'] + '"]').selected = true;
1275   for(let direction of ['up', 'right', 'down', 'left']) {
1276     let keys = settings['keyboard'][direction];
1277     let btn = ui.querySelector('.keyboard button.' + direction);
1278     btn.value = keys.join('|');
1279     keys = keys.map(k => {
1280       if(k.length == 1 && k != 'ß') {
1281         k = k.toUpperCase();
1282       }
1283       switch(k) {
1284         case 'ArrowUp': return '🠕';
1285         case 'ArrowRight': return '🠖';
1286         case 'ArrowDown': return '🠗';
1287         case 'ArrowLeft': return '🠔';
1288         case ' ': return 'Space';
1289         default: return k;
1290       }
1291     });
1292     btn.innerText = keys.join(' or ');
1293   }
1294   ui.querySelector('input[value="tapmode"]').checked = !!settings['keyboard']['tapmode'];
1295   game.settings = settings;
1298 game['fn'].applySettings = () => {
1299   const ui = game.ui.root.querySelector('.ui-page.options');
1300   if(ui.querySelector('input[name="upInTheAirGame-controls"]:checked')) {
1301     game.settings['controls'] = ui.querySelector('input[name="upInTheAirGame-controls"]:checked').value;
1302   }
1303   game.settings['virtualinputleft'] = ui.querySelector('.controls .leftside input').checked;
1304   if(game.settings['virtualinputleft']) {
1305     game.ui.root.parentNode.classList.add('virtual-input-left');
1306   } else {
1307     game.ui.root.parentNode.classList.remove('virtual-input-left');
1308   }
1309   const virtualInput = game.ui.root.parentNode.querySelector('.virtual-input-widget');
1310   virtualInput.children[0].style.display = 'block';
1311   virtualInput.children[0].style.left = '50%';
1312   virtualInput.children[0].style.top = '50%';
1313   delete virtualInput.inProgress;
1314   if(game.settings['controls'] == 'touchpad') {
1315     virtualInput.classList.remove('thumbstick');
1316     virtualInput.classList.add('touchpad');
1317     game.ui.root.classList.remove('control-mouse', 'control-thumbstick');
1318     game.ui.root.classList.add('control-touchpad');
1319     virtualInput.children[0].style.display = 'none';
1320   } else if(game.settings['controls'] == 'thumbstick') {
1321     virtualInput.classList.remove('touchpad');
1322     virtualInput.classList.add('thumbstick');
1323     game.ui.root.classList.remove('control-mouse', 'control-touchpad');
1324     game.ui.root.classList.add('control-thumbstick');
1325   } else if(game.settings['controls'] == 'mouse') {
1326     virtualInput.classList.remove('touchpad', 'thumbstick');
1327     game.ui.root.classList.remove('control-touchpad', 'control-thumbstick');
1328     game.ui.root.classList.add('control-mouse');
1329   } else {
1330     virtualInput.classList.remove('touchpad', 'thumbstick');
1331     game.ui.root.classList.remove('control-mouse', 'control-touchpad', 'control-thumbstick');
1332   }
1333   for(let timeout of [10, 100, 1000]) {
1334     setTimeout(() => { game.ui.root.style.fontSize = (game.ui.root.clientWidth / 48) + 'px'; }, timeout);
1335   }
1336   game.settings['graphics'] = parseInt(ui.querySelector('input[name="upInTheAirGame-graphics"]:checked').value, 10);
1337   if(game.view) {
1338     let resolution = Math.round(3200 / Math.pow(2, game.settings['graphics']));
1339     game.view.canvas.width = resolution;
1340     game.view.canvas.height = resolution;
1341     game.view.camera.updateProjectionMatrix();
1342     game.view.renderer.setSize(game.view.canvas.width, game.view.canvas.height);
1343   }
1344   for(let audioCategory of ['music', 'sounds']) {
1345     game.settings['audio'][audioCategory] = parseInt(ui.querySelector('.audio input[type=range].' + audioCategory).value, 10) / 100;
1346   }
1347   let audioThemeRadio = ui.querySelector('.audiotheme input[name="upInTheAirGame-audiotheme"]:checked');
1348   if(audioThemeRadio) {
1349     game.settings['audio']['theme'] = audioThemeRadio.value;
1350   }
1351   game.settings['feather'] = ui.querySelector('input[name="upInTheAirGame-feather"]:checked').value;
1352   game.settings['highcontrast'] = ui.querySelector('input[value="highcontrast"]').checked;
1353   game.settings['font'] = ui.querySelector('input[name="upInTheAirGame-font"]:checked').value;
1354   game.settings['difficulty']['collectingradius'] = parseInt(ui.querySelector('.difficulty select.collectingradius').value, 10);
1355   game.settings['difficulty']['speed'] = parseInt(ui.querySelector('.difficulty select.speed').value, 10);
1356   for(let direction of ['up', 'right', 'down', 'left']) {
1357     game.settings['keyboard'][direction] = ui.querySelector('.keyboard button.' + direction).value.split('|');
1358   }
1359   game.settings['keyboard']['tapmode'] = ui.querySelector('input[value="tapmode"]').checked;
1360   try {
1361     window['localStorage'].setItem('upInTheAirGameSettings', JSON.stringify(game.settings));
1362     game.ui.root.querySelector('.ui-page.options .warning.storage').style.display = 'none';
1363   } catch(error) {
1364     game.ui.root.querySelector('.ui-page.options .warning.storage').style.display = 'block';
1365   }
1367   for(let audioCategory of ['music', 'sounds']) {
1368     game.settings['audio'][audioCategory] = parseInt(ui.querySelector('.audio input[type=range].' + audioCategory).value, 10) / 100;
1369     let value = Math.round(100 * game.settings['audio'][audioCategory]);
1370     game.ui.root.querySelectorAll('.ui-page .audio input[type=range].' + audioCategory).forEach((elem) => {
1371       elem.value = value;
1372       elem.parentNode.nextElementSibling.innerText = value;
1373     });
1374     if(audioCategory == 'music' && game.view && game.view.music) {
1375       game.view.music.setVolume(game.settings['audio'][audioCategory]);
1376     }
1377   }
1378   game.ui.root.classList.remove('font-atkinson', 'font-opendyslexic');
1379   if(game.settings['font'] != 'standard') {
1380     game.ui.root.classList.add('font-' + game.settings['font']);
1381   }
1384 game['fn'].createFeather = () => {
1385   let position, rotation;
1386   if(game.objects.feather) {
1387     position = game.objects.feather.position;
1388     rotation = game.objects.feather.rotation;
1389     game.objects.feather.geometry.dispose();
1390     game.objects.feather.material.dispose();
1391     game.view.scene.remove(game.objects.feather);
1392     delete game.objects.feather;
1393   }
1395   const featherGeometry = new THREE.PlaneGeometry(1.6, 0.5);
1396   let options = {
1397     map: game.assets.textures['feather-' + game.settings['feather']],
1398     transparent: true,
1399     alphaTest: 0.01,
1400     side: THREE.DoubleSide,
1401   }
1402   if(game.settings['feather'] == 'golden') {
1403     options.color = 0xffffff;
1404     options.emissive = 0x644a1e;
1405     options.roughness = 0.5;
1406     options.metalness = 0.4;
1407   }
1408   if(game.settings['feather'] == 'ghost') {
1409     options.opacity = 0.7;
1410   }
1411   game.view.materials.feather = new THREE.MeshStandardMaterial(options);
1412   game.objects.feather = new THREE.Mesh(featherGeometry, game.view.materials.feather);
1413   game.objects.feather.rotation.order = 'ZXY';
1414   if(position) {
1415     game.objects.feather.position.set(position.x, position.y, position.z);
1416   }
1417   if(rotation) {
1418     game.objects.feather.rotation.set(rotation.x, rotation.y, rotation.z);
1419   }
1420   game.view.scene.add(game.objects.feather);
1421   game.objects.feather.speed = new THREE.Vector3(0, 0, 0);
1422   game.gravity = new THREE.Vector3(0, -0.1, 0);
1423   game.objects.feather.swayDirection = 0.2;
1424   game.objects.feather.twistSpeed = 0.1;
1427 game['fn'].createMeshes = () => {
1428   if(game.objects.clouds && game.objects.clouds.parent == game.view.scene) {
1429     game.view.scene.remove(game.objects.clouds);
1430     if(game.objects.clouds.children.length > 0) {
1431       game.objects.clouds.children[0].geometry.dispose();
1432     }
1433     for(let mKey in game.view.materials) {
1434       game.view.materials[mKey].dispose();
1435     }
1436     delete game.objects.clouds;
1437   }
1438   if(game.objects.backdrop && game.objects.backdrop.parent == game.view.scene) {
1439     game.view.scene.remove(game.objects.backdrop);
1440     game.objects.backdrop.material.dispose();
1441     game.objects.backdrop.geometry.dispose();
1442   }
1443   if(game.assets.fonts.geometry) {
1444     for(let geom of Object.values(game.assets.fonts.geometry)) {
1445       if(geom.customMaterial) {
1446         geom.customMaterial.dispose();
1447       }
1448       geom.dispose();
1449     }
1450     delete game.assets.fonts.geometry;
1451   }
1452   if(game.view.materials) {
1453     for(let material of Object.values(game.view.materials)) {
1454       material.dispose();
1455     }
1456     delete game.view.materials;
1457   }
1459   if(game.view.materials && game.view.materials.feather) {
1460     game.view.materials = {
1461       'feather': game.view.materials['feather'],
1462     };
1463   } else {
1464     game.view.materials = {};
1465   }
1467   if(!game.settings['highcontrast']) {
1468     let cloudShaders;
1469     let cloudGeometry = new THREE.PlaneGeometry(1, 200 / 350);
1470     if(game.settings['graphics'] <= 2) {
1471       cloudShaders = {
1472         vertexShader:
1473        `
1474        precision highp float;
1475        precision highp int;
1476        varying vec2 vUv;
1477        void main() {
1478          vUv = uv;
1479          gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
1480        }
1481          `,
1482         fragmentShader:
1483          `
1484        precision mediump float;
1485        uniform sampler2D texture1;
1486        uniform sampler2D texture2;
1487        uniform sampler2D texture3;
1488        uniform float lerp;
1489        varying vec2 vUv;
1490        void main() {
1491          if(lerp > 1.0) {
1492            vec4 col1 = texture2D(texture2, vUv);
1493            vec4 col2 = texture2D(texture3, vUv);
1494            gl_FragColor = mix(col1, col2, lerp - 1.0);
1495          } else {
1496            vec4 col1 = texture2D(texture1, vUv);
1497            vec4 col2 = texture2D(texture2, vUv);
1498            gl_FragColor = mix(col1, col2, lerp);
1499          }
1500          // I don't know how GLSL works: why do I need to do this to match the textures?
1501          gl_FragColor = mix(gl_FragColor, vec4(1.0, 1.0, 1.0, gl_FragColor.a), 0.5);
1502        }
1503          `
1504       };
1505     }
1506     for(let i = 0; i < 6; i++) {
1507       if(game.settings['graphics'] <= 2) {
1508         game.view.materials['cloud' + i] = new THREE.ShaderMaterial({
1509           uniforms: THREE.UniformsUtils.merge([{
1510             texture1: null,
1511             texture2: null,
1512             texture3: null,
1513             lerp: null,
1514           }]),
1515           ...cloudShaders,
1516         });
1517         game.view.materials['cloud' + i].uniforms.texture1.value = game.assets.textures['cloud' + i + 'a'];
1518         game.view.materials['cloud' + i].uniforms.texture2.value = game.assets.textures['cloud' + i + 'b'];
1519         game.view.materials['cloud' + i].uniforms.texture3.value = game.assets.textures['cloud' + i + 'c'];
1520         if(game.ui.reachedEnd) {
1521           game.view.materials['cloud' + i].uniforms.lerp.value = 2.0;
1522         } else {
1523           game.view.materials['cloud' + i].uniforms.lerp.value = 0.0;
1524         }
1525         game.view.materials['cloud' + i].transparent = true;
1526       } else {
1527         for(let variant of ['a', 'b', 'c']) {
1528           game.view.materials['cloud' + i + variant] = new THREE.MeshBasicMaterial({
1529             map: game.assets.textures['cloud' + i + variant],
1530             transparent: true,
1531             alphaTest: 0.5,
1532           });
1533           game.view.materials['cloud' + i + variant].name = 'cloud' + i + variant;
1534         }
1535       }
1536     }
1537     game.objects.clouds = new THREE.Group();
1538     let textureVariantSuffix = '';
1539     if(game.settings['graphics'] > 2) {
1540       if(game.ui.reachedEnd) {
1541         textureVariantSuffix = 'c';
1542       } else {
1543         textureVariantSuffix = 'a';
1544       }
1545     }
1546     game.view.materials.letter = new THREE.MeshStandardMaterial({
1547       color: 0xffffff,
1548       emissive: 0x606060,
1549       roughness: 0.4,
1550       metalness: 1,
1551     });
1552     if(game.settings['graphics'] <= 2) {
1553       game.assets.fonts.geometry = {};
1554       for(let letter of [...new Set(game.assets.wordList.join(''))]) {
1555         if(game.settings['graphics'] == 1) {
1556           game.assets.fonts.geometry[letter] = new TextGeometry(letter, {
1557             font: game.assets.fonts.cookie,
1558             size: 0.2,
1559             depth: 0.03,
1560             curveSegments: 2,
1561             bevelEnabled: false,
1562           });
1563           game.assets.fonts.geometry[letter].computeBoundingBox();
1564           let bbox = game.assets.fonts.geometry[letter].boundingBox;
1565           // Add these to local 0,0 later to get the letter's center rotation point
1566           game.assets.fonts.geometry[letter].dx = (bbox.max.x - bbox.min.x) / 2;
1567           game.assets.fonts.geometry[letter].dy = (bbox.max.y - bbox.min.y) / 2;
1568         } else {
1569           let letterCanvas = document.createElement('canvas');
1570           letterCanvas.width = 64;
1571           letterCanvas.height = 64;
1572           let letterCanvasContext = letterCanvas.getContext('2d');
1573           letterCanvasContext.font = '60px Cookie';
1574           letterCanvasContext.fillStyle = '#000';
1575           letterCanvasContext.fillRect(0, 0, letterCanvas.width, letterCanvas.height);
1576           letterCanvasContext.fillStyle = '#fff';
1577           let bbox = letterCanvasContext.measureText(letter);
1578           let vOffset = bbox.actualBoundingBoxAscent - 0.5 * (bbox.actualBoundingBoxAscent + bbox.actualBoundingBoxDescent);
1579           letterCanvasContext.fillText(letter, Math.round((letterCanvas.width - bbox.width) / 2), (letterCanvas.height / 2) + vOffset);
1580           let alphaMap = new THREE.CanvasTexture(letterCanvas);
1581           alphaMap.needsUpdate = true;
1582           let letterMaterial = new THREE.MeshStandardMaterial({
1583             color: game.view.materials.letter.color,
1584             emissive: 0x303030,
1585             roughness: game.view.materials.letter.roughness,
1586             metalness: game.view.materials.letter.metalness,
1587             side: THREE.DoubleSide,
1588             alphaMap: alphaMap,
1589             transparent: true,
1590           });
1591           game.assets.fonts.geometry[letter] = new THREE.PlaneGeometry(0.3, 0.3);
1592           game.assets.fonts.geometry[letter].dx = 0;
1593           game.assets.fonts.geometry[letter].dy = 0;
1594           game.assets.fonts.geometry[letter].customMaterial = letterMaterial;
1595         }
1596       }
1597       let numClouds = 300;
1598       if(game.settings['graphics'] == 2) {
1599         numClouds = 75;
1600       }
1601       for(let i = 0; i < numClouds; i++) {
1602         let randomAngle = Math.random() * 2 * Math.PI;
1603         let randomCameraX = game.courseRadius * Math.sin(randomAngle);
1604         let randomCameraY = game.courseRadius * Math.cos(randomAngle);
1605         let cloud = new THREE.Mesh(cloudGeometry, game.view.materials['cloud' + (i % 5 + 1) + textureVariantSuffix]);
1606         cloud.position.z = -15 - Math.round(Math.random() * 40);
1607         const vFOV = THREE.MathUtils.degToRad(game.view.camera.fov);
1608         let maxCameraDistance = 2 * Math.tan(vFOV / 2) * Math.abs(cloud.position.z - game.view.camera.position.z);
1609         cloud.position.x = randomCameraX + maxCameraDistance * 2 * (Math.random() - 0.5);
1610         cloud.position.y = randomCameraY + maxCameraDistance * 2 * (Math.random() - 0.5);
1611         let scale = 21 + (Math.random() * 0.5 + 0.5) * Math.abs(cloud.position.z);
1612         cloud.scale.set(scale, scale, scale);
1613         game.objects.clouds.add(cloud);
1614       }
1615     } else {
1616       const minimalLetterGeometry = new THREE.BoxGeometry(0.2, 0.2, 0.2);
1617       minimalLetterGeometry.dx = 0;
1618       minimalLetterGeometry.dy = 0;
1619       game.assets.fonts.geometry = {};
1620       for(let letter of [...new Set(game.assets.wordList.join(''))]) {
1621         game.assets.fonts.geometry[letter] = minimalLetterGeometry;
1622       }
1623       for(let r = 0; r < game.courseRadius / 3; r++) {
1624         let angle = THREE.MathUtils.degToRad(360 * 3 * r / game.courseRadius);
1625         let cameraX = game.courseRadius * Math.sin(angle);
1626         let cameraY = game.courseRadius * Math.cos(angle);
1627         const vFOV = THREE.MathUtils.degToRad(game.view.camera.fov);
1628         let z = -15;
1629         let maxCameraDistance = Math.tan(vFOV / 2) * Math.abs(z - game.view.camera.position.z);
1630         let axis = [-1, 0, 1];
1631         if(r % 2 == 0) {
1632           axis = [-0.5, 0.5];
1633         }
1634         for(let step of axis) {
1635           let shape = 1 + Math.floor(Math.random() * 5);
1636           let cloud = new THREE.Mesh(cloudGeometry, game.view.materials['cloud' + shape + textureVariantSuffix]);
1637           cloud.position.x = cameraX + step * 1.2 * maxCameraDistance * Math.sin(angle);
1638           cloud.position.y = cameraY + step * maxCameraDistance * Math.cos(angle);
1639           cloud.position.z = z;
1640           let scale = 15 + 0.5 * Math.abs(cloud.position.z);
1641           cloud.scale.set(scale, scale, scale);
1642           game.objects.clouds.add(cloud);
1643         }
1644       }
1645     }
1646     game.view.scene.add(game.objects.clouds);
1647     game.objects.backdrop = new THREE.Mesh(new THREE.PlaneGeometry(350, 350), game.view.materials['cloud0' + textureVariantSuffix]);
1648     game.objects.backdrop.position.setZ(-100);
1649   } else {
1650     game.view.materials.letter = new THREE.MeshStandardMaterial({
1651       color: 0x00ff00,
1652       emissive: 0x00ff00,
1653     });
1654     const highcontrastLetterGeometry = new THREE.SphereGeometry(0.1, 16, 16);
1655     highcontrastLetterGeometry.dx = 0;
1656     highcontrastLetterGeometry.dy = 0;
1657     game.assets.fonts.geometry = {};
1658     for(let letter of [...new Set(game.assets.wordList.join(''))]) {
1659       game.assets.fonts.geometry[letter] = highcontrastLetterGeometry;
1660     }
1661     const highContrastBackdropMaterial = new THREE.MeshBasicMaterial({
1662       map: game.assets.textures['highcontrast-backdrop'],
1663     });
1664     game.objects.backdrop = new THREE.Mesh(new THREE.PlaneGeometry(150, 150), highContrastBackdropMaterial);
1665     game.objects.backdrop.position.setZ(-10);
1666   }
1667   if(game.objects.words) {
1668     for(let word of game.objects.words) {
1669       game['fn'].prepareWordMesh(word);
1670     }
1671   }
1672   game.view.scene.add(game.objects.backdrop);
1675 game['fn'].unlockFeather = (feather, url) => {
1676   if(game.settings['unlocks'].includes(feather)) {
1677     return false;
1678   }
1679   game.settings['unlocks'].push(feather);
1680   if(!url) {
1681     url = game['deploymentOptions']['assetUrlPrefix'] + 'textures/feather-' + feather + '.png';
1682   } else if(url.startsWith('textures/')) {
1683     url = game['deploymentOptions']['assetUrlPrefix'] + url;
1684   }
1686   if(!game.assets['textures']['feather-' + feather]) {
1687     (new THREE.TextureLoader()).load(url, (result) => {
1688       result.colorSpace = THREE.SRGBColorSpace;
1689       result.minFilter = THREE.NearestFilter;
1690       result.magFilter = THREE.NearestFilter;
1691       result.repeat = new THREE.Vector2(1, -1);
1692       result.wrapT = THREE.RepeatWrapping;
1693       game.assets['textures']['feather-' + feather] = result;
1694     }, () => {}, (err) => {
1695       console.error('Error while loading ' + feather + ' feather texture: ' + err);
1696     });
1697   }
1698   // Custom hash function that ensures our unlockables get stored in the same order,
1699   // regardless of the order in which they get unlocked.
1700   let miniHash = (input) => {
1701     return 4 * input.charCodeAt(0) + 0.1 * input.charCodeAt(1) + 3 * input.charCodeAt(2) + 2 * input.charCodeAt(3);
1702   }
1703   game.settings['unlocks'].sort((u1, u2) => miniHash(u1) > miniHash(u2));
1704   let insertAfterFeather = 'purple';
1705   if(game.settings['unlocks'].indexOf(feather) >= 1) {
1706     insertAfterFeather = game.settings['unlocks'][game.settings['unlocks'].indexOf(feather) - 1];
1707   }
1708   let radio = document.createElement('input');
1709   radio.type = 'radio';
1710   radio.name = 'upInTheAirGame-feather';
1711   radio.value = feather;
1712   radio.addEventListener('change', () => {
1713     game['fn'].applySettings();
1714     game['fn'].createFeather();
1715   });
1716   let img = document.createElement('img');
1717   img.src = url;
1718   img.alt = feather[0].toUpperCase() + feather.slice(1) + ' feather';
1719   let label = document.createElement('label');
1720   label.appendChild(radio);
1721   label.appendChild(img);
1722   game.ui.root.querySelector('.ui-page.options .feather input[value="' + insertAfterFeather + '"]').parentNode.after(label);
1723   game['fn'].applySettings();
1724   let ui = game.ui.root.querySelector('.ui-page.unlock');
1725   let img2 = ui.querySelector('img');
1726   img2.src = img.src;
1727   img2.alt = img.alt;
1728   ui.querySelector('p.name').innerText = img2.alt;
1729   return true;
1732 game['fn'].moveToPage = (target, skipFade = false) => {
1733   let fadeDuration = 250;
1734   if(skipFade) {
1735     fadeDuration = 0;
1736   }
1737   // After the gameplay page is shown for the first time, always keep it around as a backdrop
1738   game.ui.root.querySelectorAll('.ui-page:not(.' + target + '):not(.gameplay)').forEach((page) => {
1739     page.style.opacity = '0';
1740     setTimeout((page) => {
1741       page.style.display = 'none';
1742     }, fadeDuration, page);
1743   });
1744   if(game.ui.currentPage == 'title' && !game.ui.reachedStart) {
1745     setTimeout(() => {
1746       game.ui.root.querySelector('.ui-page.title h1').removeAttribute('style');
1747       game.ui.root.querySelectorAll('.ui-page.title button').forEach(btn => { btn.disabled = false; btn.removeAttribute('style'); });
1748       game.ui.root.querySelector('.ui-page.title .footer').removeAttribute('style');
1749       game.ui.root.querySelector('.ui-page.title .system-buttons').removeAttribute('style');
1750       game.ui.reachedStart = true;
1751     }, fadeDuration);
1752   }
1753   if(target == 'title' && game.view) {
1754     game.view.cheatBuffer = '';
1755   }
1756   if(target == 'title' && (!game.ui.currentPage || ['loading', 'controls'].includes(game.ui.currentPage))) {
1757     game['fn'].initializeGame(game.ui.root.querySelector('canvas'));
1758   }
1759   if(target == 'title' && game.ui.root.querySelector('.ui-page.gameplay p')) {
1760     game.ui.root.querySelectorAll('.ui-page.gameplay p').forEach(elem => elem.remove());
1761   }
1762   if(target == 'title' && game.view && game.view.windSound && game.view.windSound.isPlaying) {
1763     game.view.windSound.stop();
1764   }
1765   if(target == 'title' && game.view && game.view.music && game.view.music.isPlaying) {
1766     game.view.music.stop();
1767     if(game.view.music.timeoutID) {
1768       clearTimeout(game.view.music.timeoutID);
1769       delete game.view.music.timeoutID;
1770     }
1771   }
1772   if((target != 'pause' && game.ui.currentPage != 'pause') || target == 'title') {
1773     game.ui.hud.style.opacity = '0';
1774   }
1775   if(target == 'outro') {
1776     if(game.view.music.isPlaying) {
1777       game.view.music.stop();
1778     }
1779     let collectedWords = game.objects.words.filter(w => w.collected).map(w => w.text);
1780     game.ui.root.querySelector('.ui-page.outro .count').innerText = game.objects.words.collectedCount;
1781     game.ui.root.querySelector('.ui-page.outro .optionalPlural').innerText = 'word' + ((game.objects.words.collectedCount == 1) ? '' : 's') + '.';
1782     let ratingElem = game.ui.root.querySelector('.ui-page.outro .rating');
1783     let exampleElems = game.ui.root.querySelectorAll('.ui-page.outro .examples');
1784     let finalParagraph = game.ui.root.querySelector('.ui-page.outro .area > p:last-child');
1785     ratingElem.style.display = 'none';
1786     exampleElems.forEach(elem => { elem.style.display = 'none'; });
1787     let returnButton = game.ui.root.querySelector('.ui-page.outro button.goto');
1788     if(game.objects.words.collectedCount == 100 || game.objects.words.collectedCount == 0) {
1789       finalParagraph.style.display = 'none';
1790       let neededUnlocking = false;
1791       if(game.objects.words.collectedCount == 100) {
1792         neededUnlocking = game['fn'].unlockFeather('golden');
1793       } else {
1794         neededUnlocking = game['fn'].unlockFeather('ghost');
1795       }
1796       if(neededUnlocking) {
1797         returnButton.innerText = 'Continue';
1798         returnButton.classList.remove('title');
1799         returnButton.classList.add('unlock');
1800       } else {
1801         returnButton.innerText = 'Return to Title Screen';
1802         returnButton.classList.remove('unlock');
1803         returnButton.classList.add('title');
1804       }
1805     } else {
1806       finalParagraph.style.display = 'block';
1807       returnButton.innerText = 'Return to Title Screen';
1808       returnButton.classList.remove('unlock');
1809       returnButton.classList.add('title');
1810     }
1811     if(game.objects.words.collectedCount > 0) {
1812       if(game.objects.words.collectedCount == 100) {
1813         ratingElem.style.display = 'block';
1814         ratingElem.innerText = 'Wow, you managed to collect all of them. Congratulations!';
1815       } else {
1816         let generateExampleSentences = (wordList) => {
1817           let container = game.ui.root.querySelector('.ui-page.outro div.examples');
1818           while(container.children.length > 0) {
1819             container.children[0].remove();
1820           }
1821           let words = {};
1822           for(let category of Object.keys(game.assets.words)) {
1823             words[category] = [];
1824             for(let word of game.assets.words[category]) {
1825               if(wordList.includes(word)) {
1826                 words[category].push(word);
1827               }
1828             }
1829           }
1830           let result = [];
1831           let failedAttempts = 0;
1832           while(result.length < 3 && failedAttempts < 1000) {
1833             let sentence = game.assets.sentences[Math.floor(Math.random() * game.assets.sentences.length)];
1834             while(sentence.indexOf('{') > -1) {
1835               let areWeStuck = true;
1836               for(let category of Object.keys(words)) {
1837                 if(sentence.includes('{' + category + '}')) {
1838                   if(words[category].length == 0) {
1839                     break;
1840                   }
1841                   let choice = words[category][Math.floor(Math.random() * words[category].length)];
1842                   if(category == 'sorry') {
1843                     if(choice == 'sorry') {
1844                       sentence = sentence.replace('{sorry}', 'I’m {sorry}');
1845                     }
1846                     if(choice == 'apologize') {
1847                       sentence = sentence.replace('{sorry}', 'I {sorry}');
1848                     }
1849                   }
1850                   if(sentence.indexOf('{' + category + '}') == 0) {
1851                     choice = choice[0].toUpperCase() + choice.slice(1);
1852                   }
1853                   sentence = sentence.replace('{' + category + '}', '<strong>' + choice + '</strong>');
1854                   words[category].splice(words[category].indexOf(choice), 1);
1855                   areWeStuck = false;
1856                 }
1857               }
1858               if(areWeStuck) {
1859                 break;
1860               }
1861             }
1862             if(sentence.indexOf('{') == -1 && !result.includes(sentence)) {
1863               result.push(sentence);
1864               failedAttempts = 0;
1865             }
1866             failedAttempts += 1;
1867           }
1868           for(let sentence of result) {
1869             let elem = document.createElement('p');
1870             elem.innerHTML = sentence;
1871             container.appendChild(elem);
1872           }
1873         };
1874         generateExampleSentences(collectedWords);
1875         game.ui.root.querySelector('.ui-page.outro button.examples').addEventListener('click', () => { generateExampleSentences(collectedWords); });
1876         exampleElems.forEach(elem => { elem.style.display = 'flex'; });
1877       }
1878     } else {
1879       ratingElem.style.display = 'block';
1880       ratingElem.innerText = 'You completed the course while dodging every word. That’s an achievement all on its own. Respect!';
1881     }
1882   }
1883   if(target == 'options') {
1884     game.ui.root.querySelectorAll('.options .areatabs button').forEach((btn) => {
1885       if(btn.classList.contains('general')) {
1886         btn.classList.add('active');
1887       } else {
1888         btn.classList.remove('active');
1889       }
1890     });
1891     game.ui.root.querySelectorAll('.options > div.area.twocol').forEach((area) => {
1892       if(area.classList.contains('general')) {
1893         area.style.display = 'flex';
1894       } else {
1895         area.style.display = 'none';
1896       }
1897     });
1898   }
1899   const targetElems = [game.ui.root.querySelector('.ui-page.' + target + '')];
1900   if(game.ui.root.querySelector('.ui-page.gameplay').style.opacity != '1' && target == 'title') {
1901     targetElems.push(game.ui.root.querySelector('.ui-page.gameplay'));
1902   }
1903   for(let targetElem of targetElems) {
1904     if(!targetElem.classList.contains('gameplay')) {
1905       targetElem.style.opacity = '0';
1906     }
1907     targetElem.style.display = 'flex';
1908     setTimeout((targetElem) => {
1909       targetElem.style.opacity = '1';
1910       if(target == 'credits') {
1911         targetElem.querySelector('.area').scrollTop = 0;
1912       }
1913     }, fadeDuration, targetElem);
1914   }
1915   if(target != 'pause' && game.ui.currentPage != 'pause') {
1916     game.timeProgress = 0;
1917   }
1918   if(target == 'pause') {
1919     game.view.music.stop();
1920     game.view.windSound.stop();
1921   } else if(game.ui.currentPage == 'pause' && target == 'openingcutscene') {
1922     if(game.timeProgress >= 1.0) {
1923       game.view.windSound.offset = game.timeProgress - 1.0;
1924       game.view.windSound.setVolume(game.settings['audio']['sounds']);
1925       if(!game.view.muted) {
1926         game.view.windSound.play();
1927       }
1928     }
1929   } else if(game.ui.currentPage == 'pause' && target == 'gameplay') {
1930     game.view.music.offset = (game.timeProgress / (game.settings['difficulty']['speed'] / 100)) % game.assets['audio']['music-' + game.settings['audio']['theme']].duration;
1931     if(!game.view.muted) {
1932       game.view.music.play();
1933     }
1934   }
1935   game.ui.previousPage = game.ui.currentPage;
1936   game.ui.currentPage = target;
1937   if(game.view) {
1938     game.startTime = game.view.clock.getElapsedTime();
1939   }
1942 game['fn'].unlockWithKey = (input) => {
1943   input = 'aBYPmb2xCwF2ilfD'+ input + 'PNHFwI2zKZejUv6c';
1944   let hash = (input) => {
1945     // Adapted with appreciation from bryc:
1946     // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
1947     let h1 = 0xdeadbeef, h2 = 0x41c6ce57;
1948     for(let i = 0, ch; i < input.length; i++) {
1949       ch = input.charCodeAt(i);
1950       h1 = Math.imul(h1 ^ ch, 2654435761);
1951       h2 = Math.imul(h2 ^ ch, 1597334677);
1952     }
1953     h1  = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
1954     h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
1955     h2  = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
1956     h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
1957     return (h2 >>> 0).toString(16).padStart(8, 0) + (h1 >>> 0).toString(16).padStart(8, 0);
1958   }
1959   for(let unlockable of game.unlockables) {
1960     if(unlockable.accessKey == hash(input)) {
1961       let key = hash('UZx2jWen9w5jm0FB' + input + '7DZpEq4OOwv2kiJ1');
1962       let seed = parseInt(key.slice(12), 16);
1963       let prng = () => {
1964         seed |= 0;
1965         seed = seed + 0x9e3779b9 | 0;
1966         let t = seed ^ seed >>> 16;
1967         t = Math.imul(t, 0x21f0aaad);
1968         t = t ^ t >>> 15;
1969         t = Math.imul(t, 0x735a2d97);
1970         return ((t = t ^ t >>> 15) >>> 0);
1971       };
1972       let data = Uint8Array.from(atob(unlockable.payload), (c) => c.codePointAt(0));
1973       let pad;
1974       for(let i = 0; i < data.length; i++) {
1975         if(i % 4 == 0) {
1976           pad = prng();
1977           pad = [pad % 256, (pad >> 8) % 256, (pad >> 16) % 256, (pad >> 24) % 256];
1978         }
1979         data[i] = data[i] ^ pad[i % 4];
1980       }
1981       data = new TextDecoder().decode(data);
1982       let result = JSON.parse(data);
1983       if(result['type'] == 'redirect') {
1984         return game['fn'].unlockWithKey(result['target']);
1985       } else {
1986         return result;
1987       }
1988     }
1989   }
1990   return null;
1991 };
1993 game['fn'].start = () => {
1994   game.ui = {
1995     root: document.querySelector('.upInTheAirGame .ui-container'),
1996     hud: document.querySelector('.upInTheAirGame .hud'),
1997     gamepads: [],
1998   };
1999   game.settings = {};
2000   // If you're looking at the source code and the following seems scary, don't worry, it's just a few
2001   // unlockable feather textures. I liked easter eggs and cheat codes when I was young, and I didn't
2002   // want these to be trivially bypassable for people who can read the code.
2003   game.unlockables = [
2004     {
2005       'accessKey': '5b32eb7ad08488f4',
2006       'payload': 'k4JPu3sWfEhcgleieVGghixKSI10qdRRC5tAl39Tzy1U7Rx9EEEYbLx9wCcxAf7wC8r9mJZCOj8bNa7grMbUmTeCeWWPAg==',
2007     },
2008     {
2009       'accessKey': '6273da5894b2dd8b',
2010       'payload': 'XAFLhAjcTzsWgGb7DAMCKwHXjoyUg/yxkIUyLcV/7PpktgW3MHtXhh4OkVeANr52RfdbwfVpgO4dxuyYPaFZ4x4JDmI=',
2011     },
2012     {
2013       'accessKey': 'fb8b533451a6dd68',
2014       'payload': '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',
2015     },
2016     {
2017       'accessKey': '3c78e25c7b1106b6',
2018       'payload': 'dnbO28tXI2i2+o+etuRc0/Cfxd4UpdG1IRgqB0fTwJE1xCoK+TtB/JVGTquaD/stnIkKiA==',
2019     },
2020     {
2021       'accessKey': '5f79141f861a146a',
2022       'payload': 'IO59sEgiVtdv68PW1n+NdmYY6sGhOdG6BHA4BwVErVCIu25lohqBbDKgI+gWyCPVFUaFk76yW1Ji09i/n+swIQK5ayyfCeRoruxz2lA/Eoe0LTPqy2CPShxD0Pfi66AdgzQ+jMvHOi9Stw/t0XGGpLjrQfghJDnZpuEgipYG3PpiZbcbj3BVUuw7fV6idwGPBXoqagwXvscfjQppTq8LvuqgHYgSM6CXlKr95uJL0zsnqvtL9DPQgmZZTdHOZcwn/AXJFT94VIctGtgs81J4zwNCelbdD0dnhoFdJSTNhEhHH6vVMblNnz6wr48kOGI88yJf158ByR4ic3+Q0T7azpOSPGqWQkrsWN4u+gAprAhUeGrsL/7FopiSdRW3/iLDsXW31omQu6iPpLiP6KcvAOsJKYQdow1uVptFbfvA3cdONWL49XsIEgDFWtAb0XckN/xaerhYN50Vlw9bZW6t+P1/EZwgpqMLgBVwYHnQjthYJUw8bgmMtF4Jos7/0XDrVGE9EmNA0bCPS+h492zQ2S20kwLrncJJocyxVsEc9Nzu7L6JNtstzYEN8lLMcXedGZwvHoki+/q1DcJI8MMi2meb9JoQZE7a8KChtPssbuu2rPbZpodK99Q9AqaFeFu/5XtRsnVHY0SIBTyr66jP0LhNwhPzjz/+sDMAPc/6JkV7MNSxP7OS1VB2gaX5Xr6+fA4c+c+e4oVgx6xtp8ENxmGyVfjEvkkFD5Md6ARJ1Fznw/TWfZyGEQMj3WFsE+YYVKcCN5plCJ0f8ZpzrBvPCvViNbOW85DXavXy05NV/+F54OXx+DnPfWvvtaKSehUKLxzNrbqedtdqweMZyg70LNxJIzhVV1LsxqaLx9Q9L3TFbE8IV0ZJSin8n1Vzq/woFlP3brIwq0bVXUPTsrD/Q2oJTM/JN5OZLyDtdqU5r7dc/r3ZRPKeOZhMiauZS8QGu4JTbkbUHJVKe81gpi/nBDdX+2PoNJJy3nuoIyhtu57e8VfQKxUPhpxY+hiv2ETT8ZTF/SmHoC+VLVaDDN9Om4dW4XdQqO2Ab+XjovK30UK2Cc5SKK7AYtbX8HdzOp6rG5uRsNllWl28MD4gsXxkrQolsFbei0uasztUuZrZ0vOS4D0pPgxjPJ3e6iVlqgcd0ioa89Fl5MEiDRmy2QakXGQ/G6HWMNEUq0Ue9kHkyShi59TLrjeiRdw1ijojQ14eLHJgtCYfKIn9wxFTZfKJtlMgDyY+bca73BuCnXbbHAOr3pMtgdCOLVj8E0+RW4uB0VW3+mZwLvEZ3BNmYuf8J+sMbOkLrZAlgYJaxQWHiiAghyshoN5Vw+6XJGxe3obLuvDBDReGxmiehzX97bH+5cmIP0S2bD06+K5Yqsay5Gnvmjtj4+R+MHYEdlXQu6wCelP34YIeBnFz//1p13vQg/gsugpGBIh0lOeolEmyekpBRIKtkaDiPf5Sem1zeqmtLtrPNU3iP+EbjE1Vp41CWkTe/zZI4syUHTEKTpJpTLT7htM38YCAZ7z7EYjLeBjWjKtew+yN5pDLl9MX0pE2PgWHCdCHcHHtQW43W1qI+XzGJmuKiNfyz6kWb7SeGaFVue5iayagFwNuFO5EWNS33dgHvlkxU3pLnorbht1l4IsqCIQJnTWTXdhmdUvMCcVecQ3ZZiIhpj6o+ZWkmpq2fmNRBIRPvvoEwn7KZ+8IWDGU+BhhEDC75wI0iIsVLH9u5i2KwV2swqC+3YM07HzLY9Yb2Sphdz/stTsuiBGrGeL1sxvbMcdG4Yenp9peYRnm6NfZ+zvx4N0P2gtG39+YSF9mHNfaKBhQdzMlVO/KrIR4oK3gq6lnsPFbEAFuITVyTqXWccYMoFhRctUF0hACqgE4aZWx2vnMwYEAogPVVmyEjRJ+hbdVybkhyOK8TTxKh1McUt8bGU22ykNZokuXxqiu2mOFfnOiEwVMTvt8P3uMDAJ0swpeGwSbRvEk5DZ1j0mY34G0gaEyMkzDSfsFGlFb+PDenq7Zz9zb6+8K6gI3DrB6piB1ZN1qsgTHi/SaOCyFCdDtaSHDCd0hWtdv9lu8ul78fNhAHV0THNagsSORQeOTmq9b3AzqB1r+PnsndH1S/qFlsBZddUihMuPttDTbsQ1z+UdzgeWs',
2023     },
2024     {
2025       'accessKey': 'c2cfaaebb10f00ab',
2026       'payload': 'CAVH/4AwEJzNt950XEAZP3Q92fMNasIje6K5FSBgjqchkxmrFxjlNHjadnrHWdqM+zrB',
2027     },
2028     {
2029       'accessKey': '130b037dadbe1d7a',
2030       'payload': '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',
2031     },
2032     {
2033       'accessKey': 'd8e8dd84f4b0c103',
2034       'payload': 'EGKsJYSjVVaxCBWPRUGjWuLMl3k7fB/7uKYp8wz28r/5XTaOJF7LnbPMpBwysAR8IR/whArG',
2035     },
2036   ];
2038   game['fn'].loadSettings();
2039   game['fn'].applySettings();
2041   if(game.ui.root.querySelectorAll('.ui-page.credits .area h3').length > 3) {
2042     // If the credits have more than three third-level headers, that means we are
2043     // in the freeware version and can make the CSS adjustments it needs.
2044     let css = document.styleSheets[0];
2045     css.insertRule('.upInTheAirGame .ui-page.credits .person { position: relative; height: 4em; padding-left: calc(4em + 1ex); display: flex; flex-direction: column; justify-content: center; }');
2046     css.insertRule('.upInTheAirGame .ui-page.credits .person::before { content: " "; position: absolute; left: 0; box-sizing: border-box; width: 4em; height: 4em; background-size: contain; border-radius: .6em; border: .1em solid #d53c59; }');
2047     game.ui.root.querySelectorAll('.ui-page.credits .area .person').forEach((person) => {
2048       let personName = Array.from(person.classList).filter(c => c != 'person')[0];
2049       let imageFormat = (personName == 'nina') ? 'png' : 'jpg';
2050       css.insertRule('.upInTheAirGame .ui-page.credits .person.' + personName + '::before { background-image: url("' + game['deploymentOptions']['assetUrlPrefix'] + 'textures/person-' + personName + '.' + imageFormat + '"); }');
2051     });
2052   }
2054   game.ui.root.querySelectorAll('button.goto').forEach((btn) => {
2055     btn.addEventListener('click', (e) => {
2056       if(game.view && !game.view.music) {
2057         game.view.audioListener = new THREE.AudioListener();
2058         game.view.camera.add(game.view.audioListener);
2059         game.view.music = new THREE.Audio(game.view.audioListener);
2060         game.view.music.setBuffer(game.assets['audio']['music-' + game.settings['audio']['theme']]);
2061         game.view.music.setVolume(game.settings['audio']['music']);
2062         game.view.windSound = new THREE.Audio(game.view.audioListener);
2063         game.view.windSound.setBuffer(game.assets['audio']['wind']);
2064         game.view.windSound.setVolume(game.settings['audio']['sounds']);
2065         game.view.windSound.setLoop(false);
2066       }
2067       let btn = e.target.closest('button');
2068       let target = Array.from(btn.classList).filter(c => c != 'goto')[0];
2069       if(target == 'previous') {
2070         target = game.ui.previousPage;
2071       }
2072       game['fn'].moveToPage(target);
2073     });
2074   });
2076   game.ui.root.querySelectorAll('.options .controls input, .options .graphics input, .options .feather input, .options .accessibility input, .options .accessibility select').forEach((elem) => {
2077     elem.addEventListener('change', () => {
2078       game['fn'].applySettings();
2079       if(elem.name == 'upInTheAirGame-controls') {
2080         game.ui.root.querySelector('.controls .leftside').style.display = (['touchpad', 'thumbstick'].includes(game.settings['controls'])) ? 'block' : 'none';
2081         game.ui.root.querySelectorAll('.options .controls p span:not(.' + game.settings['controls'] + ')').forEach(span => span.style.display = 'none');
2082         game.ui.root.querySelector('.options .controls span.' + game.settings['controls']).style.display = 'block';
2083       } else if(elem.value == 'highcontrast' || elem.name == 'upInTheAirGame-graphics') {
2084         game['fn'].createMeshes();
2085       } else if(elem.name == 'upInTheAirGame-feather') {
2086         game['fn'].createFeather();
2087       }
2088     });
2089   });
2091   game.ui.root.querySelector('.ui-page.title .system-buttons input').addEventListener('change', (e) => {
2092     game.view.muted = e.target.checked;
2093   });
2095   game.ui.root.querySelector('.ui-page.title .system-buttons button').addEventListener('click', (e) => {
2096     if(document.fullscreenElement == game.ui.root.parentNode) {
2097       document.exitFullscreen();
2098     } else {
2099       game.ui.root.parentNode.requestFullscreen();
2100     }
2101   });
2103   game.ui.root.querySelectorAll('.ui-page .audio input[type=range]').forEach((elem) => {
2104     elem.addEventListener('input', (e) => {
2105       let audioCategory = Array.from(e.target.classList).filter(v => ['music', 'sounds'].includes(v))[0];
2106       game.ui.root.querySelector('.ui-page.options .audio input[type=range].' + audioCategory).value = e.target.value;
2107       game['fn'].applySettings();
2108     });
2109   });
2111   game.ui.root.querySelectorAll('.options .audio button').forEach((btn) => {
2112     btn.addEventListener('click', (e) => {
2113       if(e.target.classList.contains('music')) {
2114         if(game.view.music.isPlaying) {
2115           game.view.music.stop();
2116           if(game.view.music.timeoutID) {
2117             clearTimeout(game.view.music.timeoutID);
2118             delete game.view.music.timeoutID;
2119           }
2120         } else {
2121           game.view.music.offset = 36;
2122           if(!game.view.muted) {
2123             game.view.music.play();
2124           }
2125           game.view.music.timeoutID = setTimeout(() => {
2126             game.view.music.stop();
2127           }, 6000);
2128         }
2129       } else if(e.target.classList.contains('sounds')) {
2130         game['fn'].playRandomSound();
2131       }
2132     });
2133   });
2135   game.ui.root.querySelectorAll('.options .keyboard label button').forEach((btn) => {
2136     btn.addEventListener('click', () => {
2137       if(game.ui.root.querySelector('.ui-page.keyboard-modal')) {
2138         return;
2139       }
2140       const keyboardModal = document.createElement('div');
2141       keyboardModal.classList.add('ui-page', 'keyboard-modal');
2142       const instruction = document.createElement('span');
2143       const direction = btn.classList[0];
2144       keyboardModal.classList.add(direction);
2145       instruction.innerText = 'Please press the key for “' + direction[0].toUpperCase() + direction.slice(1) + '”';
2146       keyboardModal.appendChild(instruction);
2147       game.ui.root.appendChild(keyboardModal);
2148     });
2149   });
2151   game.ui.root.querySelector('.options .keyboard button[value="reset"]').addEventListener('click', (e) => {
2152     const container = e.target.parentNode;
2153     container.querySelector('button.up').value = 'ArrowUp|w';
2154     container.querySelector('button.right').value = 'ArrowRight|d';
2155     container.querySelector('button.down').value = 'ArrowDown|s';
2156     container.querySelector('button.left').value = 'ArrowLeft|a';
2157     game['fn'].applySettings();
2158     game['fn'].loadSettings();
2159   });
2161   game.ui.root.querySelectorAll('.ui-page .areatabs button').forEach((btn) => {
2162     btn.addEventListener('click', (e) => {
2163       btn.parentNode.querySelectorAll('button').forEach((otherBtn) => {
2164         otherBtn.classList.remove('active');
2165         let val = otherBtn.classList[0];
2166         otherBtn.closest('.ui-page').querySelector('div.' + val).style.display = 'none';
2167       });
2168       btn.classList.add('active');
2169       let val = Array.from(btn.classList).filter(c => c != 'active')[0];
2170       btn.closest('.ui-page').querySelector('div.' + val).style.display = 'flex';
2171     });
2172   });
2174   game.ui.root.style.fontSize = (game.ui.root.clientWidth / 48) + 'px';
2175   window.addEventListener('resize', () => {
2176     game.ui.root.style.fontSize = (game.ui.root.clientWidth / 48) + 'px';
2177   });
2179   window.addEventListener('scroll', () => {
2180     if(!['gameplay', 'openingcutscene', 'endingcutscene'].includes(game.ui.currentPage)) {
2181       return;
2182     }
2183     let bbox = game.ui.root.querySelector('canvas').getBoundingClientRect();
2184     if(bbox.bottom < -100 || bbox.top - bbox.height > 100 || bbox.left + bbox.width < -100 || bbox.left - window.innerWidth > 100) {
2185       game['fn'].moveToPage('pause', true);
2186     }
2187   });
2188   window.addEventListener('blur', () => {
2189     if(['gameplay', 'openingcutscene', 'endingcutscene'].includes(game.ui.currentPage)) {
2190       game['fn'].moveToPage('pause', true);
2191     }
2192   });
2194   document.addEventListener('keydown', (e) => {
2195     const keyboardModal = game.ui.root.querySelector('.keyboard-modal');
2196     if(keyboardModal) {
2197       const direction = [...keyboardModal.classList].filter(c => c != 'ui-page' && c != 'keyboard-modal')[0];
2198       if(e.key != 'Escape') {
2199         game.ui.root.querySelector('.options .keyboard label button.' + direction).value = e.key;
2200         game['fn'].applySettings();
2201         game['fn'].loadSettings();
2202       }
2203       keyboardModal.remove();
2204       e.preventDefault();
2205       e.stopPropagation();
2206       return;
2207     }
2208     if(game.ui.currentPage == 'title' && e.key.match(/[a-z]/)) {
2209       game.view.cheatBuffer = (game.view.cheatBuffer + e.key).slice(-25);
2210       for(let len = 10; len <= 25; len++) {
2211         if(game.view.cheatBuffer.length < len) {
2212           break;
2213         }
2214         let unlock = game['fn'].unlockWithKey(game.view.cheatBuffer.slice(-len));
2215         if(unlock && unlock['type'] == 'feather' && !game.settings['unlocks'].includes(unlock['name'])) {
2216           game['fn'].playRandomSound();
2217           game['fn'].unlockFeather(unlock['name'], unlock['url']);
2218           game['fn'].moveToPage('unlock');
2219         }
2220       }
2221       return;
2222     }
2223     if(e.key == 'Escape') {
2224       if(['gameplay', 'openingcutscene', 'endingcutscene'].includes(game.ui.currentPage)) {
2225         game['fn'].moveToPage('pause', true);
2226       } else if(game.ui.currentPage == 'pause') {
2227         game['fn'].moveToPage(game.ui.previousPage, true);
2228       }
2229     }
2230   });
2232   window.addEventListener('gamepadconnected', (e) => {
2233     game.ui.gamepads.push(e.gamepad);
2234   });
2235   window.addEventListener('gamepaddisconnected', (e) => {
2236     if(game.ui.gamepads.includes(e.gamepad)) {
2237       game.ui.gamepads.splice(game.ui.gamepads.indexOf(e.gamepad), 1);
2238     }
2239   });
2241   game.ui.root.querySelector('.ui-page.pause button.title').addEventListener('click', () => {
2242     game['fn'].reset();
2243   });
2245   game['fn'].loadAllAssets((progress) => {
2246     let percentage = Math.floor(100 * progress);
2247     game.ui.root.querySelector('.ui-page.loading progress').value = percentage;
2248     game.ui.root.querySelector('.ui-page.loading span').innerText = percentage;
2249   }).then(() => {
2250     if(window.location.hostname == 'fietkau.media' && window.location.pathname == '/up_in_the_air') {
2251       game.ui.root.querySelector('.ui-page.title .footer span:last-child').remove();
2252     }
2253     let controlsInterstitial = false;
2254     if(!game.settings['controls']) {
2255       controlsInterstitial = true;
2256       let control;
2257       if(matchMedia('(hover: hover)').matches) {
2258         control = 'mouse';
2259       } else {
2260         control = 'touchpad';
2261       }
2262       game.ui.root.querySelector('.controls input[value="' + control + '"]').checked = true;
2263       game['fn'].applySettings();
2264       game['fn'].loadSettings();
2265       game.ui.root.querySelectorAll('.ui-page.controls .' + ((control == 'mouse') ? 'touchpad' : 'mouse')).forEach(elem => elem.remove());
2266     }
2267     if(!game.assets.audiothemes.includes(game.settings['audio']['theme'])) {
2268       game.settings['audio']['theme'] = game.assets.audiothemes[0];
2269     }
2270     if(game.assets.audiothemes.length == 1) {
2271       game.ui.root.querySelector('.ui-page.options .audiotheme').style.display = 'none';
2272     }
2273     let container = game.ui.root.querySelector('.ui-page.options .audiotheme');
2274     for(let audioTheme of game.assets.audiothemes) {
2275       let snippet = container.children[0].content.cloneNode(true).children[0];
2276       snippet.children[0].value = audioTheme;
2277       if(audioTheme == game.settings['audio']['theme']) {
2278         snippet.children[0].checked = true;
2279       }
2280       snippet.children[0].addEventListener('change', () => {
2281         game['fn'].applySettings();
2282         game.view.music.setBuffer(game.assets['audio']['music-' + game.settings['audio']['theme']]);
2283       });
2284       snippet.childNodes[1].textContent = ' ' + audioTheme[0].toUpperCase() + audioTheme.slice(1);
2285       container.appendChild(snippet);
2286     }
2287     if(controlsInterstitial) {
2288       game['fn'].moveToPage('controls');
2289     } else {
2290       game['fn'].moveToPage('title');
2291     }
2292   }, (err) => {
2293     console.error(err);
2294   });
2296 };
2298 // Set up name mirrors for each function that should survive most minifiers and transpilers
2299 game['fn'].animate['friendlyName'] = 'animate';
2300 game['fn'].applyForceToFeather['friendlyName'] = 'applyForceToFeather';
2301 game['fn'].applySettings['friendlyName'] = 'applySettings';
2302 game['fn'].createFeather['friendlyName'] = 'createFeather';
2303 game['fn'].createMeshes['friendlyName'] = 'createMeshes';
2304 game['fn'].easeInOut['friendlyName'] = 'easeInOut';
2305 game['fn'].initializeGame['friendlyName'] = 'initializeGame';
2306 game['fn'].lerp['friendlyName'] = 'lerp';
2307 game['fn'].loadAllAssets['friendlyName'] = 'loadAllAssets';
2308 game['fn'].loadSettings['friendlyName'] = 'loadSettings';
2309 game['fn'].moveToPage['friendlyName'] = 'moveToPage';
2310 game['fn'].playRandomSound['friendlyName'] = 'playRandomSound';
2311 game['fn'].prepareWordMesh['friendlyName'] = 'prepareWordMesh';
2312 game['fn'].reset['friendlyName'] = 'reset';
2313 game['fn'].start['friendlyName'] = 'start';
2314 game['fn'].unlockFeather['friendlyName'] = 'unlockFeather';
2315 game['fn'].unlockWithKey['friendlyName'] = 'unlockWithKey';
2317 game['fn'].start();