@combeenation/3d-viewer 14.0.0 → 14.0.1-rc1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +9 -9
  2. package/dist/lib-cjs/buildinfo.json +3 -3
  3. package/dist/lib-cjs/commonjs.tsconfig.tsbuildinfo +1 -1
  4. package/dist/lib-cjs/index.d.ts +62 -62
  5. package/dist/lib-cjs/index.js +94 -94
  6. package/dist/lib-cjs/internal/cbn-custom-babylon-loader-plugin.d.ts +10 -10
  7. package/dist/lib-cjs/internal/cbn-custom-babylon-loader-plugin.js +131 -131
  8. package/dist/lib-cjs/internal/cloning-helper.d.ts +19 -19
  9. package/dist/lib-cjs/internal/cloning-helper.js +163 -163
  10. package/dist/lib-cjs/internal/device-helper.d.ts +9 -9
  11. package/dist/lib-cjs/internal/device-helper.js +24 -24
  12. package/dist/lib-cjs/internal/geometry-helper.d.ts +21 -21
  13. package/dist/lib-cjs/internal/geometry-helper.js +145 -145
  14. package/dist/lib-cjs/internal/metadata-helper.d.ts +26 -26
  15. package/dist/lib-cjs/internal/metadata-helper.js +50 -50
  16. package/dist/lib-cjs/internal/paintable-helper.d.ts +40 -40
  17. package/dist/lib-cjs/internal/paintable-helper.js +286 -286
  18. package/dist/lib-cjs/internal/tags-helper.d.ts +12 -12
  19. package/dist/lib-cjs/internal/tags-helper.js +37 -37
  20. package/dist/lib-cjs/manager/camera-manager.d.ts +110 -110
  21. package/dist/lib-cjs/manager/camera-manager.js +206 -206
  22. package/dist/lib-cjs/manager/debug-manager.d.ts +60 -60
  23. package/dist/lib-cjs/manager/debug-manager.js +217 -217
  24. package/dist/lib-cjs/manager/event-manager.d.ts +52 -52
  25. package/dist/lib-cjs/manager/event-manager.js +71 -71
  26. package/dist/lib-cjs/manager/gltf-export-manager.d.ts +84 -75
  27. package/dist/lib-cjs/manager/gltf-export-manager.js +290 -278
  28. package/dist/lib-cjs/manager/gltf-export-manager.js.map +1 -1
  29. package/dist/lib-cjs/manager/material-manager.d.ts +35 -35
  30. package/dist/lib-cjs/manager/material-manager.js +125 -125
  31. package/dist/lib-cjs/manager/model-manager.d.ts +145 -145
  32. package/dist/lib-cjs/manager/model-manager.js +382 -382
  33. package/dist/lib-cjs/manager/parameter-manager.d.ts +210 -210
  34. package/dist/lib-cjs/manager/parameter-manager.js +514 -514
  35. package/dist/lib-cjs/manager/scene-manager.d.ts +45 -45
  36. package/dist/lib-cjs/manager/scene-manager.js +64 -64
  37. package/dist/lib-cjs/manager/texture-manager.d.ts +12 -12
  38. package/dist/lib-cjs/manager/texture-manager.js +43 -43
  39. package/dist/lib-cjs/viewer-error.d.ts +48 -48
  40. package/dist/lib-cjs/viewer-error.js +60 -60
  41. package/dist/lib-cjs/viewer.d.ts +115 -115
  42. package/dist/lib-cjs/viewer.js +217 -217
  43. package/package.json +91 -91
  44. package/src/buildinfo.json +3 -3
  45. package/src/dev.ts +47 -47
  46. package/src/global-types.d.ts +39 -39
  47. package/src/index.ts +81 -81
  48. package/src/internal/cbn-custom-babylon-loader-plugin.ts +159 -159
  49. package/src/internal/cloning-helper.ts +225 -225
  50. package/src/internal/device-helper.ts +25 -25
  51. package/src/internal/geometry-helper.ts +181 -181
  52. package/src/internal/metadata-helper.ts +63 -63
  53. package/src/internal/paintable-helper.ts +310 -310
  54. package/src/internal/tags-helper.ts +41 -41
  55. package/src/manager/camera-manager.ts +365 -365
  56. package/src/manager/debug-manager.ts +245 -245
  57. package/src/manager/event-manager.ts +72 -72
  58. package/src/manager/gltf-export-manager.ts +357 -341
  59. package/src/manager/material-manager.ts +135 -135
  60. package/src/manager/model-manager.ts +458 -458
  61. package/src/manager/parameter-manager.ts +652 -652
  62. package/src/manager/scene-manager.ts +101 -101
  63. package/src/manager/texture-manager.ts +32 -32
  64. package/src/viewer-error.ts +68 -68
  65. package/src/viewer.ts +290 -290
