-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathffl.js
More file actions
3933 lines (3546 loc) · 137 KB
/
ffl.js
File metadata and controls
3933 lines (3546 loc) · 137 KB
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* Bindings for FFL, a Mii renderer, in JavaScript.
* Uses the FFL decompilation by aboood40091.
* https://github.com/ariankordi/FFL.js
* @author Arian Kordi <https://github.com/ariankordi>
*/
// @ts-check
import * as THREE from 'three';
/**
* Generic type for both types of Three.js renderer.
* @typedef {import('three/webgpu').Renderer|THREE.WebGLRenderer} Renderer
*/
// // ---------------------------------------------------------------------
// // Emscripten Module Type
// // ---------------------------------------------------------------------
// TODO PATH: src/ModuleType.js
/**
* Emscripten "Module" type.
* https://github.com/DefinitelyTyped/DefinitelyTyped/blob/c03bddd4d3c7774d00fa256a9e165d68c7534ccc/types/emscripten/index.d.ts#L26
* This lists common Emscripten methods for interacting with memory,
* as well as functions used in the FFL library itself.
* @typedef {Object} Module
* @property {function(): void} onRuntimeInitialized
* @property {function(object): void} destroy
* @property {boolean|null} calledRun
* // USE_TYPED_ARRAYS == 2
* @property {Uint8Array} HEAPU8
* @property {Uint32Array} HEAPU32
* @property {Float32Array} HEAPF32
* @property {Int8Array} HEAP8 - Used for some vertex attributes.
* @property {Uint16Array} HEAPU16 - Used for index buffer.
* Runtime methods:
* @property {function(number): number} _malloc
* @property {function(number): void} _free
* @property {function((...args: *[]) => *, string=): number} addFunction
* @property {function(number): void} removeFunction
* @property {undefined|function(): void} _exit - Only included with a certain Emscripten linker flag.
*
* ------------------------------- FFL Bindings -------------------------------
* Utilized functions:
* @property {function(number, number, number, number): *} _FFLInitCharModelCPUStepWithCallback
* @property {function(number): *} _FFLDeleteCharModel
* @property {function(number, number, number, number): *} _FFLiGetRandomCharInfo
* @property {function(number, number): *} _FFLpGetCharInfoFromStoreData
* @property {function(number, number): *} _FFLpGetCharInfoFromMiiDataOfficialRFL
* @property {function(number, number): *} _FFLInitRes
* @property {function(): *} _FFLInitResGPUStep
* @property {function(): *} _FFLExit
* @property {function(number, number): *} _FFLGetFavoriteColor
* @property {function(number, number): *} _FFLGetFacelineColor
* @property {function(boolean): *} _FFLSetTextureFlipY
* @property {function(boolean): *} _FFLSetNormalIsSnorm8_8_8_8
* @property {function(boolean): *} _FFLSetFrontCullForFlipX
* @property {function(number): *} _FFLSetTextureCallback
* @property {function(number): *} _FFLiDeleteTextureTempObject
* @property {function(number, number, number): *} _FFLiDeleteTempObjectMaskTextures
* @property {function(number, number, number): *} _FFLiDeleteTempObjectFacelineTexture
* @property {function(number): *} _FFLiInvalidateTempObjectFacelineTexture
* @property {function(number): *} _FFLiInvalidateRawMask
* @property {function(number, boolean): *} _FFLiVerifyCharInfoWithReason
* These functions are NOT called directly:
* @property {function(number): *} _FFLiiGetEyeRotateOffset
* @property {function(number): *} _FFLiiGetEyebrowRotateOffset
* @property {function(number): *} _FFLSetLinearGammaMode
* @property {function(number, number): *} _FFLpGetStoreDataFromCharInfo
* @property {function(number, number, number, number, boolean): *} _FFLGetAdditionalInfo -
* The output is encoded in a bitfield that has to be decoded, so it's not used now,
* but to get "additional info" would be nice in general.
* @package
*/
// // ---------------------------------------------------------------------
// // Enum Definitions
// // ---------------------------------------------------------------------
// TODO PATH: src/Enums.js
/**
* Result type for Face Library functions (not the real FFL enum).
* Reference: https://github.com/aboood40091/ffl/blob/master/include/nn/ffl/FFLResult.h
* @enum {number}
* @package
*/
const FFLResult = {
OK: 0,
ERROR: 1,
HDB_EMPTY: 2,
FILE_INVALID: 3,
MANAGER_NOT_CONSTRUCT: 4,
FILE_LOAD_ERROR: 5,
// : 6,
FILE_SAVE_ERROR: 7,
// : 8,
RES_FS_ERROR: 9,
ODB_EMPTY: 10,
// : 11,
OUT_OF_MEMORY: 12,
// : 13,
// : 14,
// : 15,
// : 16,
UNKNOWN_17: 17,
FS_ERROR: 18,
FS_NOT_FOUND: 19,
MAX: 20
};
/**
* Indicates how the shape should be colored by the fragment shader.
* @enum {number}
* @public
*/
const FFLModulateMode = {
/** No Texture, Has Color (R) */
CONSTANT: 0,
/** Has Texture, No Color */
TEXTURE_DIRECT: 1,
/** Has Texture, Has Color (R + G + B) */
RGB_LAYERED: 2,
/** Has Texture, Has Color (R) */
ALPHA: 3,
/** Has Texture, Has Color (R) */
LUMINANCE_ALPHA: 4,
/** Has Texture, Has Color (R) */
ALPHA_OPA: 5
};
/**
* This is the type of shape to be rendered.
* It's separated into: opaque, translucent,
* and past SHAPE_MAX is for faceline/mask.
* @enum {number}
* @public
*/
const FFLModulateType = {
SHAPE_FACELINE: 0,
SHAPE_BEARD: 1,
SHAPE_NOSE: 2,
SHAPE_FOREHEAD: 3,
SHAPE_HAIR: 4,
SHAPE_CAP: 5,
SHAPE_MASK: 6,
SHAPE_NOSELINE: 7,
SHAPE_GLASS: 8,
MUSTACHE: 9,
MOUTH: 10,
EYEBROW: 11,
EYE: 12,
MOLE: 13,
FACE_MAKE: 14,
FACE_LINE: 15,
FACE_BEARD: 16,
FILL: 17,
SHAPE_MAX: 9
};
/**
* IDs corresponding to expressions.
* Reference: https://github.com/ariankordi/ffl/blob/nsmbu-win-port-linux64/include/nn/ffl/FFLExpression.h
* @enum {number}
* @public
*/
const FFLExpression = {
NORMAL: 0,
SMILE: 1,
ANGER: 2,
/** Primary name for expression 3. */
SORROW: 3,
PUZZLED: 3,
/** Primary name for expression 4. */
SURPRISE: 4,
SURPRISED: 4,
BLINK: 5,
OPEN_MOUTH: 6,
/** Primary name for expression 7. */
SMILE_OPEN_MOUTH: 7,
HAPPY: 7,
ANGER_OPEN_MOUTH: 8,
SORROW_OPEN_MOUTH: 9,
SURPRISE_OPEN_MOUTH: 10,
BLINK_OPEN_MOUTH: 11,
WINK_LEFT: 12,
WINK_RIGHT: 13,
WINK_LEFT_OPEN_MOUTH: 14,
WINK_RIGHT_OPEN_MOUTH: 15,
/** Primary name for expression 16. */
LIKE_WINK_LEFT: 16,
LIKE: 16,
LIKE_WINK_RIGHT: 17,
FRUSTRATED: 18,
// Additional expressions from AFL.
// Enum names are completely made up.
BORED: 19,
BORED_OPEN_MOUTH: 20,
SIGH_MOUTH_STRAIGHT: 21,
SIGH: 22,
DISGUSTED_MOUTH_STRAIGHT: 23,
DISGUSTED: 24,
LOVE: 25,
LOVE_OPEN_MOUTH: 26,
DETERMINED_MOUTH_STRAIGHT: 27,
DETERMINED: 28,
CRY_MOUTH_STRAIGHT: 29,
CRY: 30,
BIG_SMILE_MOUTH_STRAIGHT: 31,
BIG_SMILE: 32,
CHEEKY: 33,
CHEEKY_DUPLICATE: 34,
JOJO_EYES_FUNNY_MOUTH: 35,
JOJO_EYES_FUNNY_MOUTH_OPEN: 36,
SMUG: 37,
SMUG_OPEN_MOUTH: 38,
RESOLVE: 39,
RESOLVE_OPEN_MOUTH: 40,
UNBELIEVABLE: 41,
UNBELIEVABLE_DUPLICATE: 42,
CUNNING: 43,
CUNNING_DUPLICATE: 44,
RASPBERRY: 45,
RASPBERRY_DUPLICATE: 46,
INNOCENT: 47,
INNOCENT_DUPLICATE: 48,
CAT: 49,
CAT_DUPLICATE: 50,
DOG: 51,
DOG_DUPLICATE: 52,
TASTY: 53,
TASTY_DUPLICATE: 54,
MONEY_MOUTH_STRAIGHT: 55,
MONEY: 56,
SPIRAL_MOUTH_STRAIGHT: 57,
CONFUSED: 58,
CHEERFUL_MOUTH_STRAIGHT: 59,
CHEERFUL: 60,
BLANK_61: 61,
BLANK_62: 62,
GRUMBLE_MOUTH_STRAIGHT: 63,
GRUMBLE: 64,
MOVED_MOUTH_STRAIGHT: 65,
MOVED: 66,
SINGING_MOUTH_SMALL: 67,
SINGING: 68,
STUNNED: 69,
MAX: 70
};
/**
* Flags that modify how the head model is created.
* These go in {@link FFLCharModelDesc.modelFlag}.
* @enum {number}
* @public
*/
const FFLModelFlag = {
/** Default model setting. */
NORMAL: 1, // 1 << 0
/** Uses a variant of hair designed for hats. */
HAT: 1 << 1,
/** Discards hair from the model, used for helmets and similar headwear. */
FACE_ONLY: 1 << 2,
/** Limits Z depth on the nose, useful for helmets and similar headwear. */
FLATTEN_NOSE: 1 << 3,
/** Enables the model's expression flag to use expressions beyond 32. */
NEW_EXPRESSIONS: 1 << 4,
/**
* This flag only generates new textures when initializing a CharModel
* but does not initialize shapes.
* **Note:** This means you cannot use DrawOpa/Xlu when this is set.
*/
NEW_MASK_ONLY: 1 << 5
};
// The enums below are only for FFLiGetRandomCharInfo.
// Hence, why each one has a value called ALL.
/** @enum {number} */
const FFLGender = {
MALE: 0,
FEMALE: 1,
ALL: 2
};
/** @enum {number} */
const FFLAge = {
CHILD: 0,
ADULT: 1,
ELDER: 2,
ALL: 3
};
/** @enum {number} */
const FFLRace = {
BLACK: 0,
WHITE: 1,
ASIAN: 2,
ALL: 3
};
// // ---------------------------------------------------------------------
// // CharInfo Unpacking, Verification, Random
// // ---------------------------------------------------------------------
// TODO PATH: src/CharInfo.js
const FFLiCharInfo_size = 288;
/* eslint-disable jsdoc/require-returns-type -- Allow TS to predict return type. */
/**
* @param {Uint8Array} u8 - module.HEAPU8
* @param {number} ptr - Pointer to the type.
* @returns Object form of FFLiCharInfo.
* @package
*/
function _unpackFFLiCharInfo(u8, ptr) {
/* eslint-enable jsdoc/require-returns-type -- defined above */
const view = new DataView(u8.buffer, ptr);
const name = new TextDecoder('utf-16le').decode(new Uint16Array(u8.buffer, ptr + 180, 11));
const creator = new TextDecoder('utf-16le').decode(new Uint16Array(u8.buffer, ptr + 202, 11));
const createID = new Uint8Array(u8.buffer, 264, 10);
const authorID = new Uint8Array(u8.buffer, 280, 8);
return {
miiVersion: view.getInt32(0, true),
faceType: view.getInt32(4, true),
faceColor: view.getInt32(8, true),
faceTex: view.getInt32(12, true),
faceMake: view.getInt32(16, true),
hairType: view.getInt32(20, true),
hairColor: view.getInt32(24, true),
hairFlip: view.getInt32(28, true),
eyeType: view.getInt32(32, true),
eyeColor: view.getInt32(36, true),
eyeScale: view.getInt32(40, true),
eyeAspect: view.getInt32(44, true),
eyeRotate: view.getInt32(48, true),
eyeX: view.getInt32(52, true),
eyeY: view.getInt32(56, true),
eyebrowType: view.getInt32(60, true),
eyebrowColor: view.getInt32(64, true),
eyebrowScale: view.getInt32(68, true),
eyebrowAspect: view.getInt32(72, true),
eyebrowRotate: view.getInt32(76, true),
eyebrowX: view.getInt32(80, true),
eyebrowY: view.getInt32(84, true),
noseType: view.getInt32(88, true),
noseScale: view.getInt32(92, true),
noseY: view.getInt32(96, true),
mouthType: view.getInt32(100, true),
mouthColor: view.getInt32(104, true),
mouthScale: view.getInt32(108, true),
mouthAspect: view.getInt32(112, true),
mouthY: view.getInt32(116, true),
beardMustache: view.getInt32(120, true),
beardType: view.getInt32(124, true),
beardColor: view.getInt32(128, true),
beardScale: view.getInt32(132, true),
beardY: view.getInt32(136, true),
glassType: view.getInt32(140, true),
glassColor: view.getInt32(144, true),
glassScale: view.getInt32(148, true),
glassY: view.getInt32(152, true),
moleType: view.getInt32(156, true),
moleScale: view.getInt32(160, true),
moleX: view.getInt32(164, true),
moleY: view.getInt32(168, true),
height: view.getInt32(172, true),
build: view.getInt32(176, true),
name,
creator,
gender: view.getInt32(224, true),
birthMonth: view.getInt32(228, true),
birthDay: view.getInt32(232, true),
favoriteColor: view.getInt32(236, true),
favorite: view.getUint8(240),
copyable: view.getUint8(241),
ngWord: view.getUint8(242),
localonly: view.getUint8(243),
regionMove: view.getInt32(244, true),
fontRegion: view.getInt32(248, true),
roomIndex: view.getInt32(252, true),
positionInRoom: view.getInt32(256, true),
birthPlatform: view.getInt32(260, true),
createID,
padding_0: view.getUint16(274, true),
authorType: view.getInt32(276, true),
authorID
};
}
/** @typedef {ReturnType<_unpackFFLiCharInfo>} FFLiCharInfo */
/**
* Size of FFLStoreData, the 3DS/Wii U Mii data format. (Not included)
* @public
*/
/** sizeof(FFLStoreData) */
const FFLStoreData_size = 96;
/**
* Validates the input CharInfo by calling FFLiVerifyCharInfoWithReason.
* @param {Uint8Array|number} data - FFLiCharInfo structure as bytes or pointer.
* @param {FFL} ffl - FFL module/resource state.
* @param {boolean} verifyName - Whether the name and creator name should be verified.
* @returns {void} Returns nothing if verification passes.
* @throws {FFLiVerifyReasonException} Throws if the result is not 0 (FFLI_VERIFY_REASON_OK).
* @public
*/
function verifyCharInfo(data, ffl, verifyName = false) {
const mod = ffl.module;
// Resolve charInfoPtr as pointer to CharInfo.
let charInfoPtr = 0;
let charInfoAllocated = false;
// Assume that number means pointer.
if (typeof data === 'number') {
charInfoPtr = data;
charInfoAllocated = false;
} else {
// Assume everything else means Uint8Array. TODO: untested
charInfoAllocated = true;
// Allocate and copy CharInfo.
charInfoPtr = mod._malloc(FFLiCharInfo_size);
mod.HEAPU8.set(data, charInfoPtr);
}
const result = mod._FFLiVerifyCharInfoWithReason(charInfoPtr, verifyName);
// Free CharInfo as soon as the function returns.
if (charInfoAllocated) {
mod._free(charInfoPtr);
}
if (result !== 0) {
// Reference: https://github.com/aboood40091/ffl/blob/master/include/nn/ffl/detail/FFLiCharInfo.h#L90
throw new FFLiVerifyReasonException(result);
}
}
/**
* Generates a random FFLiCharInfo instance calling FFLiGetRandomCharInfo.
* @param {FFL} ffl - FFL module/resource state.
* @param {FFLGender} gender - Gender of the character.
* @param {FFLAge} age - Age of the character.
* @param {FFLRace} race - Race of the character.
* @returns {Uint8Array} The random FFLiCharInfo.
*/
function getRandomCharInfo(ffl, gender = FFLGender.ALL, age = FFLAge.ALL, race = FFLRace.ALL) {
const mod = ffl.module;
const ptr = mod._malloc(FFLiCharInfo_size);
mod._FFLiGetRandomCharInfo(ptr, gender, age, race);
const result = mod.HEAPU8.slice(ptr, ptr + FFLiCharInfo_size);
mod._free(ptr);
return result;
}
// ---------------------- Common Color Mask Definitions ----------------------
/** @package */
const commonColorEnableMask = (1 << 31);
/**
* Applies (unofficial) mask: FFLI_NN_MII_COMMON_COLOR_ENABLE_MASK
* to a common color index to indicate to FFL which color table it should use.
* @param {number} color - The color index to flag.
* @returns {number} The flagged color index to use in FFLiCharinfo.
*/
const commonColorMask = color => color | commonColorEnableMask;
/**
* Removes (unofficial) mask: FFLI_NN_MII_COMMON_COLOR_ENABLE_MASK
* to a common color index to reveal the original common color index.
* @param {number} color - The flagged color index.
* @returns {number} The original color index before flagging.
*/
// const commonColorUnmask = color => (color & ~commonColorEnableMask) === 0
// Only unmask color if the mask is enabled.
// ? color
// : color & ~commonColorEnableMask;
// EXPORTS: _unpackFFLiCharInfo, verifyCharInfo, getRandomCharInfo, commonColorMask
// // ---------------------------------------------------------------------
// // Texture Management
// // ---------------------------------------------------------------------
// TODO PATH: src/TextureManager.js
/**
* Manages THREE.Texture objects created via FFL.
* Must be instantiated after FFL is fully initialized.
* @package
*/
class TextureManager {
/**
* Global that controls if texture creation should be changed
* to account for WebGL 1.0. (Shapes should be fine)
* @public
*/
static isWebGL1 = false;
/**
* Constructs the TextureManager. This MUST be created after initializing FFL.
* @param {Module} module - The Emscripten module.
* @param {boolean} [setToFFLGlobal] - Whether or not to call FFLSetTextureCallback on the constructed callback.
*/
constructor(module, setToFFLGlobal = false) {
/**
* @type {Module}
* @private
*/
this._module = module;
/**
* Internal map of texture ID to THREE.Texture.
* @type {Map<number, THREE.Texture>}
* @private
*/
this._textures = new Map();
/** @public */
this.callbackPtr = 0;
// Create and set texture callback instance.
this._setTextureCallback();
if (setToFFLGlobal) {
// Set texture callback globally within FFL if chosen.
module._FFLSetTextureCallback(this.callbackPtr);
}
}
/** @typedef {ReturnType<TextureManager._unpackFFLTextureInfo>} FFLTextureInfo */
/* eslint-disable jsdoc/require-returns-type -- Allow TS to predict return type. */
/**
* @param {Uint8Array} u8 - module.HEAPU8
* @param {number} ptr - Pointer to the type.
* @returns Object form of FFLTextureInfo.
* @private
*/
static _unpackFFLTextureInfo(u8, ptr) {
/* eslint-enable jsdoc/require-returns-type -- defined above */
const view = new DataView(u8.buffer, ptr);
return {
width: view.getUint16(0, true),
height: view.getUint16(2, true),
mipCount: view.getUint8(4),
format: view.getUint8(5),
// isGX2Tiled, _padding
imageSize: view.getUint32(8, true),
imagePtr: view.getUint32(12, true),
mipSize: view.getUint32(16, true),
mipPtr: view.getUint32(20, true),
mipLevelOffset: new Uint32Array(u8.buffer, ptr + 24, 13)
};
}
/**
* Allocates and packs an FFLTextureCallback instance from callback function pointers.
* @param {Module} module - The Emscripten module.
* @param {number} createCallback - Function pointer for the create callback.
* @param {number} deleteCallback - Function pointer for the delete callback.
* @returns {number} Pointer to the FFLTextureCallback.
* Note that you MUST free this after using it (done in {@link TextureManager.disposeCallback}).
* @private
*/
static _allocateTextureCallback(module, createCallback, deleteCallback) {
// this would usually be in a func called something like _packFFLTextureCallback
const FFLTextureCallback_size = 16;
const u8 = new Uint8Array(FFLTextureCallback_size);
const view = new DataView(u8.buffer);
view.setUint32(8, createCallback, true); // pCreateFunc
view.setUint32(12, deleteCallback, true); // pDeleteFunc
const ptr = module._malloc(FFLTextureCallback_size);
module.HEAPU8.set(u8, ptr);
return ptr;
}
/**
* Creates the create/delete functions in Emscripten and allocates and sets
* the FFLTextureCallback object as {@link TextureManager.callbackPtr}.
*/
_setTextureCallback() {
const mod = this._module;
// Bind the callbacks to this instance.
/** @private */
this._createCallback = mod.addFunction(this._textureCreateFunc.bind(this), 'vppp');
this.callbackPtr = TextureManager._allocateTextureCallback(mod,
this._createCallback, this._deleteCallback || 0);
}
/**
* @param {number} format - Enum value for FFLTextureFormat.
* @returns {THREE.PixelFormat} Three.js texture format constant.
* Note that this function won't work on WebGL1Renderer in Three.js r137-r162
* since R and RG textures need to use Luminance(Alpha)Format
* (you'd somehow need to detect which renderer is used)
* @private
*/
static _getTextureFormat(format) {
// Map FFLTextureFormat to Three.js texture formats.
// THREE.RGFormat did not work for me on Three.js r136/older.
const useOldFormats = Number(THREE.REVISION) <= 136 || TextureManager.isWebGL1;
const r8 = useOldFormats
// eslint-disable-next-line import-x/namespace -- deprecated, maybe deleted
? THREE.LuminanceFormat
: THREE.RedFormat;
const r8g8 = useOldFormats
// NOTE: Using THREE.LuminanceAlphaFormat before it
// was removed on WebGL 1.0/2.0 causes the texture
// to be converted to RGBA resulting in two issues.
// - There is a black outline around glasses
// - For glasses that have an inner color, the color is wrongly applied to the frames as well.
// eslint-disable-next-line import-x/namespace -- deprecated, maybe deleted
? THREE.LuminanceAlphaFormat
: THREE.RGFormat;
const textureFormatToThreeFormat = [
r8, // R8_UNORM = 0
r8g8, // R8_G8_UNORM = 1
THREE.RGBAFormat // R8_G8_B8_A8_UNORM = 2
];
// Determine the data format from the table.
const dataFormat = textureFormatToThreeFormat[format];
console.assert(dataFormat !== undefined, `_textureCreateFunc: Unexpected FFLTextureFormat value: ${format}`);
return dataFormat;
}
/**
* @param {number} _ - Originally pObj, unused here.
* @param {number} textureInfoPtr - Pointer to {@link FFLTextureInfo}.
* @param {number} texturePtrPtr - Pointer to the texture handle (pTexture2D).
* @private
*/
_textureCreateFunc(_, textureInfoPtr, texturePtrPtr) {
const textureInfo = TextureManager._unpackFFLTextureInfo(
this._module.HEAPU8, textureInfoPtr);
// console.debug(`_textureCreateFunc: width=${textureInfo.width}, ` +
// `height=${textureInfo.height}, format=${textureInfo.format}, ` +
// `imageSize=${textureInfo.imageSize}, mipCount=${textureInfo.mipCount}`);
/** Resolve THREE.PixelFormat. */
const format = TextureManager._getTextureFormat(textureInfo.format);
// Copy image data from HEAPU8 via slice. This is base level/mip level 0.
const imageData = this._module.HEAPU8.slice(textureInfo.imagePtr,
textureInfo.imagePtr + textureInfo.imageSize);
/**
* Determine whether mipmaps can be used at all.
* Implemented in Three.js r137 and only works properly on r138.
*
* This is also disabled for WebGL 1.0, since there are some NPOT textures.
* Those aren't supposed to have mipmaps e.g., glass, but I found that
* while in OpenGL ES 2, some textures that didn't wrap could have mips with
* NPOT, this didn't work in WebGL 1.0.
*/
const canUseMipmaps = Number(THREE.REVISION) >= 138 && !TextureManager.isWebGL1;
// Actually use mipmaps if the mip count is over 1.
const useMipmaps = textureInfo.mipCount > 1 && canUseMipmaps;
// Create new THREE.Texture with the specified format.
const texture = new THREE.DataTexture(useMipmaps ? null : imageData,
textureInfo.width, textureInfo.height, format, THREE.UnsignedByteType);
texture.magFilter = THREE.LinearFilter;
// texture.generateMipmaps = true; // not necessary at higher resolutions
texture.minFilter = THREE.LinearFilter;
if (useMipmaps) {
// Add base texture.
texture.mipmaps = [{
data: imageData,
width: textureInfo.width,
height: textureInfo.height
}];
// Enable filtering option for mipmap and add levels.
texture.minFilter = THREE.LinearMipmapLinearFilter;
texture.generateMipmaps = false;
this._addMipmaps(texture, textureInfo);
}
texture.needsUpdate = true;
this.set(texture.id, texture);
this._module.HEAPU32[texturePtrPtr / 4] = texture.id;
}
/**
* @param {THREE.Texture} texture - Texture to upload mipmaps into.
* @param {FFLTextureInfo} textureInfo - FFLTextureInfo object representing this texture.
* @private
*/
_addMipmaps(texture, textureInfo) {
// Make sure mipPtr is not null.
console.assert(textureInfo.mipPtr, '_addMipmaps: mipPtr is null, so the caller incorrectly assumed this texture has mipmaps');
// Iterate through mip levels starting from 1 (base level is mip level 0).
for (let mipLevel = 1; mipLevel < textureInfo.mipCount; mipLevel++) {
// Calculate the offset for the current mip level.
const mipOffset = textureInfo.mipLevelOffset[mipLevel - 1];
// Calculate dimensions of the current mip level.
const mipWidth = Math.max(1, textureInfo.width >> mipLevel);
const mipHeight = Math.max(1, textureInfo.height >> mipLevel);
// Get the offset of the next mipmap and calculate end offset.
const nextMipOffset = textureInfo.mipLevelOffset[mipLevel] || textureInfo.mipSize;
const end = textureInfo.mipPtr + nextMipOffset;
// Copy the data from the heap.
const start = textureInfo.mipPtr + mipOffset;
const mipData = this._module.HEAPU8.slice(start, end);
// console.debug(` - Mip ${mipLevel}: ${mipWidth}x${mipHeight}, `
// + `offset=${mipOffset}, range=${start}-${end}`);
// console.debug(uint8ArrayToBase64(mipData)); // will leak the data
// Push this mip level data into the texture's mipmaps array.
// @ts-ignore - data = "CompressedTextureMipmap & CubeTexture & HTMLCanvasElement"
texture.mipmaps.push({
data: mipData, // Should still accept Uint8Array.
width: mipWidth,
height: mipHeight
});
}
}
/**
* @param {number} id - ID assigned to the texture.
* @returns {THREE.Texture|null|undefined} Returns the texture if it is found.
* @public
*/
get(id) {
return this._textures.get(id);
}
/**
* @param {number} id - ID assigned to the texture.
* @param {THREE.Texture} texture - Texture to add.
* @public
*/
set(id, texture) {
// Set texture with an override for dispose.
const disposeReal = texture.dispose.bind(texture);
texture.dispose = () => {
// Remove this texture from the map after disposing.
disposeReal();
this.delete(id); // this = TextureManager
};
this._textures.set(id, texture);
}
/**
* @param {number} id - ID assigned to the texture.
* @public
*/
delete(id) {
// Get texture from array instead of with get()
// because it's okay if it was already deleted.
const texture = this._textures.get(id);
if (texture) {
// This is assuming the texture has already been disposed.
/** @type {Object<string, *>} */ (texture).source = null;
/** @type {Object<string, *>} */ (texture).mipmaps = null;
this._textures.delete(id);
}
}
/**
* Disposes/frees the FFLTextureCallback along with
* removing the created Emscripten functions.
* @public
*/
disposeCallback() {
// if (!this._module) {
// return;
// }
if (this.callbackPtr) {
this._module._free(this.callbackPtr);
this.callbackPtr = 0;
}
if (this._deleteCallback) {
this._module.removeFunction(this._deleteCallback);
this._deleteCallback = 0;
}
// should always exist?:
if (this._createCallback) {
this._module.removeFunction(this._createCallback);
this._createCallback = 0;
}
// this._module = null;
}
/**
* Disposes of all textures and frees the FFLTextureCallback.
* @public
*/
dispose() {
// Dispose of all stored textures.
for (const tex of this._textures) {
tex[1].dispose();
}
// Clear texture map.
this._textures.clear();
// Free texture callback.
this.disposeCallback();
}
}
// // ---------------------------------------------------------------------
// // Classes for FFL Exceptions
// // ---------------------------------------------------------------------
// TODO PATH: src/Exceptions.js
/**
* Base exception type for all exceptions based on FFLResult.
* https://github.com/ariankordi/FFLSharp/blob/master/FFLSharp.FFLManager/FFLExceptions.cs
* https://github.com/aboood40091/ffl/blob/master/include/nn/ffl/FFLResult.h
*/
class FFLResultException extends Error {
/**
* @param {number|FFLResult} result - The returned {@link FFLResult}.
* @param {string} [funcName] - The name of the function that was called.
* @param {string} [message] - An optional message for the exception.
*/
constructor(result, funcName, message) {
if (!message) {
message = funcName
? `${funcName} failed with FFLResult: ${result}`
: `From FFLResult: ${result}`;
}
super(message);
/** The stored {@link FFLResult} code. */
this.result = result;
}
/**
* Throws an exception if the {@link FFLResult} is not OK.
* @param {number} result - The {@link FFLResult} from an FFL function.
* @param {string} [funcName] - The name of the function that was called.
* @throws {FFLResultException|FFLResultWrongParam|FFLResultBroken|FFLResultNotAvailable|FFLResultFatal}
*/
static handleResult(result, funcName) {
switch (result) {
case FFLResult.ERROR: // FFL_RESULT_WRONG_PARAM
throw new FFLResultWrongParam(funcName);
case FFLResult.FILE_INVALID: // FFL_RESULT_BROKEN
throw new FFLResultBroken(funcName);
case FFLResult.MANAGER_NOT_CONSTRUCT: // FFL_RESULT_NOT_AVAILABLE
throw new FFLResultNotAvailable(funcName);
case FFLResult.FILE_LOAD_ERROR: // FFL_RESULT_FATAL
throw new FFLResultFatal(funcName);
case FFLResult.OK: // FFL_RESULT_OK
return; // All is OK.
default:
throw new FFLResultException(result, funcName);
}
}
}
/**
* Exception reflecting FFL_RESULT_WRONG_PARAM / FFL_RESULT_ERROR.
* This is the most common error thrown in FFL. It usually
* means that input parameters are invalid.
* So many cases this is thrown: parts index is out of bounds,
* CharModelCreateParam is malformed, FFLDataSource is invalid, FFLInitResEx
* parameters are null or invalid... Many different causes, very much an annoying error.
*/
class FFLResultWrongParam extends FFLResultException {
/** @param {string} [funcName] - Name of the function where the result originated. */
constructor(funcName) {
super(FFLResult.ERROR, funcName, `${funcName} returned FFL_RESULT_WRONG_PARAM. This usually means parameters going into that function were invalid.`);
}
}
/** Exception reflecting FFL_RESULT_BROKEN / FFL_RESULT_FILE_INVALID. */
class FFLResultBroken extends FFLResultException {
/**
* @param {string} [funcName] - Name of the function where the result originated.
* @param {string} [message] - An optional message for the exception.
*/
constructor(funcName, message) {
super(FFLResult.FILE_INVALID, funcName, message || `${funcName} returned FFL_RESULT_BROKEN. This usually indicates invalid underlying data.`);
}
}
/** Exception when resource header verification fails. */
class BrokenInitRes extends FFLResultBroken {
constructor() {
super('FFLInitRes', 'The header for the FFL resource is probably invalid. Check the version and magic, should be "FFRA" or "ARFF".');
}
}
/**
* Exception reflecting FFL_RESULT_NOT_AVAILABLE / FFL_RESULT_MANAGER_NOT_CONSTRUCT.
* This is seen when FFLiManager is not constructed, which it is not when FFLInitResEx fails
* or was never called to begin with.
*/
class FFLResultNotAvailable extends FFLResultException {
/** @param {string} [funcName] - Name of the function where the result originated. */
constructor(funcName) {
super(FFLResult.MANAGER_NOT_CONSTRUCT, funcName, `Tried to call FFL function ${funcName} when FFLManager is not constructed (FFL is not initialized properly).`);
}
}
/**
* Exception reflecting FFL_RESULT_FATAL / FFL_RESULT_FILE_LOAD_ERROR.
* This error indicates database file load errors or failures from FFLiResourceLoader (decompression? misalignment?)
*/
class FFLResultFatal extends FFLResultException {
/** @param {string} [funcName] - Name of the function where the result originated. */
constructor(funcName) {
super(FFLResult.FILE_LOAD_ERROR, funcName, `Failed to uncompress or load a specific asset from the FFL resource file during call to ${funcName}`);
}
}
/**
* Exception thrown by the result of FFLiVerifyCharInfoWithReason.
* Reference: https://github.com/aboood40091/ffl/blob/master/include/nn/ffl/detail/FFLiCharInfo.h#L90
*/
class FFLiVerifyReasonException extends Error {
/** @param {number} result - The FFLiVerifyReason code from FFLiVerifyCharInfoWithReason. */
constructor(result) {
super(`FFLiVerifyCharInfoWithReason (CharInfo verification) failed with result: ${result}`);
/** The stored FFLiVerifyReason code. */
this.result = result;
}
}
/**
* Exception thrown when the mask is set to an expression that
* the {@link CharModel} was never initialized to, which can't happen
* because that mask texture does not exist on the {@link CharModel}.
* @augments {Error}
*/
class ExpressionNotSet extends Error {
/** @param {FFLExpression} expression - The attempted expression. */
constructor(expression) {
super(`Attempted to set expression ${expression}, but the mask for that expression does not exist. You must reinitialize the CharModel with this expression in the expression flags before using it.`);
this.expression = expression;
}
}
// // ---------------------------------------------------------------------
// // FFL Initialization
// // ---------------------------------------------------------------------
// TODO PATH: src/Initialization.js
/**
* Class for initializing FFL.js.
* The instance of this class is meant to be passed when creating
* CharModels or to functions that need the {@link Module}.
*/
class FFL {
/**
* Resource type to load single resource into = FFL_RESOURCE_TYPE_HIGH
* @package
*/
static singleResourceType = 1;
/**
* Initializes FFL by copying the resource into heap and calling FFLInitRes.
* It will first wait for the Emscripten module to be ready.
* @param {Uint8Array|Response} resource - The FFL resource data. Use a Uint8Array
* if you have the raw bytes, or a fetch response containing the FFL resource file.
* @param {Module|Promise<Module>|function(): Promise<Module>} moduleOrPromise - The Emscripten module
* by itself (window.Module when MODULARIZE=0), as a promise (window.Module() when MODULARIZE=1),
* or as a function returning a promise (window.Module when MODULARIZE=1).
* @returns {Promise<FFL>} Resolves when FFL is fully initialized.
* returning the final Emscripten {@link Module} instance and the FFLResourceDesc buffer
* that can later be passed into `FFL.dispose()`.
* @public
*/
static async initWithResource(resource, moduleOrPromise) {
// console.debug('FFL.initWithResource: Entrypoint, waiting for module to be ready.');
/**
* Pointer to the FFLResourceDesc structure to free when FFLInitRes call is done.
* @type {number}
*/
let resourceDescPtr = 0;
/**
* The Emscripten Module instance to set and return at the end.
* @type {Module}
*/
let module;
// Resolve moduleOrPromise to the Module instance.
if (typeof moduleOrPromise === 'function') {
// Assume this function gets the promise of the module.
moduleOrPromise = moduleOrPromise();
}
module = (moduleOrPromise instanceof Promise)
// Await if this is now a promise.
? module = await moduleOrPromise
// Otherwise, assume it is already the module.
: module = moduleOrPromise;
// Wait for the Emscripten runtime to be ready if it isn't already.
if (!module.calledRun && !module.onRuntimeInitialized) {
// calledRun is not defined. Set onRuntimeInitialized and wait for it in a new promise.
await new Promise((resolve) => {
/** If onRuntimeInitialized is not defined on module, add it. */