-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathtable.ts
544 lines (480 loc) · 17.1 KB
/
table.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
/*
* VPDB - Virtual Pinball Database
* Copyright (C) 2019 freezy <freezy@vpdb.io>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import { Event } from '../../game/event';
import { EventProxy } from '../../game/event-proxy';
import { IAnimatable, isAnimatable } from '../../game/ianimatable';
import { IHittable, isHittable } from '../../game/ihittable';
import { IMovable, isMovable } from '../../game/imovable';
import { IPlayable, isPlayable } from '../../game/iplayable';
import { IRenderable, isRenderable, Meshes } from '../../game/irenderable';
import { IScriptable, isScriptable } from '../../game/iscriptable';
import { Player } from '../../game/player';
import { IBinaryReader, Storage } from '../../io/ole-doc';
import { degToRad, f4 } from '../../math/float';
import { FRect3D } from '../../math/frect3d';
import { Vertex3D } from '../../math/vertex3d';
import { HitObject } from '../../physics/hit-object';
import { HitPlane } from '../../physics/hit-plane';
import { IRenderApi } from '../../render/irender-api';
import { Transpiler } from '../../scripting/transpiler';
import { logger, progress } from '../../util/logger';
import { Bumper } from '../bumper/bumper';
import { Collection } from '../collection/collection';
import { Decal } from '../decal/decal';
import { DispReel } from '../dispreel/dispreel';
import { Flasher } from '../flasher/flasher';
import { Flipper } from '../flipper/flipper';
import { Gate } from '../gate/gate';
import { HitTarget } from '../hit-target/hit-target';
import { Item } from '../item';
import { ItemData } from '../item-data';
import { ItemState } from '../item-state';
import { Kicker } from '../kicker/kicker';
import { Light } from '../light/light';
import { LightSeq } from '../lightseq/lightseq';
import { Material } from '../material';
import { Plunger } from '../plunger/plunger';
import { Primitive } from '../primitive/primitive';
import { Ramp } from '../ramp/ramp';
import { Rubber } from '../rubber/rubber';
import { Spinner } from '../spinner/spinner';
import { Surface } from '../surface/surface';
import { Textbox } from '../textbox/textbox';
import { Texture } from '../texture';
import { Timer } from '../timer/timer';
import { Trigger } from '../trigger/trigger';
import { TableApi } from './table-api';
import { TableData } from './table-data';
import { TableExportOptions } from './table-exporter';
import { TableHitGenerator } from './table-hit-generator';
import { LoadedTable, TableLoader } from './table-loader';
import { TableMeshGenerator } from './table-mesh-generator';
import { TableState } from './table-state';
import { TableUpdater } from './table-updater';
/**
* A Visual Pinball table.
*
* This holds together all table elements of a .vpt/.vpx file. It's also
* the entry point for parsing the file.
*/
export class Table implements IScriptable<TableApi>, IRenderable<TableState> {
public readonly data?: TableData;
public readonly info?: { [key: string]: string };
public readonly items: { [key: string]: Item<ItemData> };
public readonly tableScript?: string;
private readonly state?: TableState;
private readonly updater?: TableUpdater;
private events?: EventProxy;
private api?: TableApi;
private itemIndex?: { [key: string]: string };
public readonly textures: { [key: string]: Texture } = {};
public readonly collections: { [key: string]: Collection } = {};
public readonly bumpers: { [key: string]: Bumper } = {};
public readonly flippers: { [key: string]: Flipper } = {};
public readonly flashers: { [key: string]: Flasher } = {};
public readonly gates: { [key: string]: Gate } = {};
public readonly hitTargets: { [key: string]: HitTarget } = {};
public readonly kickers: { [key: string]: Kicker } = {};
public readonly lights: { [key: string]: Light } = {};
public readonly plungers: { [key: string]: Plunger } = {};
public readonly primitives: { [key: string]: Primitive } = {};
public readonly ramps: { [key: string]: Ramp } = {};
public readonly rubbers: { [key: string]: Rubber } = {};
public readonly spinners: { [key: string]: Spinner } = {};
public readonly surfaces: { [key: string]: Surface } = {};
public readonly textboxes: { [key: string]: Textbox } = {};
public readonly timers: { [key: string]: Timer } = {};
public readonly triggers: { [key: string]: Trigger } = {};
public readonly decals: { [key: string]: Decal } = {};
public readonly lightSeqs: { [key: string]: LightSeq } = {};
public readonly dispReels: { [key: string]: DispReel } = {};
private readonly meshGenerator?: TableMeshGenerator;
private readonly hitGenerator?: TableHitGenerator;
private readonly loader: TableLoader;
public static playfieldThickness = 20.0;
public static async load(reader: IBinaryReader, opts?: TableLoadOptions): Promise<Table> {
opts = opts || defaultTableLoadOptions;
const tableLoader = new TableLoader();
return new Table(tableLoader, await tableLoader.load(reader, opts));
}
public constructor(loader: TableLoader, loadedTable: LoadedTable) {
this.loader = loader;
this.items = loadedTable.items;
if (loadedTable.data) {
this.data = loadedTable.data;
this.meshGenerator = new TableMeshGenerator(this);
this.hitGenerator = new TableHitGenerator(loadedTable.data);
this.state = TableState.claim(this.data.getName(), this.data.szPlayfieldMaterial, true);
this.updater = new TableUpdater(this.state);
}
if (loadedTable.info) {
this.info = loadedTable.info;
}
if (loadedTable.tableScript) {
this.tableScript = loadedTable.tableScript;
}
const mapping: Array<[any, any]> = [
[loadedTable.textures, this.textures],
[loadedTable.collections, this.collections],
[loadedTable.bumpers, this.bumpers],
[loadedTable.flippers, this.flippers],
[loadedTable.flashers, this.flashers],
[loadedTable.gates, this.gates],
[loadedTable.hitTargets, this.hitTargets],
[loadedTable.kickers, this.kickers],
[loadedTable.lights, this.lights],
[loadedTable.plungers, this.plungers],
[loadedTable.primitives, this.primitives],
[loadedTable.ramps, this.ramps],
[loadedTable.rubbers, this.rubbers],
[loadedTable.spinners, this.spinners],
[loadedTable.surfaces, this.surfaces],
[loadedTable.textBoxes, this.textboxes],
[loadedTable.timers, this.timers],
[loadedTable.triggers, this.triggers],
[loadedTable.decals, this.decals],
[loadedTable.lightSeqs, this.lightSeqs],
[loadedTable.dispReels, this.dispReels],
];
for (const m of mapping) {
if (isLoaded(m[0])) {
for (const item of m[0]) {
m[1][item.getName()] = item;
}
}
}
}
public getName(): string {
return this.data!.getName();
}
public getTexture(name?: string): Texture | undefined {
if (!name) {
return undefined;
}
return this.textures[name.toLowerCase()];
}
public getMaterial(name?: string): Material | undefined {
if (!name) {
return undefined;
}
/* istanbul ignore if */
if (!this.data) {
throw new Error('Table data is not loaded. Load table with tableDataOnly = false.');
}
return this.data.materials.find(m => m.name === name);
}
public getApi(): TableApi {
return this.api!;
}
public getState(): TableState {
return this.state!;
}
public getUpdater(): TableUpdater {
return this.updater!;
}
public getEventNames(): string[] {
return [ 'Exit', 'Init', 'KeyDown', 'KeyUp', 'MusicDone', 'Paused', 'UnPaused' ];
}
public setupPlayer(player: Player, table: Table): void {
this.events = new EventProxy(this);
this.api = new TableApi(this.data!, this.events, player, this);
}
public getBoundingBox(): FRect3D {
return new FRect3D(this.data!.left, this.data!.right, this.data!.top, this.data!.bottom, this.getTableHeight(), this.data!.glassHeight);
}
public getPlayables(): IPlayable[] {
const playableItems = this.getItems().filter(isPlayable) as unknown as IPlayable[];
return [ this, ...playableItems ];
}
public getMovables(): IMovable[] {
return this.getItems().filter(isMovable) as unknown as IMovable[];
}
public getRenderables(): Array<IRenderable<ItemState>> {
return this.getItems().filter(isRenderable) as unknown as Array<IRenderable<ItemState>>;
}
public getAnimatables(): IAnimatable[] {
return this.getItems().filter(isAnimatable) as unknown as IAnimatable[];
}
public getScriptables(): Array<IScriptable<any>> {
const scriptableItems = this.getItems().filter(isScriptable) as unknown as Array<IScriptable<any>>;
return [ this, ...scriptableItems ];
}
public getHittables(): IHittable[] {
return this.getItems().filter(isHittable) as unknown as IHittable[];
}
public getHitShapes(): HitObject[] {
return this.hitGenerator!.generateHitObjects();
}
public generatePlayfieldHit() {
return new HitPlane(new Vertex3D(0, 0, 1), this.data!.tableHeight)
.setFriction(this.data!.getFriction())
.setElasticity(this.data!.getElasticity(), this.data!.getElasticityFalloff())
.setScatter(degToRad(this.data!.getScatter()));
}
public generateGlassHit() {
return new HitPlane(new Vertex3D(0, 0, -1), this.data!.glassHeight)
.setElasticity(0.2);
}
public getElementApis(): { [key: string]: any } {
const apis: { [key: string]: any } = {};
const elements = this.getScriptables();
for (const element of elements) {
apis[element.getName()] = element.getApi();
}
return apis;
}
public getElementApiName(vbsName: string): string {
if (!this.itemIndex) {
this.itemIndex = {};
for (const element of this.getScriptables()) {
this.itemIndex[element.getName().toLowerCase()] = element.getName();
}
}
return this.itemIndex[vbsName.toLowerCase()];
}
public getElements(): { [key: string]: IScriptable<any> } {
const elements: { [key: string]: any } = {};
const elementList = this.getScriptables();
for (const element of elementList) {
elements[element.getName()] = element;
}
return elements;
}
public getScaleZ(): number {
/* istanbul ignore if */
if (!this.data) {
throw new Error('Table data is not loaded. Load table with tableDataOnly = false.');
}
return f4(this.data.bgScaleZ[this.data.bgCurrentSet]) || 1.0;
}
public getDetailLevel() {
return 10; // todo check if true
}
public getGlobalDifficulty(): number {
return this.data!.globalDifficulty!;
}
public getTableHeight() {
/* istanbul ignore if */
if (!this.data) {
throw new Error('Table data is not loaded. Load table with tableDataOnly = false.');
}
return this.data.tableHeight;
}
public getDimensions(): { width: number, height: number } {
/* istanbul ignore if */
if (!this.data) {
throw new Error('Table data is not loaded. Load table with tableDataOnly = false.');
}
return {
width: this.data.right - this.data.left,
height: this.data.bottom - this.data.top,
};
}
public getPlayfieldMap(): string {
/* istanbul ignore if */
if (!this.data) {
throw new Error('Table data is not loaded. Load table with tableDataOnly = false.');
}
return this.data.szImage || '';
}
public getSurfaceHeight(surface: string | undefined, x: number, y: number) {
/* istanbul ignore if */
if (!this.data) {
throw new Error('Table data is not loaded. Load table with tableDataOnly = false.');
}
if (!surface) {
return this.data.tableHeight;
}
if (this.surfaces[surface]) {
return f4(this.data.tableHeight + this.surfaces[surface].heightTop);
}
if (this.ramps[surface]) {
return f4(this.data.tableHeight + this.ramps[surface].getSurfaceHeight(x, y, this));
}
/* istanbul ignore next */
logger().warn('[Table.getSurfaceHeight] Unknown surface %s.', surface);
return this.data.tableHeight;
}
// public async exportGltf(opts?: TableExportOptions): Promise<string> {
// const exporter = new TableExporter(this, opts || {});
// return await exporter.exportGltf();
// }
// public async exportGlb(opts?: TableExportOptions): Promise<Buffer> {
// const exporter = new TableExporter(new ThreeRenderApi(), this, opts || {});
// return await exporter.exportGlb();
// }
public async streamStorage<T>(name: string, streamer: (stg: Storage) => Promise<T>): Promise<T> {
return this.loader.streamStorage(name, streamer);
}
public getTableScript(): string {
/* istanbul ignore if */
if (!this.tableScript) {
throw new Error('Table script is not loaded. Load table with loadTableScript = true.');
}
return this.tableScript;
}
public isVisible(): boolean {
return true;
}
public getMeshes<NODE, GEOMETRY, POINT_LIGHT>(table: Table, renderApi: IRenderApi<NODE, GEOMETRY, POINT_LIGHT>, opts: TableExportOptions): Meshes<GEOMETRY> {
/* istanbul ignore if */
if (!this.data) {
throw new Error('Table data is not loaded. Load table with tableDataOnly = false.');
}
const geometry = this.meshGenerator!.getPlayfieldMesh(renderApi, opts);
return {
playfield: {
isVisible: true,
geometry,
material: this.getMaterial(this.data.szPlayfieldMaterial),
map: this.getTexture(this.data.szImage),
},
};
}
/**
* Generates the top-most node for the render engine that contains the entire table.
*
* @param renderApi Render API
* @param opts Which elements to generate
*/
public async generateTableNode<NODE, GEOMETRY, POINT_LIGHT>(renderApi: IRenderApi<NODE, GEOMETRY, POINT_LIGHT>, opts: TableExportOptions = {}): Promise<NODE> {
await renderApi.preloadTextures(Object.values(this.textures), this);
return this.meshGenerator!.generateTableNode(renderApi, opts);
}
public prepareToPlay() {
for (const primitive of Object.values<Primitive>(this.primitives)) {
primitive.clearMesh();
}
}
public runTableScript(player: Player, scope = {}): void {
if (!this.tableScript) {
logger().warn('Table script is not loaded!');
return;
}
progress().show('Transpiling and executing table script');
const transpiler = new Transpiler(this, player);
transpiler.execute(this.tableScript, scope);
logger().info('Table script loaded, transpiled and executed.');
}
public broadcastInit() {
this.events!.fireVoidEvent(Event.GameEventsInit);
for (const hittable of this.getHittables()) {
hittable.getEventProxy().fireVoidEvent(Event.GameEventsInit);
}
}
public fireVoidEvent(event: Event): this {
this.events!.fireVoidEvent(event);
return this;
}
public setupCollections() {
for (const tableItem of Object.keys(this.items)) {
if (isScriptable(tableItem)) {
tableItem.getApi()._resetCollections();
}
}
for (const collection of Object.values(this.collections)) {
for (const itemName of collection.getItemNames()) {
const tableItem = this.items[itemName];
if (!tableItem) {
logger().warn('Non-existent item "%s" in collection "%s", skipping.', itemName, collection.getName());
break;
}
if (isScriptable(tableItem)) {
tableItem.getApi()._addCollection(collection, collection.items.length);
collection.items.push(tableItem.getApi());
}
}
}
}
public getItems(): Array<Item<ItemData>> {
return Object.values(this.items);
}
}
function isLoaded(items: any[] | undefined) {
return items && items.length > 0;
}
const defaultTableLoadOptions: TableLoadOptions = {
tableDataOnly: false,
tableInfoOnly: false,
loadInvisibleItems: true,
loadTableScript: true,
};
export interface TableLoadOptions {
/**
* If set, don't parse game items but only game data (faster).
*/
tableDataOnly?: boolean;
/**
* If set, ignore game storage and only parse table info.
*/
tableInfoOnly?: boolean;
/**
* If set, also parse items like timers, i.e. non-visible items.
*/
loadInvisibleItems?: boolean;
/**
* If set, table script is read
*/
loadTableScript?: boolean;
/**
* If set, skips reading primitive mesh data.
*/
skipMeshes?: boolean;
}
export interface TableGenerateOptions {
exportPlayfield?: boolean;
exportPrimitives?: boolean;
exportRubbers?: boolean;
exportSurfaces?: boolean;
exportFlippers?: boolean;
exportBumpers?: boolean;
exportRamps?: boolean;
exportLightBulbs?: boolean;
exportPlayfieldLights?: boolean;
exportLightBulbLights?: boolean;
exportHitTargets?: boolean;
exportGates?: boolean;
exportKickers?: boolean;
exportTriggers?: boolean;
exportSpinners?: boolean;
exportPlungers?: boolean;
gltfOptions?: TableGenerateGltfOptions;
}
export interface TableGenerateGltfOptions {
binary?: boolean;
optimizeImages?: boolean;
trs?: boolean;
onlyVisible?: boolean;
truncateDrawRange?: boolean;
embedImages?: boolean;
animations?: any[];
forceIndices?: boolean;
forcePowerOfTwoTextures?: boolean;
compressVertices?: boolean;
versionString?: string;
dracoOptions?: {
compressionLevel?: number;
quantizePosition?: number;
quantizeNormal?: number;
quantizeTexcoord?: number;
quantizeColor?: number;
quantizeSkin?: number;
unifiedQuantization?: boolean;
};
}