@woosh/meep-engine 2.61.0 → 2.63.0

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 (56) hide show
  1. package/build/meep.cjs +1277 -1259
  2. package/build/meep.min.js +1 -1
  3. package/build/meep.module.js +1277 -1259
  4. package/package.json +1 -1
  5. package/src/core/binary/EncodingBinaryBuffer.js +7 -43
  6. package/src/core/binary/EncodingBinaryBuffer.spec.js +16 -0
  7. package/src/core/bvh2/BinaryNode.js +16 -13
  8. package/src/core/bvh2/LeafNode.js +6 -3
  9. package/src/core/bvh2/bvh3/EBBVHLeafProxy.js +4 -2
  10. package/src/core/bvh2/bvh3/query/bvh_query_user_data_overlaps_sphere.js +81 -0
  11. package/src/core/cache/LoadingCache.js +4 -1
  12. package/src/core/collection/map/BiMap.js +49 -0
  13. package/src/core/geom/3d/aabb/AABB3.js +24 -36
  14. package/src/core/geom/3d/aabb/aabb3_array_compute_from_sphere.js +22 -0
  15. package/src/core/geom/3d/aabb/aabb3_array_intersects_sphere.js +22 -0
  16. package/src/core/geom/3d/aabb/aabb3_array_intersects_sphere_array.js +11 -0
  17. package/src/core/geom/3d/aabb/aabb3_signed_distance_to_aabb3.js +28 -0
  18. package/src/core/geom/3d/aabb/serializeAABB3Quantized16Uint.js +19 -10
  19. package/src/core/geom/3d/tetrahedra/delaunay/Cavity.js +3 -4
  20. package/src/engine/ecs/components/Tag.d.ts +2 -0
  21. package/src/engine/ecs/components/Tag.js +19 -28
  22. package/src/engine/ecs/components/Tag.spec.js +47 -0
  23. package/src/engine/ecs/foliage/ecs/Foliage2System.js +3 -0
  24. package/src/engine/ecs/foliage/ecs/InstancedMeshComponent.js +4 -1
  25. package/src/engine/ecs/foliage/ecs/convertInstancedMeshComponents2Entities.js +64 -0
  26. package/src/engine/ecs/foliage/ecs/{InstancedMeshUtils.js → optimizeIndividualMeshesEntitiesToInstances.js} +11 -70
  27. package/src/engine/ecs/fow/FogOfWar.js +4 -0
  28. package/src/engine/ecs/fow/FogOfWarEditor.js +3 -0
  29. package/src/engine/ecs/terrain/TerrainPreview.js +45 -44
  30. package/src/engine/ecs/terrain/ecs/cling/ClingToTerrain.js +22 -4
  31. package/src/engine/ecs/terrain/tiles/TerrainTile.js +17 -12
  32. package/src/engine/graphics/camera/testClippingPlaneComputation.js +25 -27
  33. package/src/engine/graphics/ecs/mesh/Mesh.d.ts +0 -4
  34. package/src/engine/graphics/ecs/mesh/Mesh.js +0 -11
  35. package/src/engine/graphics/ecs/mesh/MeshSystem.js +57 -67
  36. package/src/engine/graphics/ecs/path/testPathDisplaySystem.js +49 -52
  37. package/src/engine/graphics/ecs/path/tube/prototypeAnimatedPathMask.js +40 -42
  38. package/src/engine/graphics/particles/ecs/ParticleEmitterSystem.js +43 -25
  39. package/src/engine/graphics/particles/particular/engine/ParticularEngine.js +10 -6
  40. package/src/engine/graphics/particles/particular/engine/emitter/ParticleEmitter.js +37 -41
  41. package/src/engine/graphics/particles/particular/engine/utils/volume/prototypeParticleVolume.js +44 -46
  42. package/src/engine/graphics/render/buffer/buffers/prototypeNormalFrameBuffer.js +24 -26
  43. package/src/engine/graphics/render/forward_plus/plugin/ptototypeFPPlugin.js +40 -42
  44. package/src/engine/graphics/render/visibility/hiz/prototypeHiZ.js +36 -38
  45. package/src/engine/graphics/shadows/testShadowMapRendering.js +19 -19
  46. package/src/engine/grid/ORTHOGONAL_NEIGHBOURHOOD_MASK.js +11 -0
  47. package/src/engine/sound/dB2Volume.js +8 -0
  48. package/src/engine/sound/ecs/emitter/SoundEmitter.js +125 -99
  49. package/src/engine/sound/ecs/emitter/SoundEmitterComponentContext.js +4 -42
  50. package/src/engine/sound/ecs/emitter/SoundEmitterSystem.js +31 -121
  51. package/src/engine/sound/volume2dB.js +8 -0
  52. package/src/generation/theme/ThemeEngine.js +19 -53
  53. package/src/core/binary/stringToByteArray.js +0 -24
  54. package/src/engine/graphics/geometry/bvh/buffered/BVHFromBufferGeometry.js +0 -133
  55. package/src/engine/save/storage/LocalStorage.js +0 -148
  56. package/src/engine/save/storage/MsgPackCodec.js +0 -22