@@ -1,287 +1,287 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __rest = (this && this.__rest) || function (s, e) {
12
- var t = {};
13
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
- t[p] = s[p];
15
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
- t[p[i]] = s[p[i]];
19
- }
20
- return t;
21
- };
22
- var __importDefault = (this && this.__importDefault) || function (mod) {
23
- return (mod && mod.__esModule) ? mod : { "default": mod };
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.parsePaintable = exports.paintableParameterObserver = void 0;
27
- const index_1 = require("../index");
28
- const is_svg_1 = __importDefault(require("is-svg"));
29
- const lodash_es_1 = require("lodash-es");
30
- /**
31
- * Observer implementation for "paintable" parameter.
32
- * Basically creates a dynamic texture from the source image and assigns it as albedo (or diffuse) texture.
33
- */
34
- function paintableParameterObserver(newValue, materials, scene) {
35
- return __awaiter(this, void 0, void 0, function* () {
36
- const paintable = parsePaintable(newValue);
37
- // check if value is svg or image source, do the conversion accordingly
38
- const srcIsSvg = (0, is_svg_1.default)(paintable.src);
39
- if (!srcIsSvg && paintable.src.includes('<svg') && paintable.src.includes('</svg>')) {
40
- // seems like the user tried to use a SVG string, as <svg> tags are used
41
- // inform the user that this is not a valid SVG string
42
- throw new index_1.ViewerError({
43
- id: index_1.ViewerErrorIds.InvalidParameterValue,
44
- message: `Invalid value for parameter "paintable" given:\nsource string is no valid SVG string\nGiven value: ${paintable.src}`,
45
- });
46
- }
47
- let imageSource;
48
- try {
49
- imageSource = srcIsSvg ? yield _createImageFromSvg(paintable.src) : yield _createImageFromImgSrc(paintable.src);
50
- }
51
- catch (_a) {
52
- // SVG might be invalid, even if it passes `isSvg` check
53
- // in this case the image can't be created and will throw an error, which should be handled by the viewer and
54
- // Combeenation viewer control
55
- throw new index_1.ViewerError({
56
- id: index_1.ViewerErrorIds.InvalidParameterValue,
57
- message: `Invalid value for parameter "paintable" given:\nimage can't be created from source string\nGiven value: ${paintable.src}`,
58
- });
59
- }
60
- // apply image source on desired material(s)
61
- for (const material of materials) {
62
- _drawPaintableOnMaterial(material, imageSource, scene, paintable.options);
63
- }
64
- });
65
- }
66
- exports.paintableParameterObserver = paintableParameterObserver;
67
- /**
68
- * Parser for paintable value.
69
- * ATM this is only used internally, but it could theoretically be used to create ones own paintable implementation.
70
- *
71
- * @param value The value to parse. Examples:
72
- * ```ts
73
- * // Default definition as JSON object:
74
- * '{ "src": "https://path.to/image.jpg", "uScale": 0.5 }'
75
- *
76
- * // Short hand definition, only contains source string:
77
- * 'https://path.to/image.jpg'
78
- *
79
- * // Full content, paintable texture is flipped in both directions
80
- * '{ "src": "https://path.to/image.jpg", "uScale": -1, "vScale": -1, "uOffset": 0, "vOffset": 0 }'
81
- *
82
- * // SVG content can be used directly:
83
- * '<svg>...</svg>'
84
- *
85
- * // SVG in src property works as well:
86
- * '{ "src": "<svg>...</svg>", "uScale": 0.5 }'
87
- * ```
88
- */
89
- function parsePaintable(value) {
90
- if (!(0, lodash_es_1.isString)(value)) {
91
- throw new index_1.ViewerError({
92
- id: index_1.ViewerErrorIds.InvalidParameterValue,
93
- message: `Unable to parse paintable value: not a string\nGiven value: ${value}`,
94
- });
95
- }
96
- const paintableValue = { src: '' };
97
- let valObj = null;
98
- try {
99
- valObj = JSON.parse(value);
100
- }
101
- catch (_a) {
102
- // use string directly
103
- paintableValue.src = value;
104
- if (value.startsWith('{')) {
105
- // seems like the user tried to use a JSON string, as the input starts with {
106
- throw new index_1.ViewerError({
107
- id: index_1.ViewerErrorIds.InvalidParameterValue,
108
- message: `Unable to parse paintable value: not a valid JSON string\nGiven value: ${value}`,
109
- });
110
- }
111
- }
112
- if (valObj) {
113
- // input string is JSON, src attribute is required
114
- if (!valObj.src) {
115
- throw new index_1.ViewerError({
116
- id: index_1.ViewerErrorIds.InvalidParameterValue,
117
- message: `Unable to parse paintable value: property "src" is missing\nGiven value: ${value}`,
118
- });
119
- }
120
- if (!(0, lodash_es_1.isString)(valObj.src)) {
121
- throw new index_1.ViewerError({
122
- id: index_1.ViewerErrorIds.InvalidParameterValue,
123
- message: `Unable to parse paintable value: property "src" is not a string\nGiven value: ${value}`,
124
- });
125
- }
126
- // split src and options
127
- const { src } = valObj, options = __rest(valObj, ["src"]);
128
- paintableValue.src = src;
129
- // only forward valid paintable options
130
- const validOptionKeys = ['uScale', 'vScale', 'uOffset', 'vOffset'];
131
- const { validOptions, invalidKeys } = Object.entries(options).reduce((accRes, [curKey, curValue]) => {
132
- const isValidKey = validOptionKeys.includes(curKey);
133
- if (isValidKey) {
134
- accRes.validOptions[curKey] = curValue;
135
- }
136
- else {
137
- accRes.invalidKeys.push(curKey);
138
- }
139
- return accRes;
140
- }, { validOptions: {}, invalidKeys: [] });
141
- if (invalidKeys.length) {
142
- console.warn('Invalid paintable options provided: ' + invalidKeys.toString());
143
- }
144
- paintableValue.options = validOptions;
145
- }
146
- return paintableValue;
147
- }
148
- exports.parsePaintable = parsePaintable;
149
- function _drawPaintableOnMaterial(material, imageSource, scene, options) {
150
- var _a, _b, _c, _d;
151
- // always take width and height from image source, scaling is done with uvScale properties
152
- const widthAndHeight = {
153
- width: imageSource.width,
154
- height: imageSource.height,
155
- };
156
- const texture = new index_1.DynamicTexture(`${material.id}.paintable_texture`, widthAndHeight, scene);
157
- // draw image on texture
158
- const ctx = texture.getContext();
159
- ctx.drawImage(imageSource, 0, 0);
160
- texture.update();
161
- // apply settings from paintable options to tweak position and scaling of image on the texture
162
- texture.uScale = (_a = options === null || options === void 0 ? void 0 : options.uScale) !== null && _a !== void 0 ? _a : texture.uScale;
163
- texture.vScale = (_b = options === null || options === void 0 ? void 0 : options.vScale) !== null && _b !== void 0 ? _b : texture.vScale;
164
- texture.uOffset = (_c = options === null || options === void 0 ? void 0 : options.uOffset) !== null && _c !== void 0 ? _c : texture.uOffset;
165
- texture.vOffset = (_d = options === null || options === void 0 ? void 0 : options.vOffset) !== null && _d !== void 0 ? _d : texture.vOffset;
166
- // wrap mode is preferred, as it will always show the texture, no matter which position offset is currently chosen
167
- // clamp mode requires more knowledge (and patience) when adjusting the uv scale and offset values
168
- texture.wrapU = index_1.Texture.WRAP_ADDRESSMODE;
169
- texture.wrapV = index_1.Texture.WRAP_ADDRESSMODE;
170
- // apply the paintable texture on the dedicated material type
171
- const materialCls = material.getClassName();
172
- switch (materialCls) {
173
- case 'PBRMaterial':
174
- material.albedoTexture = texture;
175
- break;
176
- case 'StandardMaterial':
177
- material.diffuseTexture = texture;
178
- break;
179
- default:
180
- throw new Error(`Setting paintable texture for material of instance "${materialCls}" not implemented (yet)`);
181
- }
182
- }
183
- /**
184
- * Creates a HTML image element based on a SVG string, whereas all the embedded assets in the SVG (eg: fonts, images)
185
- * are already loaded and exchanged by their base64 representation.\
186
- * There the output image can exist as "standalone" image and may be used for example as a paintable.
187
- *
188
- * !!CAUTION!!: The used functions within this code section are very well evaluated since most alternatives
189
- * somehow don't work in Safari, as mentioned in the following BJS forum entries:
190
- * - https://forum.babylonjs.com/t/drawing-svg-content-text-into-dynamictexture-doesnt-work-in-safari-v15/25048
191
- * - https://forum.babylonjs.com/t/texture-createfrombase64string-doesnt-seem-to-work-for-ios-devices-initially/25502
192
- */
193
- function _createImageFromSvg(svgSrc) {
194
- return __awaiter(this, void 0, void 0, function* () {
195
- // replace assets with their base64 versions in svg source code
196
- const svgWithAssetsEmbedded = yield _embedAssets(svgSrc);
197
- // create data string which can be used as an image source
198
- const svgEncoded = 'data:image/svg+xml,' + encodeURIComponent(svgWithAssetsEmbedded);
199
- return _createImageFromImgSrc(svgEncoded);
200
- });
201
- }
202
- /**
203
- * Creates an HTML image element from a dedicated image source.\
204
- * Also waits until the image has loaded.
205
- *
206
- * !!CAUTION!!: The `setTimeout` after loading is finished is required due to a Safari bug:
207
- * - https://bugs.webkit.org/show_bug.cgi?id=39059
208
- * - https://bugs.webkit.org/show_bug.cgi?id=219770
209
- *
210
- * It's not 100% ensured that the timeout solves the issue in every case, but there is no other way unfortunately.\
211
- * => Keep an eye on it in future projects
212
- *
213
- * @param imgSrc Theoretically every source is valid which is also supported by
214
- * [HTMLImageElement.src](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/src).\
215
- * Known exceptions are SVGs with embedded assets that are provided as object URL. See comments in
216
- * {@link createImageFromSvg} for further details.
217
- */
218
- function _createImageFromImgSrc(imgSrc) {
219
- return __awaiter(this, void 0, void 0, function* () {
220
- const img = new Image();
221
- yield new Promise((resolve, reject) => {
222
- img.onload = () => {
223
- setTimeout(resolve, 0);
224
- };
225
- img.onerror = () => {
226
- reject();
227
- };
228
- img.crossOrigin = 'anonymous';
229
- img.src = imgSrc;
230
- });
231
- return img;
232
- });
233
- }
234
- /**
235
- * Replaces all supported image & font URLs in the given SVG with their base64 representation.
236
- */
237
- function _embedAssets(svgSrc) {
238
- return __awaiter(this, void 0, void 0, function* () {
239
- const _imageExtensions = ['png', 'gif', 'jpg', 'jpeg', 'svg', 'bmp'];
240
- const _fontExtensions = ['woff2', 'woff', 'ttf', 'otf'];
241
- const _assetExtensions = [..._imageExtensions, ..._fontExtensions];
242
- // Regex copied from https://stackoverflow.com/a/8943487/1273551, not "stress tested"...
243
- const urlRegex = /(\bhttps?:\/\/[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/gi;
244
- const allUrls = svgSrc.match(urlRegex);
245
- const assetUrls = allUrls.filter(url => {
246
- const indexParam = url.indexOf('?');
247
- // remove url parameter to recognize extension
248
- if (indexParam > -1) {
249
- url = url.substring(0, indexParam);
250
- }
251
- return _assetExtensions.some(extension => url.toLowerCase().endsWith(`.${extension}`));
252
- });
253
- const assetBase64Fetcher = assetUrls.map(_fetchBase64AssetUrl);
254
- const assetFetcherResults = yield Promise.all(assetBase64Fetcher);
255
- return assetFetcherResults.reduce((svgSrc, x) => svgSrc.replace(x.url, x.base64), svgSrc);
256
- });
257
- }
258
- /**
259
- * Fetch asset (image or font) and convert it to base64 string representation.
260
- */
261
- function _fetchBase64AssetUrl(assetUrl) {
262
- return __awaiter(this, void 0, void 0, function* () {
263
- // TODO WTT: Cache known base64 representation and only fetch/convert when not already known.
264
- // Usually the fetch shouldn't hit the network but the browser cache since the SVG was already drawn..
265
- const resp = yield fetch(assetUrl);
266
- const blob = yield resp.blob();
267
- return new Promise((resolve, reject) => {
268
- const reader = new FileReader();
269
- reader.onloadend = (event) => {
270
- const target = event.target;
271
- if (!target) {
272
- return reject(`Asset with URL "${assetUrl}" could not be loaded.`);
273
- }
274
- const result = target.result;
275
- if (!result) {
276
- return reject(`Asset with URL "${assetUrl}" returned an empty result.`);
277
- }
278
- resolve({
279
- url: assetUrl,
280
- base64: result.toString(),
281
- });
282
- };
283
- reader.readAsDataURL(blob);
284
- });
285
- });
286
- }
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __rest = (this && this.__rest) || function (s, e) {
12
+ var t = {};
13
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
+ t[p] = s[p];
15
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
+ t[p[i]] = s[p[i]];
19
+ }
20
+ return t;
21
+ };
22
+ var __importDefault = (this && this.__importDefault) || function (mod) {
23
+ return (mod && mod.__esModule) ? mod : { "default": mod };
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.parsePaintable = exports.paintableParameterObserver = void 0;
27
+ const index_1 = require("../index");
28
+ const is_svg_1 = __importDefault(require("is-svg"));
29
+ const lodash_es_1 = require("lodash-es");
30
+ /**
31
+ * Observer implementation for "paintable" parameter.
32
+ * Basically creates a dynamic texture from the source image and assigns it as albedo (or diffuse) texture.
33
+ */
34
+ function paintableParameterObserver(newValue, materials, scene) {
35
+ return __awaiter(this, void 0, void 0, function* () {
36
+ const paintable = parsePaintable(newValue);
37
+ // check if value is svg or image source, do the conversion accordingly
38
+ const srcIsSvg = (0, is_svg_1.default)(paintable.src);
39
+ if (!srcIsSvg && paintable.src.includes('<svg') && paintable.src.includes('</svg>')) {
40
+ // seems like the user tried to use a SVG string, as <svg> tags are used
41
+ // inform the user that this is not a valid SVG string
42
+ throw new index_1.ViewerError({
43
+ id: index_1.ViewerErrorIds.InvalidParameterValue,
44
+ message: `Invalid value for parameter "paintable" given:\nsource string is no valid SVG string\nGiven value: ${paintable.src}`,
45
+ });
46
+ }
47
+ let imageSource;
48
+ try {
49
+ imageSource = srcIsSvg ? yield _createImageFromSvg(paintable.src) : yield _createImageFromImgSrc(paintable.src);
50
+ }
51
+ catch (_a) {
52
+ // SVG might be invalid, even if it passes `isSvg` check
53
+ // in this case the image can't be created and will throw an error, which should be handled by the viewer and
54
+ // Combeenation viewer control
55
+ throw new index_1.ViewerError({
56
+ id: index_1.ViewerErrorIds.InvalidParameterValue,
57
+ message: `Invalid value for parameter "paintable" given:\nimage can't be created from source string\nGiven value: ${paintable.src}`,
58
+ });
59
+ }
60
+ // apply image source on desired material(s)
61
+ for (const material of materials) {
62
+ _drawPaintableOnMaterial(material, imageSource, scene, paintable.options);
63
+ }
64
+ });
65
+ }
66
+ exports.paintableParameterObserver = paintableParameterObserver;
67
+ /**
68
+ * Parser for paintable value.
69
+ * ATM this is only used internally, but it could theoretically be used to create ones own paintable implementation.
70
+ *
71
+ * @param value The value to parse. Examples:
72
+ * ```ts
73
+ * // Default definition as JSON object:
74
+ * '{ "src": "https://path.to/image.jpg", "uScale": 0.5 }'
75
+ *
76
+ * // Short hand definition, only contains source string:
77
+ * 'https://path.to/image.jpg'
78
+ *
79
+ * // Full content, paintable texture is flipped in both directions
80
+ * '{ "src": "https://path.to/image.jpg", "uScale": -1, "vScale": -1, "uOffset": 0, "vOffset": 0 }'
81
+ *
82
+ * // SVG content can be used directly:
83
+ * '<svg>...</svg>'
84
+ *
85
+ * // SVG in src property works as well:
86
+ * '{ "src": "<svg>...</svg>", "uScale": 0.5 }'
87
+ * ```
88
+ */
89
+ function parsePaintable(value) {
90
+ if (!(0, lodash_es_1.isString)(value)) {
91
+ throw new index_1.ViewerError({
92
+ id: index_1.ViewerErrorIds.InvalidParameterValue,
93
+ message: `Unable to parse paintable value: not a string\nGiven value: ${value}`,
94
+ });
95
+ }
96
+ const paintableValue = { src: '' };
97
+ let valObj = null;
98
+ try {
99
+ valObj = JSON.parse(value);
100
+ }
101
+ catch (_a) {
102
+ // use string directly
103
+ paintableValue.src = value;
104
+ if (value.startsWith('{')) {
105
+ // seems like the user tried to use a JSON string, as the input starts with {
106
+ throw new index_1.ViewerError({
107
+ id: index_1.ViewerErrorIds.InvalidParameterValue,
108
+ message: `Unable to parse paintable value: not a valid JSON string\nGiven value: ${value}`,
109
+ });
110
+ }
111
+ }
112
+ if (valObj) {
113
+ // input string is JSON, src attribute is required
114
+ if (!valObj.src) {
115
+ throw new index_1.ViewerError({
116
+ id: index_1.ViewerErrorIds.InvalidParameterValue,
117
+ message: `Unable to parse paintable value: property "src" is missing\nGiven value: ${value}`,
118
+ });
119
+ }
120
+ if (!(0, lodash_es_1.isString)(valObj.src)) {
121
+ throw new index_1.ViewerError({
122
+ id: index_1.ViewerErrorIds.InvalidParameterValue,
123
+ message: `Unable to parse paintable value: property "src" is not a string\nGiven value: ${value}`,
124
+ });
125
+ }
126
+ // split src and options
127
+ const { src } = valObj, options = __rest(valObj, ["src"]);
128
+ paintableValue.src = src;
129
+ // only forward valid paintable options
130
+ const validOptionKeys = ['uScale', 'vScale', 'uOffset', 'vOffset'];
131
+ const { validOptions, invalidKeys } = Object.entries(options).reduce((accRes, [curKey, curValue]) => {
132
+ const isValidKey = validOptionKeys.includes(curKey);
133
+ if (isValidKey) {
134
+ accRes.validOptions[curKey] = curValue;
135
+ }
136
+ else {
137
+ accRes.invalidKeys.push(curKey);
138
+ }
139
+ return accRes;
140
+ }, { validOptions: {}, invalidKeys: [] });
141
+ if (invalidKeys.length) {
142
+ console.warn('Invalid paintable options provided: ' + invalidKeys.toString());
143
+ }
144
+ paintableValue.options = validOptions;
145
+ }
146
+ return paintableValue;
147
+ }
148
+ exports.parsePaintable = parsePaintable;
149
+ function _drawPaintableOnMaterial(material, imageSource, scene, options) {
150
+ var _a, _b, _c, _d;
151
+ // always take width and height from image source, scaling is done with uvScale properties
152
+ const widthAndHeight = {
153
+ width: imageSource.width,
154
+ height: imageSource.height,
155
+ };
156
+ const texture = new index_1.DynamicTexture(`${material.id}.paintable_texture`, widthAndHeight, scene);
157
+ // draw image on texture
158
+ const ctx = texture.getContext();
159
+ ctx.drawImage(imageSource, 0, 0);
160
+ texture.update();
161
+ // apply settings from paintable options to tweak position and scaling of image on the texture
162
+ texture.uScale = (_a = options === null || options === void 0 ? void 0 : options.uScale) !== null && _a !== void 0 ? _a : texture.uScale;
163
+ texture.vScale = (_b = options === null || options === void 0 ? void 0 : options.vScale) !== null && _b !== void 0 ? _b : texture.vScale;
164
+ texture.uOffset = (_c = options === null || options === void 0 ? void 0 : options.uOffset) !== null && _c !== void 0 ? _c : texture.uOffset;
165
+ texture.vOffset = (_d = options === null || options === void 0 ? void 0 : options.vOffset) !== null && _d !== void 0 ? _d : texture.vOffset;
166
+ // wrap mode is preferred, as it will always show the texture, no matter which position offset is currently chosen
167
+ // clamp mode requires more knowledge (and patience) when adjusting the uv scale and offset values
168
+ texture.wrapU = index_1.Texture.WRAP_ADDRESSMODE;
169
+ texture.wrapV = index_1.Texture.WRAP_ADDRESSMODE;
170
+ // apply the paintable texture on the dedicated material type
171
+ const materialCls = material.getClassName();
172
+ switch (materialCls) {
173
+ case 'PBRMaterial':
174
+ material.albedoTexture = texture;
175
+ break;
176
+ case 'StandardMaterial':
177
+ material.diffuseTexture = texture;
178
+ break;
179
+ default:
180
+ throw new Error(`Setting paintable texture for material of instance "${materialCls}" not implemented (yet)`);
181
+ }
182
+ }
183
+ /**
184
+ * Creates a HTML image element based on a SVG string, whereas all the embedded assets in the SVG (eg: fonts, images)
185
+ * are already loaded and exchanged by their base64 representation.\
186
+ * There the output image can exist as "standalone" image and may be used for example as a paintable.
187
+ *
188
+ * !!CAUTION!!: The used functions within this code section are very well evaluated since most alternatives
189
+ * somehow don't work in Safari, as mentioned in the following BJS forum entries:
190
+ * - https://forum.babylonjs.com/t/drawing-svg-content-text-into-dynamictexture-doesnt-work-in-safari-v15/25048
191
+ * - https://forum.babylonjs.com/t/texture-createfrombase64string-doesnt-seem-to-work-for-ios-devices-initially/25502
192
+ */
193
+ function _createImageFromSvg(svgSrc) {
194
+ return __awaiter(this, void 0, void 0, function* () {
195
+ // replace assets with their base64 versions in svg source code
196
+ const svgWithAssetsEmbedded = yield _embedAssets(svgSrc);
197
+ // create data string which can be used as an image source
198
+ const svgEncoded = 'data:image/svg+xml,' + encodeURIComponent(svgWithAssetsEmbedded);
199
+ return _createImageFromImgSrc(svgEncoded);
200
+ });
201
+ }
202
+ /**
203
+ * Creates an HTML image element from a dedicated image source.\
204
+ * Also waits until the image has loaded.
205
+ *
206
+ * !!CAUTION!!: The `setTimeout` after loading is finished is required due to a Safari bug:
207
+ * - https://bugs.webkit.org/show_bug.cgi?id=39059
208
+ * - https://bugs.webkit.org/show_bug.cgi?id=219770
209
+ *
210
+ * It's not 100% ensured that the timeout solves the issue in every case, but there is no other way unfortunately.\
211
+ * => Keep an eye on it in future projects
212
+ *
213
+ * @param imgSrc Theoretically every source is valid which is also supported by
214
+ * [HTMLImageElement.src](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/src).\
215
+ * Known exceptions are SVGs with embedded assets that are provided as object URL. See comments in
216
+ * {@link createImageFromSvg} for further details.
217
+ */
218
+ function _createImageFromImgSrc(imgSrc) {
219
+ return __awaiter(this, void 0, void 0, function* () {
220
+ const img = new Image();
221
+ yield new Promise((resolve, reject) => {
222
+ img.onload = () => {
223
+ setTimeout(resolve, 0);
224
+ };
225
+ img.onerror = () => {
226
+ reject();
227
+ };
228
+ img.crossOrigin = 'anonymous';
229
+ img.src = imgSrc;
230
+ });
231
+ return img;
232
+ });
233
+ }
234
+ /**
235
+ * Replaces all supported image & font URLs in the given SVG with their base64 representation.
236
+ */
237
+ function _embedAssets(svgSrc) {
238
+ return __awaiter(this, void 0, void 0, function* () {
239
+ const _imageExtensions = ['png', 'gif', 'jpg', 'jpeg', 'svg', 'bmp'];
240
+ const _fontExtensions = ['woff2', 'woff', 'ttf', 'otf'];
241
+ const _assetExtensions = [..._imageExtensions, ..._fontExtensions];
242
+ // Regex copied from https://stackoverflow.com/a/8943487/1273551, not "stress tested"...
243
+ const urlRegex = /(\bhttps?:\/\/[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/gi;
244
+ const allUrls = svgSrc.match(urlRegex);
245
+ const assetUrls = allUrls.filter(url => {
246
+ const indexParam = url.indexOf('?');
247
+ // remove url parameter to recognize extension
248
+ if (indexParam > -1) {
249
+ url = url.substring(0, indexParam);
250
+ }
251
+ return _assetExtensions.some(extension => url.toLowerCase().endsWith(`.${extension}`));
252
+ });
253
+ const assetBase64Fetcher = assetUrls.map(_fetchBase64AssetUrl);
254
+ const assetFetcherResults = yield Promise.all(assetBase64Fetcher);
255
+ return assetFetcherResults.reduce((svgSrc, x) => svgSrc.replace(x.url, x.base64), svgSrc);
256
+ });
257
+ }
258
+ /**
259
+ * Fetch asset (image or font) and convert it to base64 string representation.
260
+ */
261
+ function _fetchBase64AssetUrl(assetUrl) {
262
+ return __awaiter(this, void 0, void 0, function* () {
263
+ // TODO WTT: Cache known base64 representation and only fetch/convert when not already known.
264
+ // Usually the fetch shouldn't hit the network but the browser cache since the SVG was already drawn..
265
+ const resp = yield fetch(assetUrl);
266
+ const blob = yield resp.blob();
267
+ return new Promise((resolve, reject) => {
268
+ const reader = new FileReader();
269
+ reader.onloadend = (event) => {
270
+ const target = event.target;
271
+ if (!target) {
272
+ return reject(`Asset with URL "${assetUrl}" could not be loaded.`);
273
+ }
274
+ const result = target.result;
275
+ if (!result) {
276
+ return reject(`Asset with URL "${assetUrl}" returned an empty result.`);
277
+ }
278
+ resolve({
279
+ url: assetUrl,
280
+ base64: result.toString(),
281
+ });
282
+ };
283
+ reader.readAsDataURL(blob);
284
+ });
285
+ });
286
+ }
287
287
  //# sourceMappingURL=paintable-helper.js.map
@@ -1,12 +1,12 @@
1
- import { Material, Node } from '../index';
2
- /**
3
- * This is a wrapper around Babylon.js Tags API, as the API is really clunky to use
4
- */
5
- declare type TagTarget = Node | Material;
6
- export declare function hasTag(object: TagTarget, tag: string): boolean;
7
- export declare function getTags(object: TagTarget): string[];
8
- export declare function setTags(object: TagTarget, tags: string[]): void;
9
- export declare function deleteAllTags(object: TagTarget): void;
10
- export declare function setTagsAsString(object: TagTarget, tagsString: string): void;
11
- export declare function cloneTags(sourceObject: TagTarget, destinationObject: TagTarget): void;
12
- export {};
1
+ import { Material, Node } from '../index';
2
+ /**
3
+ * This is a wrapper around Babylon.js Tags API, as the API is really clunky to use
4
+ */
5
+ declare type TagTarget = Node | Material;
6
+ export declare function hasTag(object: TagTarget, tag: string): boolean;
7
+ export declare function getTags(object: TagTarget): string[];
8
+ export declare function setTags(object: TagTarget, tags: string[]): void;
9
+ export declare function deleteAllTags(object: TagTarget): void;
10
+ export declare function setTagsAsString(object: TagTarget, tagsString: string): void;
11
+ export declare function cloneTags(sourceObject: TagTarget, destinationObject: TagTarget): void;
12
+ export {};