@newkrok/nape-js 3.30.3 → 3.31.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.
package/dist/index.d.cts CHANGED
@@ -1539,6 +1539,20 @@ interface CharacterControllerOptions {
1539
1539
  * @default null
1540
1540
  */
1541
1541
  filter?: InteractionFilter | null;
1542
+ /**
1543
+ * World-space "down" direction used for ground / wall raycasts.
1544
+ *
1545
+ * Default `Vec2(0, 1)` matches a standard top-down-Y platformer (gravity
1546
+ * points along +Y). Override for radial-gravity / planet-platformer
1547
+ * scenarios — set `cc.down` each frame to the unit vector pointing from
1548
+ * the character toward whatever you treat as "down" (e.g. the nearest
1549
+ * planet's centre). Walls are detected perpendicular to this direction.
1550
+ *
1551
+ * The vector is normalized internally; magnitude is ignored.
1552
+ *
1553
+ * @default Vec2(0, 1)
1554
+ */
1555
+ down?: Vec2;
1542
1556
  }
1543
1557
  /**
1544
1558
  * Velocity-based character controller for 2D platformers.
@@ -1585,6 +1599,8 @@ declare class CharacterController {
1585
1599
  private _maxSlopeAngle;
1586
1600
  private _maxSlopeCos;
1587
1601
  private _filter;
1602
+ private _downX;
1603
+ private _downY;
1588
1604
  private _oneWayListener;
1589
1605
  private _grounded;
1590
1606
  private _groundNormal;
@@ -1601,6 +1617,16 @@ declare class CharacterController {
1601
1617
  get timeSinceGrounded(): number;
1602
1618
  get maxSlopeAngle(): number;
1603
1619
  set maxSlopeAngle(v: number);
1620
+ /**
1621
+ * Current world-space "down" direction used for ground / wall raycasts.
1622
+ * Returns a fresh `Vec2` each call; mutate via {@link setDown} or by
1623
+ * assigning a new `Vec2` to this property.
1624
+ */
1625
+ get down(): Vec2;
1626
+ set down(value: Vec2);
1627
+ /** Update the down direction from raw components (normalized internally). */
1628
+ setDown(x: number, y: number): void;
1629
+ private _setDown;
1604
1630
  /**
1605
1631
  * Set the character body's velocity. Call this each frame **before**
1606
1632
  * `space.step()`.
@@ -1860,6 +1886,319 @@ interface FractureResult {
1860
1886
  */
1861
1887
  declare function fractureBody(body: Body, impactPoint: Vec2, options?: FractureOptions): FractureResult;
1862
1888
 