@@ -5,23 +5,24 @@
5
5
  */
6
6
 
7
7
 
8
- import { System } from '../../../ecs/System.js';
9
- import { SoundEmitter } from './SoundEmitter.js';
10
- import { Transform } from '../../../ecs/transform/Transform.js';
11
- import { SoundAssetLoader } from "../../../asset/loaders/SoundAssetLoader.js";
12
- import { GameAssetType } from "../../../asset/GameAssetType.js";
13
- import { BinaryNode } from "../../../../core/bvh2/BinaryNode.js";
14
- import SoundListener from "../SoundListener.js";
15
- import { IncrementalDeltaSet } from "../../../graphics/render/visibility/IncrementalDeltaSet.js";
16
8
  import {
17
- queryBinaryNode_SphereIntersections_Data
18
- } from "../../../../core/bvh2/traversal/queryBinaryNode_SphereIntersections.js";
19
- import { SoundEmitterComponentContext } from "./SoundEmitterComponentContext.js";
20
- import { SoundEmitterFlags } from "./SoundEmitterFlags.js";
21
- import { SoundEmitterChannel } from "./SoundEmitterChannel.js";
22
- import { invokeObjectCompare } from "../../../../core/model/object/invokeObjectCompare.js";
23
- import { tryRotateSingleNode } from "../../../../core/bvh2/transform/tryRotateSingleNode.js";
24
- import { SoundTrackFlags } from "./SoundTrackFlags.js";
9
+ ExplicitBinaryBoundingVolumeHierarchy
10
+ } from "../../../../core/bvh2/bvh3/ExplicitBinaryBoundingVolumeHierarchy.js";
11
+ import {
12
+ bvh_query_user_data_overlaps_sphere
13
+ } from "../../../../core/bvh2/bvh3/query/bvh_query_user_data_overlaps_sphere.js";
14
+ import {invokeObjectCompare} from "../../../../core/model/object/invokeObjectCompare.js";
15
+ import {GameAssetType} from "../../../asset/GameAssetType.js";
16
+ import {SoundAssetLoader} from "../../../asset/loaders/SoundAssetLoader.js";
17
+ import {System} from '../../../ecs/System.js';
18
+ import {Transform} from '../../../ecs/transform/Transform.js';
19
+ import {IncrementalDeltaSet} from "../../../graphics/render/visibility/IncrementalDeltaSet.js";
20
+ import SoundListener from "../SoundListener.js";
21
+ import {SoundEmitter} from './SoundEmitter.js';
22
+ import {SoundEmitterChannel} from "./SoundEmitterChannel.js";
23
+ import {SoundEmitterComponentContext} from "./SoundEmitterComponentContext.js";
24
+ import {SoundEmitterFlags} from "./SoundEmitterFlags.js";
25
+ import {SoundTrackFlags} from "./SoundTrackFlags.js";
25
26
 
26
27
  /**
27
28
  * @readonly
@@ -35,21 +36,9 @@ export const SoundEmitterChannels = {
35
36
 
36
37
  /**
37
38
  *
38
- * @type {Map<NodeDescription, number>}
39
- */
40
- const leafCount = new Map();
41
-
42
- /**
43
- *
44
- * @type {SoundEmitterComponentContext[]}
39
+ * @type {number[]}
45
40
  */
