littlejsengine 1.17.11 → 1.17.15

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 (48) hide show
  1. package/AI.md +162 -0
  2. package/README.md +50 -63
  3. package/dist/littlejs.d.ts +150 -68
  4. package/dist/littlejs.esm.js +323 -105
  5. package/dist/littlejs.esm.min.js +1 -1
  6. package/dist/littlejs.js +320 -104
  7. package/dist/littlejs.min.js +1 -1
  8. package/dist/littlejs.release.js +318 -101
  9. package/examples/electron/{build.js → build.mjs} +26 -23
  10. package/examples/electron/game.js +5 -50
  11. package/examples/electron/index.html +2 -2
  12. package/examples/index.html +1 -0
  13. package/examples/module/{build.js → build.mjs} +22 -19
  14. package/examples/shorts/base.html +1 -1
  15. package/examples/shorts/hillGlideGame.js +1 -1
  16. package/examples/shorts/nineSlice.js +3 -3
  17. package/examples/shorts/shapes.js +1 -1
  18. package/examples/shorts/uiSystem.js +17 -16
  19. package/examples/starter/build.bat +1 -1
  20. package/examples/starter/{build.js → build.mjs} +25 -22
  21. package/examples/starter/index.html +2 -2
  22. package/examples/typescript/build.mjs +60 -0
  23. package/examples/typescript/game.js +2 -2
  24. package/examples/typescript/tsconfig.json +11 -2
  25. package/package.json +2 -2
  26. package/plugins/pluginExport.js +1 -0
  27. package/plugins/uiSystem.js +143 -20
  28. package/reference.md +0 -1
  29. package/src/engine.js +16 -14
  30. package/src/engineAudio.js +9 -6
  31. package/src/{engineBuild.js → engineBuild.mjs} +95 -78
  32. package/src/engineDebug.js +8 -5
  33. package/src/engineDraw.js +16 -14
  34. package/src/engineExport.js +2 -1
  35. package/src/engineInput.js +29 -8
  36. package/src/engineMath.js +46 -14
  37. package/src/engineMedals.js +6 -3
  38. package/src/engineObject.js +14 -3
  39. package/src/engineParticles.js +8 -3
  40. package/src/engineRelease.js +6 -2
  41. package/src/engineTileLayer.js +8 -4
  42. package/src/engineUtilities.js +6 -2
  43. package/src/engineWebGL.js +11 -8
  44. package/src/jsconfig.json +2 -1
  45. package/examples/electron/build.bat +0 -7
  46. package/examples/module/build.bat +0 -7
  47. package/examples/typescript/build.bat +0 -5
  48. package/examples/typescript/build.js +0 -31
package/src/engineDraw.js CHANGED
@@ -1,21 +1,22 @@
1
1
  /**
2
2
  * LittleJS Drawing System
3
- * - Hybrid system with both Canvas2D and WebGL available
4
- * - Super fast tile sheet rendering with WebGL
5
- * - Can apply rotation, mirror, color and additive color
6
- * - Font rendering system with built in engine font
7
- * - Many useful utility functions
3
+ * - Hybrid rendering with both Canvas2D and WebGL support
4
+ * - Optimized tile sheet sprite rendering using WebGL batching
5
+ * - Primitive drawing for polygons, ellipses, and lines
6
+ * - Tile-based rendering with TileInfo and TextureInfo classes
7
+ * - Text rendering with custom fonts and FontImage support
8
+ * - Color and additive color blending for effects
9
+ * - Rotation, mirroring, and scaling transformations
10
+ * - Camera system with position, scale, and rotation
11
+ * - Multiple canvas support (main, WebGL, work canvases)
12
+ * - Gradient fills and outlined shapes
13
+ * - Image manipulation and color tinting
8
14
  *
9
- * LittleJS uses a hybrid rendering solution with the best of both Canvas2D and WebGL.
10
- * There are 3 canvas/contexts available to draw to...
11
- * mainCanvas - 2D background canvas, non WebGL stuff like tile layers are drawn here.
12
- * glCanvas - Used by the accelerated WebGL batch rendering system.
15
+ * Rendering Architecture:
16
+ * - glCanvas: WebGL canvas for accelerated sprite batch rendering
17
+ * - mainCanvas: Canvas2D overlay for text, UI, and custom drawing
18
+ * - All draw functions default to WebGL when enabled, can force Canvas2D with useWebGL parameter
13
19
  *
14
- * The WebGL rendering system is very fast with some caveats...
15
- * - Switching blend modes (additive) or textures causes another draw call which is expensive in excess
16
- * - Group additive rendering together using renderOrder to mitigate this issue
17
- *
18
- * The LittleJS rendering solution is intentionally simple, feel free to adjust it for your needs!
19
20
  * @namespace Draw
20
21
  */