1889
+ /** A 2D row-major grid of tile values. `grid[y][x]` is the cell at row `y`, column `x`. */
1890
+ type TilemapGrid = ArrayLike<ArrayLike<number>>;
1891
+ /** Predicate deciding whether a tile value at `(x, y)` represents a solid (collidable) cell. */
1892
+ type TilemapSolidPredicate = (value: number, x: number, y: number) => boolean;
1893
+ /**
1894
+ * Strategy for combining adjacent solid tiles into fewer rectangles.
1895
+ *
1896
+ * - `"none"` — every solid tile becomes its own 1x1 rectangle
1897
+ * - `"rows"` — horizontally-adjacent solid tiles within a row are merged
1898
+ * - `"greedy"` — runs are extended both horizontally and vertically using a
1899
+ * greedy meshing pass (default — produces the fewest rectangles)
1900
+ */
1901
+ type TilemapMergeMode = "none" | "rows" | "greedy";
1902
+ /** Tile width and height in pixels. */
1903
+ interface TilemapTileSize {
1904
+ /** Tile width in pixels. */
1905
+ w: number;
1906
+ /** Tile height in pixels. */
1907
+ h: number;
1908
+ }
1909
+ /** Configuration options for {@link buildTilemapBody} / {@link meshTilemap}. */
1910
+ interface TilemapOptions {
1911
+ /** Tile size in pixels — either a square size or `{ w, h }` for non-square tiles. */
1912
+ tileSize: number | TilemapTileSize;
1913
+ /** Body position (top-left corner of the map in world space). Default `(0, 0)`. */
1914
+ position?: Vec2;
1915
+ /**
1916
+ * Predicate deciding which cells are solid. Default treats any non-zero
1917
+ * value as solid.
1918
+ */
1919
+ solid?: TilemapSolidPredicate;
1920
+ /** Merge strategy — defaults to `"greedy"`. */
1921
+ merge?: TilemapMergeMode;
1922
+ /** Material applied to every generated shape. */
1923
+ material?: Material;
1924
+ /** InteractionFilter applied to every generated shape. */
1925
+ filter?: InteractionFilter;
1926
+ /** CbTypes added to every generated shape. */
1927
+ cbTypes?: CbType[];
1928
+ /** Body type — defaults to `BodyType.STATIC`. Ignored when `body` is provided. */
1929
+ bodyType?: BodyType;
1930
+ /**
1931
+ * Append shapes to this existing body instead of creating a new one. Useful
1932
+ * for chunked maps where many tilemap layers share one body, or when adding
1933
+ * a collision mesh to a body that already exists.
1934
+ */
1935
+ body?: Body;
1936
+ }
1937
+ /** A rectangle in tile coordinates produced by {@link meshTilemap}. */
1938
+ interface TilemapRect {
1939
+ /** Tile column of the rectangle's left edge. */
1940
+ x: number;
1941
+ /** Tile row of the rectangle's top edge. */
1942
+ y: number;
1943
+ /** Width in tiles (>= 1). */
1944
+ w: number;
1945
+ /** Height in tiles (>= 1). */
1946
+ h: number;
1947
+ }
1948
+ /** Subset of a Tiled JSON tile layer needed for grid extraction. */
1949
+ interface TiledTileLayer {
1950
+ /** Flat row-major array of tile GIDs. */
1951
+ data: ArrayLike<number>;
1952
+ /** Width of the layer in tiles. */
1953
+ width: number;
1954
+ /** Height of the layer in tiles. */
1955
+ height: number;
1956
+ }
1957
+ /** Subset of an LDtk IntGrid layer instance needed for grid extraction. */
1958
+ interface LDtkIntGridLayer {
1959
+ /** Row-major flat array of int values (0 = empty). */
1960
+ intGridCsv: ArrayLike<number>;
1961
+ /** Cell-grid width (LDtk's `__cWid`, falls back to `cWid`). */
1962
+ __cWid?: number;
1963
+ /** Cell-grid height (LDtk's `__cHei`, falls back to `cHei`). */
1964
+ __cHei?: number;
1965
+ /** Alternate width key. */
1966
+ cWid?: number;
1967
+ /** Alternate height key. */
1968
+ cHei?: number;
1969
+ }
1970
+ /**
1971
+ * Convert a 2D grid of tile values into the minimal set of axis-aligned
1972
+ * rectangles that cover the solid cells, using the requested merge strategy.
1973
+ *
1974
+ * The result is geometry-only — no `Body` or `Shape` is created — which makes
1975
+ * this function reusable for debug overlays, rendering, or custom body
1976
+ * construction. {@link buildTilemapBody} is a thin wrapper that converts the
1977
+ * rectangles to `Polygon` shapes.
1978
+ *
1979
+ * Greedy meshing reduces shape count dramatically for typical platformer
1980
+ * maps. A 50-tile floor strip becomes one rectangle; a solid 10x10 block
1981
+ * becomes one rectangle instead of 100. Fewer shapes = smaller broadphase
1982
+ * footprint, faster narrowphase, less debug-draw work.
1983
+ *
1984
+ * @param grid - 2D row-major tile grid (`grid[y][x]`).
1985
+ * @param options - Optional `solid` predicate and `merge` strategy.
1986
+ * @returns The list of merged rectangles in tile coordinates.
1987
+ *
1988
+ * @example
1989
+ * ```ts
1990
+ * const rects = meshTilemap([
1991
+ * [1, 1, 1, 0, 1],
1992
+ * [1, 1, 1, 0, 1],
1993
+ * [0, 0, 0, 0, 1],
1994
+ * ]);
1995
+ * // -> [{x:0,y:0,w:3,h:2}, {x:4,y:0,w:1,h:3}]
1996
+ * ```
1997
+ */
1998
+ declare function meshTilemap(grid: TilemapGrid, options?: {
1999
+ solid?: TilemapSolidPredicate;
2000
+ merge?: TilemapMergeMode;
2001
+ }): TilemapRect[];
2002
+ /**
2003
+ * Build a single physics `Body` from a 2D tile grid.
2004
+ *
2005
+ * Each merged rectangle becomes a `Polygon` shape on the body. Tiles are laid
2006
+ * out with `(0, 0)` at the top-left of tile `(0, 0)`, so the body's
2007
+ * `position` (defaults to origin) is the world-space location of that
2008
+ * top-left corner.
2009
+ *
2010
+ * Defaults to `BodyType.STATIC` and `merge: "greedy"`, matching the most
2011
+ * common gamedev use case (level collision geometry from a Tiled / LDtk map).
2012
+ *
2013
+ * @param grid - 2D row-major tile grid.
2014
+ * @param options - Tile size + body / shape options.
2015
+ * @returns A `Body` containing one `Polygon` shape per merged rectangle.
2016
+ * The returned body is not yet attached to a `Space` — set `body.space`
2017
+ * to insert it.
2018
+ *
2019
+ * @example
2020
+ * ```ts
2021
+ * const grid = [
2022
+ * [1, 1, 1, 0, 1, 1, 1],
2023
+ * [0, 0, 0, 0, 0, 0, 0],
2024
+ * [1, 1, 1, 1, 1, 1, 1],
2025
+ * ];
2026
+ * const body = buildTilemapBody(grid, { tileSize: 32, position: Vec2.get(0, 100) });
2027
+ * body.space = space;
2028
+ * ```
2029
+ */
2030
+ declare function buildTilemapBody(grid: TilemapGrid, options: TilemapOptions): Body;
2031
+ /**
2032
+ * Convert a Tiled JSON tile layer into a 2D row-major grid suitable for
2033
+ * {@link meshTilemap} / {@link buildTilemapBody}.
2034
+ *
2035
+ * Only the `data`, `width`, and `height` fields of the layer are read — the
2036
+ * helper has no runtime dependency on a Tiled SDK and accepts any object with
2037
+ * that shape.
2038
+ *
2039
+ * @param layer - A Tiled tile layer (e.g. `map.layers[i]` from a Tiled JSON export).
2040
+ * @returns A 2D number array, with `0` representing empty tiles.
2041
+ */
2042
+ declare function tiledLayerToGrid(layer: TiledTileLayer): number[][];
2043
+ /**
2044
+ * Convert an LDtk IntGrid layer instance into a 2D row-major grid.
2045
+ *
2046
+ * Reads `intGridCsv` plus the cell-dimension fields (`__cWid` / `__cHei`,
2047
+ * with `cWid` / `cHei` accepted as fallbacks). LDtk uses `0` for empty
2048
+ * IntGrid cells, which the default `solid` predicate already treats as
2049
+ * non-solid.
2050
+ *
2051
+ * @param layer - An LDtk IntGrid layer instance.
2052
+ * @returns A 2D number array, with `0` representing empty cells.
2053
+ */
2054
+ declare function ldtkLayerToGrid(layer: LDtkIntGridLayer): number[][];
2055
+
2056
+ /**
2057
+ * Falloff law for {@link RadialGravityField}.
2058
+ *
2059
+ * - `"inverse-square"` — `F = strength / d²` (Newtonian gravity, default)
2060
+ * - `"inverse"` — `F = strength / d` (line-source gravity)
2061
+ * - `"constant"` — `F = strength` (constant pull regardless of distance)
2062
+ * - `(distance) => number` — custom multiplier, applied as `F = strength * fn(d)`
2063
+ */
2064
+ type GravityFalloff = "inverse-square" | "inverse" | "constant" | ((distance: number) => number);
2065
+ /** Per-body filter — `false` skips the body. */
2066
+ type BodyFilter = (body: Body) => boolean;
2067
+ /** Configuration options for {@link RadialGravityField}. */
2068
+ interface RadialGravityFieldOptions {
2069
+ /**
2070
+ * The field's anchor point. May be a `Vec2` (fixed world position — captured
2071
+ * by reference, so mutating it after construction moves the field), or a
2072
+ * `Body` (the field tracks `body.position` automatically each step).
2073
+ */
2074
+ source: Vec2 | Body;
2075
+ /** Field strength scaling — units depend on `falloff` (see {@link GravityFalloff}). */
2076
+ strength: number;
2077
+ /** Falloff law. @default `"inverse-square"` */
2078
+ falloff?: GravityFalloff;
2079
+ /** Multiply the resulting force by `body.mass` (Newtonian gravity). @default `true` */
2080
+ scaleByMass?: boolean;
2081
+ /**
2082
+ * Bodies farther than this from the source receive zero force — useful for
2083
+ * bounded gravity wells with hard edges.
2084
+ * @default `Infinity`
2085
+ */
2086
+ maxRadius?: number;
2087
+ /**
2088
+ * Distance values used in the falloff calculation are clamped to be at
2089
+ * least this — prevents singularities at the source center.
2090
+ * @default `1`
2091
+ */
2092
+ minRadius?: number;
2093
+ /**
2094
+ * Softening epsilon added to `d²` for the inverse-square falloff (smooths
2095
+ * out near-source spikes without disabling the pull). Has no effect on
2096
+ * other falloff laws.
2097
+ * @default `0`
2098
+ */
2099
+ softening?: number;
2100
+ /**
2101
+ * Predicate deciding which bodies the field affects. `null` (default)
2102
+ * means "all dynamic bodies". Static and kinematic bodies are always
2103
+ * skipped (forces have no effect on them anyway).
2104
+ * @default `null`
2105
+ */
2106
+ bodyFilter?: BodyFilter | null;
2107
+ /** When `false`, calls to {@link RadialGravityField.apply} are no-ops. @default `true` */
2108
+ enabled?: boolean;
2109
+ }
2110
+ /**
2111
+ * A point-source gravity field — pulls bodies toward an anchor with a chosen
2112
+ * falloff law.
2113
+ *
2114
+ * Replaces the manual `for (body of space.bodies) body.force = ...` loops
2115
+ * commonly written for orbital / planet / multi-body gravity scenarios.
2116
+ * Multiple fields compose naturally via {@link RadialGravityFieldGroup} or
2117
+ * by calling `apply()` on each one in sequence — each call **adds** to the
2118
+ * existing accumulated force, so userland `body.force` writes are preserved.
2119
+ *
2120
+ * @example
2121
+ * ```ts
2122
+ * // Mario-Galaxy-style planet pulling everything toward its center
2123
+ * const planet = new Body(BodyType.STATIC, new Vec2(400, 300));
2124
+ * planet.shapes.add(new Circle(40));
2125
+ * planet.space = space;
2126
+ *
2127
+ * const field = new RadialGravityField({
2128
+ * source: planet,
2129
+ * strength: 800000,
2130
+ * maxRadius: 250,
2131
+ * softening: 100,
2132
+ * });
2133
+ *
2134
+ * // Each frame, BEFORE space.step():
2135
+ * field.apply(space);
2136
+ * space.step(1 / 60);
2137
+ * ```
2138
+ */
2139
+ declare class RadialGravityField {
2140
+ source: Vec2 | Body;
2141
+ strength: number;
2142
+ falloff: GravityFalloff;
2143
+ scaleByMass: boolean;
2144
+ maxRadius: number;
2145
+ minRadius: number;
2146
+ softening: number;
2147
+ bodyFilter: BodyFilter | null;
2148
+ enabled: boolean;
2149
+ constructor(options: RadialGravityFieldOptions);
2150
+ /**
2151
+ * Current world-space center of the field.
2152
+ *
2153
+ * Returns the anchor's `(x, y)` — for a `Body` source this reflects the
2154
+ * body's current position each call, so the field automatically tracks
2155
+ * a moving anchor.
2156
+ */
2157
+ getPosition(): {
2158
+ x: number;
2159
+ y: number;
2160
+ };
2161
+ /**
2162
+ * Compute (but do not apply) the force this field would exert on `body`
2163
+ * given its current position. Returns `(0, 0)` when the field is disabled,
2164
+ * the body is static, the body is filtered out, or the body is outside
2165
+ * `maxRadius`.
2166
+ *
2167
+ * The returned `Vec2` is fresh and owned by the caller.
2168
+ */
2169
+ forceOn(body: Body): Vec2;
2170
+ /**
2171
+ * Add this field's force contribution to every eligible body in `space`.
2172
+ *
2173
+ * Adds to (does not replace) each body's existing accumulated force, so
2174
+ * multiple fields and userland force writes all stack naturally. Call
2175
+ * once per frame, before `space.step()`.
2176
+ */
2177
+ apply(space: Space): void;
2178
+ }
2179
+ /**
2180
+ * A composable collection of {@link RadialGravityField} instances. Calling
2181
+ * `apply()` runs every member field once — convenient for multi-source
2182
+ * scenarios (binary stars, three-body, planet platformers).
2183
+ */
2184
+ declare class RadialGravityFieldGroup {
2185
+ /** Ordered list of fields. Mutate via {@link add} / {@link remove}. */
2186
+ readonly fields: RadialGravityField[];
2187
+ /** Add a field to the group and return it. */
2188
+ add(field: RadialGravityField): RadialGravityField;
2189
+ /** Remove a field from the group. Returns `true` if it was present. */
2190
+ remove(field: RadialGravityField): boolean;
2191
+ /** Remove all fields. */
2192
+ clear(): void;
2193
+ /** Number of fields currently in the group. */
2194
+ get length(): number;
2195
+ /**
2196
+ * Apply every field's force contribution to all eligible bodies in `space`.
2197
+ * Forces stack additively, preserving any userland `body.force` writes.
2198
+ */
2199
+ apply(space: Space): void;
2200
+ }
2201
+
1863
2202
  declare const VERSION: string;