46
- const positionalNodes = [];
47
-
48
- /**
49
- *
50
- * @type {number}
51
- */
52
- const OPTIMIZATION_LOOP_LIMIT = 10000;
41
+ const scratch_array = [];
53
42
 
54
43
  export class SoundEmitterSystem extends System {
55
44
  /**
@@ -103,17 +92,10 @@ export class SoundEmitterSystem extends System {
103
92
 
104
93
  /**
105
94
  * Spatial index
106
- * @type {BinaryNode}
107
- * @private
108
- */
109
- this.__bvh = new BinaryNode();
110
-
111
- /**
112
- *
113
- * @type {number}
95
+ * @type {ExplicitBinaryBoundingVolumeHierarchy}
114
96
  * @private
115
97
  */
116
- this.__optimizationPointer = 0;
98
+ this.__bvh = new ExplicitBinaryBoundingVolumeHierarchy();
117
99
 
118
100
  /**
119
101
  * Number of currently linked entities
@@ -226,6 +208,8 @@ export class SoundEmitterSystem extends System {
226
208
  emitter.buildNodes(context);
227
209
  }
228
210
 
211
+ emitter.bvh.link(this.__bvh, entity);
212
+
229
213
  const ctx = new SoundEmitterComponentContext();
230
214
 
231
215
  ctx.system = this;
@@ -240,11 +224,6 @@ export class SoundEmitterSystem extends System {
240
224
 
241
225
  this.data[entity] = ctx;
242
226
 
243
- //attach bvh
244
- this.__bvh.insertNode(ctx.leaf);
245
-
246
- leafCount.clear();
247
-
248
227
  this.__linkedCount++;
249
228
  }
250
229
 
@@ -266,12 +245,9 @@ export class SoundEmitterSystem extends System {
266
245
 
267
246
  ctx.unlink();
268
247
 
269
- ctx.leaf.disconnect();
270
-
271
248
  }
272
249
 
273
-
274
- leafCount.clear();
250
+ emitter.bvh.unlink();
275
251
 
276
252
  this.__linkedCount--;
277
253
  }
@@ -296,13 +272,18 @@ export class SoundEmitterSystem extends System {
296
272
 
297
273
  const listenerPosition = listenerTransform.position;
298
274
 
299
- const matchCount = queryBinaryNode_SphereIntersections_Data(positionalNodes, 0, this.__bvh, listenerPosition.x, listenerPosition.y, listenerPosition.z, 0);
275
+ const matchCount = bvh_query_user_data_overlaps_sphere(
276
+ scratch_array, 0,
277
+ this.__bvh, [listenerPosition.x, listenerPosition.y, listenerPosition.z, 0]
278
+ );
300
279
 
301
280
  for (let i = 0; i < matchCount; i++) {
281
+ const entity = scratch_array[i];
282
+
302
283
  /**
303
284
  * @type {SoundEmitterComponentContext}
304
285
  */
305
- const ctx = positionalNodes[i];
286
+ const ctx = this.data[entity];
306
287
 
307
288
  const emitter = ctx.emitter;
308
289
 
@@ -378,79 +359,8 @@ export class SoundEmitterSystem extends System {
378
359
  }
379
360
 
380
361
  activeSet.finalizeUpdate();
381
-
382
- this.optimize(1, 50);
383
362
  }
384
363
 
385
- /**
386
- *
387
- * @param {number} timeout In milliseconds
388
- * @param {number} iterations Maximum number of steps the optimizer can take
389
- */
390
- optimize(timeout, iterations) {
391
- let ctx;
392
-
393
- let i = 0;
394
- let j = 0;
395
-
396
- if (this.__linkedCount <= 0) {
397
- //nothing to optimize
398
- return;
399
- }
400
-
401
- const data = this.data;
402
- const length = data.length;
403
-
404
- const t0 = performance.now();
405
-
406
-
407
- LOOP_MAIN: while (j < OPTIMIZATION_LOOP_LIMIT) {
408
-
409
- j++;
410
-
411
- //find next entity
412
- while (((ctx = data[this.__optimizationPointer]) === undefined)) {
413
-
414
- this.__optimizationPointer++;
415
-
416
- j++;
417
-
418
- if (this.__optimizationPointer >= length) {
419
- this.__optimizationPointer = 0;
420
-
421
- continue LOOP_MAIN;
422
- }
423
-
424
- }
425
-
426
- let n = ctx.leaf.parentNode;
427
-
428
- while (n !== null) {
429
-
430
- tryRotateSingleNode(n, leafCount);
431
-
432
- i++
433
-
434
- if (Math.random() < 0.5) {
435
- //random exit
436
- break;
437
- }
438
-
439
- n = n.parentNode;
440
- }
441
-
442
- this.__optimizationPointer++;
443
-
444
- const t1 = performance.now();
445
-
446
- const time = t1 - t0;
447
-
448
- if (time > timeout || i > iterations) {
449
-
450
- break;
451
- }
452
- }
453
- }
454
364
 