21
22
 
@@ -108,6 +109,7 @@ function tile(index=new Vector2, size=tileDefaultSize, texture=0, padding=tileDe
108
109
  // create tile info object
109
110
  const textureInfo = typeof texture === 'number' ?
110
111
  textureInfos[texture] : texture;
112
+ ASSERT(textureInfo instanceof TextureInfo, 'tile texture is not loaded');
111
113
 
112
114
  // get the position of the tile
113
115
  const sizePaddedX = size.x + padding*2;
@@ -1,5 +1,6 @@
1
1
  /**
2
2
  * LittleJS Module Export
3
+ * - Exports all engine modules and functions for external use
3
4
  */
4
5
 
5
6
  export
@@ -168,7 +169,7 @@ export
168
169
  nearestPowerOfTwo,
169
170
  isOverlapping,
170
171
  isIntersecting,
171
- wave,
172
+ oscillate,
172
173
 
173
174
  // Utilities
174
175
  formatTime,
@@ -1,10 +1,13 @@
1
1
  /**
2
2
  * LittleJS Input System
3
- * - Tracks keyboard down, pressed, and released
4
- * - Tracks mouse buttons, position, and wheel
5
- * - Tracks multiple analog gamepads
6
- * - Touch input is handled as mouse input
7
- * - Virtual gamepad for touch devices
3
+ * - Keyboard input with key down, pressed, and released states
4
+ * - Mouse input with position (world and screen space), buttons, and wheel
5
+ * - Gamepad support for multiple controllers with analog sticks and buttons
6
+ * - Touch input mapped to mouse position and buttons
7
+ * - Virtual on-screen gamepad for mobile devices
8
+ * - Automatic gamepad vs keyboard/mouse detection
9
+ * - Input event prevention for canvas focus
10
+ * - Clipboard copy/paste support
8
11
  * @namespace Input
9
12
  */
10
13
 
@@ -336,7 +339,19 @@ function inputInit()
336
339
  inputData[0][remapKey(e.code)] = 3;
337
340
  }
338
341
 
339
- // prevent arrow key from moving the page
342
+ // try to prevent default browser handling of input
343
+ if (!inputPreventDefault || !document.hasFocus() || !e.cancelable) return;
344
+
345
+ // don't break browser shortcuts
346
+ if (e.ctrlKey || e.metaKey || e.altKey) return;
347
+
348
+ // don't interfere with user typing into UI fields
349
+ if (isTextInput(e.target) || isTextInput(document.activeElement)) return;
350
+
351
+ // fix browser setting "Search for text when you start typing"
352
+ const printable = typeof e.key === 'string' && e.key.length === 1;
353
+
354
+ // prevent arrow key and other default keys from messing with stuff
340
355
  const preventDefaultKeys =
341
356
  [
342
357
  'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', // scrolling
@@ -344,9 +359,15 @@ function inputInit()
344
359
  'Tab', // focus navigation
345
360
  'Backspace', // browser back
346
361
  ];
347
- if (preventDefaultKeys.includes(e.code))
348
- if (inputPreventDefault && document.hasFocus() && e.cancelable)
362
+ if (preventDefaultKeys.includes(e.code) || printable)
349
363
  e.preventDefault();
364
+
365
+ function isTextInput(element)
366
+ {
367
+ const tag = element?.tagName;
368
+ const editable = element?.isContentEditable;
369
+ return editable || ['INPUT','TEXTAREA','SELECT'].includes(tag);
370
+ }
350
371
  }
351
372
  function onKeyUp(e)
