BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / engine / game.js

game.js

game.js 5.0 KiB Download Raw
1class Game
2{
3 activeScenes = [];
4 pendingRemoval = [];
5
6 previousStep = 0; //used for calculating deltaTime
7 isRunning = false;
8 rafId = null;
9
10 images = {};
11 shaders = {};
12
13 constructor ()
14 {
15 this.previousStep = 0;
16 this.activeScenes = [];
17 this.isRunning = false;
18 this.rafId = null;
19 this.shaders = {};
20 this.update = this.update.bind(this);
21 }
22
23 startGame ()
24 {
25 GameInput.g_init();
26
27 if (this.isRunning)
28 { return; }
29
30 this.isRunning = true;
31 this.previousStep = Date.now();
32 this.update();
33 }
34
35 stopGame ()
36 {
37 this.isRunning = false;
38 if (this.rafId != null)
39 {
40 cancelAnimationFrame(this.rafId);
41 this.rafId = null;
42 }
43 }
44
45 preloadImagesThenStart (imageData, onComplete, onError)
46 {
47 const cont = async () =>
48 {
49 try
50 {
51 await this.preloadImages(
52 imageData
53 );
54
55 this.startGame();
56 onComplete && onComplete();
57 }
58 catch (err)
59 {
60 console.error("GAME: Image preload failed.", err);
61 onError && onError(err);
62 }
63 };
64
65 cont();
66 }
67
68 setPrimaryScene (scene)
69 {
70 if (this.activeScenes.contains(scene))
71 {
72 for (let i = 0; i < this.activeScenes.length; i++)
73 { this.activeScenes[i].g_primary = false; }
74
75 scene.g_primary = true;
76 }
77 }
78
79 async preloadImages (imagesData)
80 {
81 const promises = [];
82 const context = this;
83
84 for (var imageData of imagesData)
85 {
86 if (context.images[imageData.name])
87 {
88 console.warn("Image '" + imageData.name + "' is already loaded! (overwriting anyway)");
89 }
90
91 promises.push(new Promise((resolve, reject) =>
92 {
93 var img = new Image();
94 var imageContext = { name: imageData.name, subImgTotal: imageData.subImgTotal, perRow: imageData.perRow, loop: imageData.loop, chain: imageData.chain };
95
96 img.onload = function ()
97 {
98 var finalImage = new image(img, imageContext.subImgTotal, imageContext.perRow, imageContext.loop, imageContext.chain);
99 finalImage.name = imageContext.name;
100
101 context.images[imageContext.name] = finalImage;
102
103 resolve();
104 };
105
106 img.onerror = function ()
107 {
108 reject(new Error("Failed to load image '" + imageContext.name + "' from " + imageData.url));
109 };
110
111 img.src = imageData.url;
112 img.setAttribute("style", "display:none");
113 }));
114 }
115 await Promise.all(promises);
116
117 console.log("all images loaded ", this.images);
118
119 return this.images;
120 }
121
122 async preloadShaders (shadersData)
123 {
124 const context = this;
125 const promises = [];
126
127 for (const shaderData of shadersData)
128 {
129 if (!shaderData || !shaderData.name)
130 { throw new Error("preloadShaders: each entry needs a name"); }
131
132 if (!shaderData.frag)
133 { throw new Error("preloadShaders: '" + shaderData.name + "' needs a frag path"); }
134
135 if (context.shaders[shaderData.name])
136 { console.warn("Shader '" + shaderData.name + "' is already loaded! (overwriting anyway)"); }
137
138 promises.push((async () =>
139 {
140 let vertSource = shaderData.screen ? Shader.SCREEN_VERT : Shader.DEFAULT_VERT;
141
142 if (shaderData.vert)
143 {
144 const vertResponse = await fetch(shaderData.vert);
145 if (!vertResponse.ok)
146 {
147 throw new Error("Failed to load vertex shader '" + shaderData.name + "' from " + shaderData.vert);
148 }
149
150 vertSource = await vertResponse.text();
151 }
152
153 const fragResponse = await fetch(shaderData.frag);
154 if (!fragResponse.ok)
155 {
156 throw new Error("Failed to load fragment shader '" + shaderData.name + "' from " + shaderData.frag);
157 }
158
159 const fragSource = await fragResponse.text();
160 const shader = new Shader(vertSource, fragSource);
161 shader.name = shaderData.name;
162 shader.screen = !!shaderData.screen || vertSource === Shader.SCREEN_VERT;
163 context.shaders[shaderData.name] = shader;
164 })());
165 }
166
167 await Promise.all(promises);
168 console.log("all shaders loaded ", this.shaders);
169 return this.shaders;
170 }
171
172 loadScene (scene)
173 {
174 if (this.activeScenes.length == 0)
175 { scene.g_primary = true; }
176
177 this.activeScenes.push(scene);
178 scene.game = this;
179 scene.onLoad();
180 }
181
182 removeScene (scene)
183 {
184 if (this.activeScenes.indexOf(scene) >= 0)
185 {
186 if (!this.pendingRemoval.contains(scene))
187 { this.pendingRemoval.push(scene); }
188 }
189 }
190
191 update ()
192 {
193 this.previousStep = this.previousStep || 0;
194 const stepTime = Date.now();
195 let stepTimeCurr = (stepTime - this.previousStep) * 0.001;
196 stepTimeCurr = Math.min(stepTimeCurr, 0.1);
197 if (isNaN(stepTimeCurr))
198 { stepTimeCurr = 0; }
199
200 GameInput.g_updateKeys();
201
202 for (let i = 0; i < this.activeScenes.length; i++)
203 {
204 this.activeScenes[i].update(stepTimeCurr);
205 this.activeScenes[i].draw();
206 }
207
208 this.cleanActiveScenes();
209
210 this.previousStep = stepTime;
211
212 TWEEN.update();
213
214 if (this.isRunning)
215 { this.rafId = requestAnimationFrame(this.update); }
216 }
217
218 cleanActiveScenes ()
219 {
220 if (this.pendingRemoval.length > 0)
221 {
222 for (let i = 0; i < this.pendingRemoval.length; i++)
223 {
224 const scene = this.pendingRemoval[i];
225 const index = this.activeScenes.indexOf(scene);
226 if (index >= 0 && scene.destroyed)
227 { this.activeScenes.removeAt(index); }
228 }
229
230 this.pendingRemoval.length = 0;
231 }
232 }
233}