455
365
 
456
366
  }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Convert percentage volume to decibel
3
+ * @param {number} volume
4
+ * @returns {number}
5
+ */
6
+ function volume2dB(volume) {
7
+ return 20 * Math.log10(volume);
8
+ }
@@ -1,25 +1,23 @@
1
- import { QuadTreeNode } from "../../core/geom/2d/quad-tree/QuadTreeNode.js";
2
- import { assert } from "../../core/assert.js";
3
- import { seededRandom } from "../../core/math/random/seededRandom.js";
4
- import { TerrainLayerRuleAggregator } from "./TerrainLayerRuleAggregator.js";
5
- import { Sampler2D } from "../../engine/graphics/texture/sampler/Sampler2D.js";
1
+ import {assert} from "../../core/assert.js";
2
+ import {binarySearchLowIndex} from "../../core/collection/array/binarySearchLowIndex.js";
3
+ import {HashMap} from "../../core/collection/map/HashMap.js";
4
+ import {QuadTreeNode} from "../../core/geom/2d/quad-tree/QuadTreeNode.js";
5
+ import {randomFloatBetween} from "../../core/math/random/randomFloatBetween.js";
6
+ import {seededRandom} from "../../core/math/random/seededRandom.js";
7
+ import {number_compare_ascending} from "../../core/primitives/numbers/number_compare_ascending.js";
8
+ import Future from "../../core/process/Future.js";
6
9
  import Task from "../../core/process/task/Task.js";
7
- import { TaskSignal } from "../../core/process/task/TaskSignal.js";
8
10
  import TaskGroup from "../../core/process/task/TaskGroup.js";
9
- import Future from "../../core/process/Future.js";
10
- import { optimizeIndividualMeshesEntitiesToInstances } from "../../engine/ecs/foliage/ecs/InstancedMeshUtils.js";
11
- import TaskState from "../../core/process/task/TaskState.js";
12
- import { HashMap } from "../../core/collection/map/HashMap.js";
13
- import { TerrainLayer } from "../../engine/ecs/terrain/ecs/layers/TerrainLayer.js";
14
- import { TerrainFlags } from "../../engine/ecs/terrain/ecs/TerrainFlags.js";
15
- import { binarySearchLowIndex } from "../../core/collection/array/binarySearchLowIndex.js";
16
- import { randomFloatBetween } from "../../core/math/random/randomFloatBetween.js";
17
- import { obtainTerrain } from "../../engine/ecs/terrain/util/obtainTerrain.js";
18
- import { actionTask } from "../../core/process/task/util/actionTask.js";
19
- import { countTask } from "../../core/process/task/util/countTask.js";
20
- import { emptyTask } from "../../core/process/task/util/emptyTask.js";
21
- import { futureTask } from "../../core/process/task/util/futureTask.js";
22
- import { number_compare_ascending } from "../../core/primitives/numbers/number_compare_ascending.js";
11
+ import {TaskSignal} from "../../core/process/task/TaskSignal.js";
12
+ import {actionTask} from "../../core/process/task/util/actionTask.js";
13
+ import {countTask} from "../../core/process/task/util/countTask.js";
14
+ import {emptyTask} from "../../core/process/task/util/emptyTask.js";
15
+ import {futureTask} from "../../core/process/task/util/futureTask.js";
16
+ import {TerrainLayer} from "../../engine/ecs/terrain/ecs/layers/TerrainLayer.js";
17
+ import {TerrainFlags} from "../../engine/ecs/terrain/ecs/TerrainFlags.js";
18
+ import {obtainTerrain} from "../../engine/ecs/terrain/util/obtainTerrain.js";
19
+ import {Sampler2D} from "../../engine/graphics/texture/sampler/Sampler2D.js";
20
+ import {TerrainLayerRuleAggregator} from "./TerrainLayerRuleAggregator.js";
23
21
 