352
373
  {
package/src/engineMath.js CHANGED
@@ -1,9 +1,16 @@
1
1
  /**
2
2
  * LittleJS Math Classes and Functions
3
- * - General purpose math library
4
- * - RandomGenerator - seeded random number generator
5
- * - Vector2 - fast, simple, easy 2D vector class
6
- * - Color - holds a rgba color with math functions
3
+ * - Comprehensive math utilities for game development
4
+ * - Vector2 class for 2D positions, directions, and math operations
5
+ * - Color class for RGBA colors with interpolation and manipulation
6
+ * - RandomGenerator for seeded pseudo-random number generation
7
+ * - Math shortcuts (PI, abs, floor, ceil, min, max, sin, cos, etc.)
8
+ * - Interpolation functions (lerp, smoothStep, percent)
9
+ * - Clamping, wrapping, and modulo operations
10
+ * - Angle utilities with wrap-around support
11
+ * - Collision detection (overlapping, intersection, line tests)
12
+ * - Random number generation and seeding
13
+ * - Type checking utilities
7
14
  * @namespace Math
8
15
  */
9
16
 
@@ -254,10 +261,24 @@ function isIntersecting(start, end, pos, size)
254
261
  * @param {number} [amplitude] - Amplitude (max height) of the wave
255
262
  * @param {number} [t=time] - Value to use for time of the wave
256
263
  * @param {number} [offset] - Value to use for time offset of the wave
264
+ * @param {number} [type] - Wave type: 0=sine, 1=triangle, 2=square, 3=sawtooth
257
265
  * @return {number} - Value waving between 0 and amplitude
258
266
  * @memberof Math */
259
- function wave(frequency=1, amplitude=1, t=time, offset=0)
260
- { return amplitude/2 * (1 - cos(offset + t*frequency*2*PI)); }
267
+ function oscillate(frequency=1, amplitude=1, t=time, offset=0, type=0)
268
+ {
269
+ const phase = (offset + t*frequency) % 1;
270
+ let value;
271
+
272
+ if (type === 1) // triangle
273
+ value = 2 * abs(2 * phase - 1) - 1;
274
+ else if (type === 2) // square
275
+ value = phase < .5 ? -1 : 1;
276
+ else if (type === 3) // sawtooth
277
+ value = 2 * phase - 1;
278
+ else // sine
279
+ value = -cos(phase * 2*PI);
280
+ return amplitude/2 * (value + 1);
281
+ }
261
282
 
262
283
  /**
263
284
  * Check if object is a valid number, not NaN or undefined, but it may be infinite
@@ -339,15 +360,17 @@ function lineTest(posStart, posEnd, testFunction, normal)
339
360
  // set hit point
340
361
  const hitPos = vec2(posStart.x + dirX*t, posStart.y + dirY*t);
341
362
 
342
- // move inside of tile if on positive edge
363
+ // ensure result is inside the tile
343
364
  const e = 1e-9;
344
- if (wasX)
345
- {
346
- if (stepX < 0)
347
- hitPos.x -= e;
348
- }
349
- else if (stepY < 0)
350
- hitPos.y -= e;
365
+ const hitPosFloor = hitPos.floor();
366
+ if (hitPosFloor.x < pos.x)
367
+ hitPos.x = pos.x;
368
+ else if (hitPosFloor.x > pos.x)
369
+ hitPos.x = pos.x + 1 - e;
370
+ if (hitPosFloor.y < pos.y)
371
+ hitPos.y = pos.y;
372
+ else if (hitPosFloor.y > pos.y)
373
+ hitPos.y = pos.y + 1 - e;
351
374
 
352
375
  // set normal
353
376
  if (normal)
@@ -740,6 +763,15 @@ class Vector2
740
763
  * @return {Vector2} */
741
764
  floor() { return new Vector2(floor(this.x), floor(this.y)); }
742
765
 
766
+ /** Returns a copy of this vector snapped to a grid
767
+ * @param {number} grid - grid size to snap to
768
+ * @return {Vector2} */
769
+ snap(grid)
770
+ {
771
+ ASSERT_NUMBER_VALID(grid);
772
+ return new Vector2(floor(this.x*grid)/grid, floor(this.y*grid)/grid);
773
+ }
774
+
743
775
  /** Returns new vec2 with modded values
744
776
  * @param {number} [divisor]
745
777
  * @return {Vector2} */
@@ -1,8 +1,11 @@
1
1
  /**
2
2
  * LittleJS Medal System
3
- * - Tracks and displays medals
4
- * - Saves medals to local storage
5
- * - Newgrounds integration
3
+ * - Achievement/trophy system for games
4
+ * - Medal class with name, description, icon, and unlock tracking
5
+ * - Automatic saving to local storage
6
+ * - Visual display queue with slide-in notifications
7
+ * - Newgrounds API integration for online achievements
8
+ * - Debug mode to unlock/reset medals during development
6
9
  * @namespace Medals
7
10
  */
8
11
 
@@ -1,5 +1,12 @@
1
1
  /**
2
2
  * LittleJS Object System
3
+ * - EngineObject is the base class for all game objects
4
+ * - Handles automatic updating, rendering, physics, and collision
5
+ * - Supports parent-child hierarchies with transform inheritance
6
+ * - 2D physics with velocity, acceleration, damping, and gravity
7
+ * - Collision system with tiles and other objects
8
+ * - Renders sprites from tile sheets with color and rotation
9
+ * - Objects sorted by renderOrder for layered rendering
3
10
  */
4
11
 
5
12
  'use strict';
@@ -514,12 +521,16 @@ class EngineObject
514
521
  {
515
522
  if (!debug) return;
516
523
 
524
+ // check if there is anything to show
525
+ const hasPhysics = this.collideTiles || this.collideSolidObjects || this.isSolid;
526
+ if (!hasPhysics && !this.parent) return;
527
+
517
528
  // show object info for debugging
518
529
  const size = vec2(max(this.size.x, .2), max(this.size.y, .2));
519
530
  const color = rgb(this.collideTiles?1:0, this.collideSolidObjects?1:0, this.isSolid?1:0, .5);
520
- drawRect(this.pos, size, color, this.angle);
531
+ debugRect(this.pos, size, color, 0, this.angle, hasPhysics);
521
532
  if (this.parent)
522
- drawRect(this.pos, size.scale(.8), rgb(1,1,1,.5), this.angle);
523
- this.parent && drawLine(this.pos, this.parent.pos, .1, rgb(1,1,1,.5));
533
+ debugRect(this.pos, size.scale(.8), rgb(1,1,1,.5), 0, this.angle);
534
+ this.parent && debugLine(this.pos, this.parent.pos, rgb(1,1,1,.5), .5);
524
535
  }
525
536
  }