1864
2203
 
1865
- export { AABB, AngleJoint, Arbiter, Body, BodyCallback, BodyListener, BodyType, Callback, Capsule, CbEvent, CbType, CharacterController, type CharacterControllerOptions, Circle, CollisionArbiter, type ConcaveBodyOptions, Constraint, ConstraintCallback, ConstraintListener, Contact, DebugDrawFlags, DistanceJoint, type FractureOptions, type FractureResult, Geom, GeomPoly, InteractionCallback, InteractionFilter, InteractionListener, InteractionType, Interactor, LineJoint, Listener, MarchingSquares, MatMN, Material, MotorJoint, type MoveResult, OptionType, PivotJoint, PreCallback, PreFlag, PreListener, PulleyJoint, Shape, ShapeType, Space, SpringJoint, type TriggerHandler, TriggerZone, type TriggerZoneOptions, UserConstraint, VERSION, ValidationResult, Vec2, Vec3, type VoronoiCell, type VoronoiPoint, type VoronoiResult, WeldJoint, Winding, computeVoronoi, createConcaveBody, fractureBody, generateFractureSites };
2204
+ export { AABB, AngleJoint, Arbiter, Body, BodyCallback, type BodyFilter, BodyListener, BodyType, Callback, Capsule, CbEvent, CbType, CharacterController, type CharacterControllerOptions, Circle, CollisionArbiter, type ConcaveBodyOptions, Constraint, ConstraintCallback, ConstraintListener, Contact, DebugDrawFlags, DistanceJoint, type FractureOptions, type FractureResult, Geom, GeomPoly, type GravityFalloff, InteractionCallback, InteractionFilter, InteractionListener, InteractionType, Interactor, type LDtkIntGridLayer, LineJoint, Listener, MarchingSquares, MatMN, Material, MotorJoint, type MoveResult, OptionType, PivotJoint, PreCallback, PreFlag, PreListener, PulleyJoint, RadialGravityField, RadialGravityFieldGroup, type RadialGravityFieldOptions, Shape, ShapeType, Space, SpringJoint, type TiledTileLayer, type TilemapGrid, type TilemapMergeMode, type TilemapOptions, type TilemapRect, type TilemapSolidPredicate, type TilemapTileSize, type TriggerHandler, TriggerZone, type TriggerZoneOptions, UserConstraint, VERSION, ValidationResult, Vec2, Vec3, type VoronoiCell, type VoronoiPoint, type VoronoiResult, WeldJoint, Winding, buildTilemapBody, computeVoronoi, createConcaveBody, fractureBody, generateFractureSites, ldtkLayerToGrid, meshTilemap, tiledLayerToGrid };