24
22
  /**
25
23
  *
@@ -530,39 +528,7 @@ export class ThemeEngine {
530
528
  terrain.buildLightMap().then(resolve, reject);
531
529
  }), 'Building Lightmap');
532
530
 
533
- const optimization_task = new TaskGroup([]);
534
-
535
- const tOptimizeMeshes = new Task({
536
- name: 'Mesh optimization',
537
- initializer(task, executor) {
538
-
539
- const o = optimizeIndividualMeshesEntitiesToInstances(ecd, 10);
540
-
541
- optimization_task.addChildren(o.tasks);
542
-
543
- executor.runGroup(optimization_task);
544
- },
545
- cycleFunction() {
546
- const state = optimization_task.state.getValue();
547
-
548
- if (state === TaskState.RUNNING) {
549
- return TaskSignal.Yield;
550
- } else if (state === TaskState.FAILED) {
551
- return TaskSignal.EndFailure;
552
- } else if (state === TaskState.SUCCEEDED) {
553
- return TaskSignal.EndSuccess;
554
- } else {
555
- return TaskSignal.Continue;
556
- }
557
- },
558
- computeProgress() {
559
- return optimization_task.computeProgress();
560
- }
561
- });
562
-
563
- tOptimizeMeshes.estimatedDuration = 5;
564
-
565
- return new TaskGroup([tLightMap, tOptimizeMeshes]);
531
+ return new TaskGroup([tLightMap]);
566
532
  }
567
533
 
568
534
  /**
@@ -1,24 +0,0 @@
1
- /**
2
- * Turns a string into an array of bytes; a "byte" being a JS number in the
3
- * range 0-255.
4
- * @param {string} str String value to arrify.
5
- * @return {Uint8Array} Array of numbers corresponding to the
6
- * UCS character codes of each character in str.
7
- */
8
- export function stringToByteArray(str) {
9
- const length = str.length;
10
-
11
- const output = [];
12
- let p = 0;
13
-
14
- for (let i = 0; i < length; i++) {
15
- let c = str.charCodeAt(i);
16
- while (c > 0xff) {
17
- output[p++] = c & 0xff;
18
- c >>= 8;
19
- }
20
- output[p++] = c;
21
- }
22
-
23
- return new Uint8Array(output);
24
- }
@@ -1,133 +0,0 @@
1
- /**
2
- * Created by Alex on 04/05/2016.
3
- */
4
- import { BinaryNode } from '../../../../../core/bvh2/BinaryNode.js';
5
- import { LeafNode } from '../../../../../core/bvh2/LeafNode.js';
6
- import IndexedTriangleBoundsComputer from './IndexedTraingleBoundsComputer.js';
7
-
8
- import { buildUnsorted as buildUnsortedBinaryBVH } from './BinaryBVHFromBufferGeometry.js';
9
-
10
- const makeTriangle = IndexedTriangleBoundsComputer.compute;
11
-
12
- /**
13
- *
14
- * @param object
15
- * @param {number|uint} a
16
- * @param {number|uint} b
17
- * @param {number|uint} c
18
- * @param {Float32Array|Float64Array} vertices
19
- */
20
- function makeTriangleLeaf(object, a, b, c, vertices) {
21
- return makeTriangle(a, b, c, vertices, function (x0, y0, z0, x1, y1, z1) {
22
- return new LeafNode(object, x0, y0, z0, x1, y1, z1);
23
- });
24
- }
25
-
26
- /**
27
- *
28
- * @param {Uint32Array|Uint16Array|Uint8Array} indices
29
- * @param {Float32Array|Float64Array} vertices
30
- * @param {BinaryNode} tree
31
- */
32
- function fillTree(indices, vertices, tree) {
33
- const numFaces = indices.length / 3;
34
- let iA, iB, iC;
35
-
36
- function processLeaf(index) {
37
- const index3 = index * 3;
38
-
39
- iA = indices[index3];
40
- iB = indices[index3 + 1];
41
- iC = indices[index3 + 2];
42
-
43
- return makeTriangleLeaf(index, iA * 3, iB * 3, iC * 3, vertices);
44
- }
45
-
46
- tree.insertManyBoxes2(processLeaf, numFaces);
47
- }
48
-
49
- /**
50
- *
51
- * @param {BufferGeometry} geometry
52
- * @returns {BinaryNode}
53
- */
54
- function bvhFromGeometry(geometry) {
55
- // console.profile( "building geometry bvh" );
56
- const tree = new BinaryNode();
57
- tree.setNegativelyInfiniteBounds();
58
- const vertices = geometry.getAttribute('position').array;
59
- const indices = geometry.getIndex().array;
60
-
61
- fillTree(indices, vertices, tree);
62
-
63
- // console.profileEnd( "building geometry bvh" );
64
- //
65
- //console.log("built bvh for " + faces.length + " faces");
66
- return tree;
67
- }
68
-
69
- /**
70
- *
71
- * @param {THREE.BufferGeometry} geometry
72
- * @returns {BinaryNode}
73
- */
74
- function buildUnsorted(geometry) {
75
- const tree = new BinaryNode();
76
- tree.setNegativelyInfiniteBounds();
77
- //
78
- const index = geometry.index;
79
- const indices = index.array;
80
- const vertices = geometry.attributes.position.array;
81
-
82
- let numNodes = indices.length / 3;
83
- let i, n;
84
- //create leaf nodes
85
- const nodes = new Array(numNodes);
86
- let iA, iB, iC;
87
-
88
-
89
- for (i = 0; i < numNodes; i++) {
90
- //leaf needs to be set up inside the callback
91
- const index3 = i * 3;
92
-
93
- iA = indices[index3];
94
- iB = indices[index3 + 1];
95
- iC = indices[index3 + 2];
96
- nodes[i] = makeTriangleLeaf(i, iA * 3, iB * 3, iC * 3, vertices);
97
- }
98
- while (numNodes > 2) {
99
- //sort leafs
100
-
101
- //pair
102
- for (i = 0; i < numNodes; i += 2) {
103
- const a = nodes[i];
104
- const b = nodes[i + 1];
105
- n = new BinaryNode();
106
- n.setChildren(a, b);
107
- nodes[i >> 1] = n;
108
- }
109
- numNodes = (numNodes >> 1) + numNodes % 2;
110
- //nodes.length = numNodes;
111
- }
112
- //finally insert these boxes from this node
113
- nodes.length = numNodes;
114
- for (i = 0; i < numNodes; i++) {
115
- n = nodes[i];
116
- tree.insertNode(n);
117
- }
118
- return tree;
119
- }
120
-
121
-
122
- export default {
123
- build: bvhFromGeometry,
124
- buildUnsorted: buildUnsorted,
125
- setFaceBounds: makeTriangleLeaf,
126
- buildUnsortedBinaryBVH: function (geometry) {
127
-
128
- const index = geometry.index;
129
- const indices = index.array;
130
- const vertices = geometry.attributes.position.array;
131
- return buildUnsortedBinaryBVH(vertices, indices);
132
- }
133
- };
@@ -1,148 +0,0 @@
1
- /**
2
- * Created by Alex on 22/02/2017.
3
- */
4
-
5
-
6
- import MsgPackCodec from './MsgPackCodec.js';
7
-
8
- import Storage from '../Storage.js';
9
- import { InMemoryLocalStorage } from "./InMemoryLocalStorage.js";
10
- import {stringToByteArray} from "../../../core/binary/stringToByteArray.js";
11
- import {byteArrayToString} from "../../../core/binary/byteArrayToString.js";
12
-
13
-
14
- class LocalStorage extends Storage {
15
- constructor(namespace, services) {
16
- super();
17
- this.namespace = namespace;
18
- this.services = services;
19
-
20
- this.compressionLevel = 2;
21
- this.compressionEnabled = false;
22
-
23
- this.codec = new MsgPackCodec();
24
-
25
- try {
26
- console.log('Accessing Window.localStorage...');
27
- this.localStorage = window.localStorage;
28
- console.log('LocalStorage acquired');
29
- } catch (e) {
30
- console.error(`Failed to get localStorage:`, e);
31
-
32
- // This fallback allows the system to continue functioning at least
33
- this.localStorage = new InMemoryLocalStorage();
34
-
35
- console.warn(`Falling back to in-memory storage`);
36
- }
37
-
38
- const item = this.localStorage.getItem(this.namespace + "-list");
39
- let stored;
40
-
41
- try {
42
- stored = JSON.parse(item);
43
- } catch (e) {
44
- console.error('Failed to parse loaded item:', e, item);
45
- console.warn('Ignoring previously stored data');
46
- stored = null;
47
- }
48
-
49
- if (stored !== null && typeof stored === "object" && typeof stored.length === "number") {
50
- this.__list = stored;
51
- } else {
52
- this.__list = [];
53
- }
54
- }
55
-
56
- makeObjectId(key) {
57
- return this.namespace + '-item-' + key;
58
- }
59
-
60
- storeBinary(key, value, resolve, reject, progress) {
61
- const self = this;
62
-
63
- function store(data) {
64
- const compressedUint8Array = new Uint8Array(data.length);
65
- compressedUint8Array.set(data, 0);
66
-
67
- if (compressedUint8Array.length !== value.length) {
68
- console.log("Compressed size:", compressedUint8Array.length, "bytes, original ", value.length, ".", (compressedUint8Array.length / value.length * 100).toFixed(2) + "% of the original");
69
- }
70
-
71
- const compressedString = byteArrayToString(compressedUint8Array);
72
-
73
- self.localStorage.setItem(self.makeObjectId(key), compressedString);
74
-
75
- if (self.__list.indexOf(key) === -1) {
76
- //update the list
77
- self.__list.push(key);
78
- self.localStorage.setItem(self.namespace + "-list", JSON.stringify(self.__list));
79
- }
80
-
81
- if (typeof resolve === "function") {
82
- resolve();
83
- }
84
- }
85
-
86
- if (this.compressionEnabled) {
87
- const compressionService = this.services.compression;
88
-
89
- compressionService
90
- .encode(value, this.compressionLevel)
91
- .then(store, reject);
92
- } else {
93
- store(value);
94
- }
95
- }
96
-
97
- store(key, value, resolve, reject, progress) {
98
- const rawData = this.codec.encode(value);
99
-
100
- this.storeBinary(key, rawData, resolve, reject, progress);
101
- }
102
-
103
- loadBinary(key, resolve, reject, progress) {
104
-
105
- let compressedString = this.localStorage.getItem(this.makeObjectId(key));
106
-
107
- if (compressedString === null) {
108
- //no data
109
- resolve(new ArrayBuffer(0));
110
- return;
111
- }
112
-
113
- const uint8array = stringToByteArray(compressedString);
114
-
115
- const data = uint8array.buffer;
116
- // console.log("compressedBytes", compressedBytes);
117
-
118
- if (this.compressionEnabled) {
119
- const compressionService = this.services.compression;
120
-
121
- compressionService.decode(data).then(resolve, reject);
122
- } else {
123
- resolve(data);
124
- }
125
- }
126
-
127
- load(key, resolve, reject, progress) {
128
- const codec = this.codec;
129
-
130
- this.loadBinary(key, function (binary) {
131
- let result;
132
-
133
- try {
134
- result = codec.decode(new Uint8Array(binary));
135
- } catch (e) {
136
- reject(e);
137
- }
138
-
139
- resolve(result);
140
- }, reject, progress);
141
- }
142
-
143
- list(resolve, reject) {
144
- resolve(this.__list);
145
- }
146
- }
147
-
148
- export default LocalStorage;
@@ -1,22 +0,0 @@
1
- /**
2
- * Created by Alex on 12/06/2017.
3
- */
4
-
5
- import msgpack from 'msgpack-lite';
6
-
7
- function MsgPackCodec() {
8
-
9
- }
10
-
11
- MsgPackCodec.prototype.encode = function (json) {
12
- console.time("encoding of value");
13
- const result = msgpack.encode(json);
14
- console.timeEnd("encoding of value");
15
- return result;
16
- };
17
-
18
- MsgPackCodec.prototype.decode = function (bytes) {
19
- return msgpack.decode(bytes);
20
- };
21
-
22
- export default MsgPackCodec;