@@ -1,8 +1,13 @@
1
1
  /**
2
2
  * LittleJS Particle System
3
- * - A simple but fast and flexible particle system
4
- * - Lightweight Particles are created and managed by ParticleEmitters
5
- * - The particle design tool can be used to help create emitters
3
+ * - Fast and flexible particle effects system
4
+ * - ParticleEmitter spawns and manages lightweight Particle objects
5
+ * - Particles support color gradients, fading, rotation, and scaling
6
+ * - Physics simulation with velocity, gravity, and damping
7
+ * - Collision detection with tile layers
8
+ * - Additive blending for glowing effects
9
+ * - Cone-based emission with randomization
10
+ * - Particle design tool available for easy emitter creation
6
11
  * @namespace Particles
7
12
  */
8
13
 
@@ -1,7 +1,11 @@
1
1
  /**
2
2
  * LittleJS - Release Mode
3
- * - This file is used for release builds in place of engineDebug.js
4
- * - Debug functionality is disabled to reduce size and increase performance
3
+ * - Replaces engineDebug.js in production builds
4
+ * - All debug functions are stubbed out as no-ops
5
+ * - Removes ASSERT and LOG calls to reduce file size
6
+ * - Disables debug overlay, watermark, and visualizations
7
+ * - Improves performance by eliminating debug overhead
8
+ * - Significantly reduces final bundle size
5
9
  */
6
10
 
7
11
  'use strict';
@@ -1,9 +1,13 @@
1
1
  /**
2
2
  * LittleJS Tile Layer System
3
- * - Caches arrays of tiles to off screen canvas for fast rendering
4
- * - Unlimited numbers of layers, allocates canvases as needed
5
- * - Tile layers can be drawn to using their context with canvas2d
6
- * - Tile layers can also have collision with EngineObjects
3
+ * - Renders large tile-based levels efficiently using cached canvases
4
+ * - Unlimited tile layers with automatic canvas allocation
5
+ * - Layers support both rendering and collision detection
6
+ * - Direct canvas2d drawing access for custom tile rendering
7
+ * - TileLayer for rendering, TileCollisionLayer for physics
8
+ * - Collision callbacks for tile interactions with objects
9
+ * - Optimized raycast support for tile-based physics
10
+ * - Integration with Box2D physics via Box2DTileLayer plugin
7
11
  * @namespace TileLayers
8
12
  */
9
13
 
@@ -1,7 +1,11 @@
1
1
  /**
2
2
  * LittleJS Utility Classes and Functions
3
- * - General purpose utilities
4
- * - Timer - tracks time automatically
3
+ * - Timer - tracks time automatically with support for pause and real-time modes
4
+ * - Time formatting helper
5
+ * - JSON file fetching
6
+ * - File saving (text, canvas, data URLs)
7
+ * - Native share dialog support
8
+ * - Local storage save data management
5
9
  * @namespace Utilities
6
10
  */
7
11
 
@@ -1,13 +1,16 @@
1
1
  /**
2
2
  * LittleJS WebGL Interface
3
- * - All WebGL used by the engine is wrapped up here
4
- * - Will fall back to 2D canvas rendering if WebGL is not supported
5
- * - For normal stuff you won't need to see or call anything in this file
6
- * - For advanced stuff there are helper functions to create shaders, textures, etc
7
- * - Can be disabled with glEnable to revert to 2D canvas rendering
8
- * - Batches sprite rendering on GPU for incredibly fast performance
9
- * - Sprite transform math is done in the shader where possible
10
- * - Supports shadertoy style post processing shaders via plugin
3
+ * - WebGL2 rendering engine for high-performance graphics
4
+ * - Batched sprite rendering for drawing thousands of sprites efficiently
5
+ * - Instanced rendering using vertex array objects (VAOs)
6
+ * - Polygon rendering with triangle strip support
7
+ * - Shader system with custom vertex and fragment shaders
8
+ * - Texture management with automatic atlas support
9
+ * - Post-processing effects via framebuffer and shader plugins
10
+ * - Automatic fallback to Canvas2D if WebGL is unavailable
11
+ * - Context loss and restoration handling
12
+ * - Can be disabled with glEnable setting
13
+ * - Advanced users can create custom shaders and render targets
11
14
  * @namespace WebGL
12
15
  */
13
16
 
package/src/jsconfig.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "compilerOptions": {
3
3
  "checkJs": true,
4
- "target": "ES6"
4
+ "target": "ES2020",
5
+ "module": "esnext"
5
6
  },
6
7
  "exclude": [
7
8
  "engineRelease.js",
@@ -1,7 +0,0 @@
1
- rem LittleJS Build Script
2
- call node build.js
3
- if %errorlevel% neq 0 (
4
- echo Build failed with error level %errorlevel%
5
- pause
6
- exit /b %errorlevel%
7
- )
@@ -1,7 +0,0 @@
1
- rem LittleJS Build Script
2
- call node build.js
3
- if %errorlevel% neq 0 (
4
- echo Build failed with error level %errorlevel%
5
- pause
6
- exit /b %errorlevel%
7
- )
@@ -1,5 +0,0 @@
1
- rem LittleJS Build Script
2
- call node build.js
3
-
4
- @echo off
5
- if %ERRORLEVEL% neq 0 ( pause )
@@ -1,31 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- const PROGRAM_NAME = 'game';
4
- const BUILD_FOLDER = 'build';
5
-
6
- // Define TypeScript source files
7
- const tsSourceFiles = [
8
- 'game.ts',
9
- // add your TypeScript files here
10
- ];
11
-
12
- // Corresponding JS output files
13
- const jsSourceFiles = tsSourceFiles.map(file => file.replace('.ts', '.js'));
14
-
15
- console.log(`Building TypeScript for ${PROGRAM_NAME}...`);
16
- const startTime = Date.now();
17
- const fs = require('node:fs');
18
- const child_process = require('node:child_process');
19
-
20
- console.log(`Removing old build folder...`);
21
- fs.rmSync(BUILD_FOLDER, { recursive: true, force: true });
22
-
23
- console.log(`Compiling TypeScript...`);
24
- // Compile all TypeScript files at once
25
- const tsFiles = tsSourceFiles.join(' ');
26
- child_process.execSync(`npx tsc ${tsFiles} --outDir './${BUILD_FOLDER}' --target es2020 --module es2020`, {stdio: 'inherit'});
27
- console.log(`TypeScript built in ${((Date.now() - startTime)/1e3).toFixed(2)} seconds!`);
28
-
29
- console.log(`Moving js files back to root...`);
30
- for (const file of jsSourceFiles)
31
- fs.copyFileSync(`${BUILD_FOLDER}/${file}`, file);