@adatechnology/game-contracts

中文文档
0.25.0发布于 2026/11/06MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 1.1万

The contracts every game module depends on, and nothing else: destruction (parts, hits, events, DestructibleImpl), weapons (shots), fluids (containers, item uses), item animations and the TestableModule a module hands the test room. Types plus tiny checke

原始使用文档
文档目录13 节
  1. Install
  2. What is in it
  3. Destruction: a module owns its object
  4. Weapons
  5. Animations
  6. A module for the test room
  7. A bench for the module
  8. Effects the host lends
  9. Sound and weather the host lends
  10. API
  11. Ignition of a leak
  12. Categories (kinds with inheritance)
  13. Português

@adatechnology/game-contracts

The contracts every game module depends on, and nothing else. Types plus a few tiny pure checkers, no runtime dependencies, MIT.

The idea: a vehicle, a chair, a pistol or a house is a module. It does not need the default destruction world, a renderer or the test room. It only needs to agree on a few shapes, and these are they. The destruction package, the weapons package, the fluids package and the test room all depend on this one and re-export what they used to define, so import { Hit } from '@adatechnology/game-destruction' keeps working.

your module ──▶ game-contracts ◀── game-destruction / game-weapons / game-fluids / game-test-room

Install

pnpm add @adatechnology/game-contracts

Browser without a bundler (the global is GameContracts):

<script src="https://unpkg.com/@adatechnology/game-contracts/dist/index.global.js"></script>
<script>
  const problems = GameContracts.checkHit({ type: 'blunt', point: [0, 1, 0] })
</script>

What is in it

ContractExportsUsed for
DestructionDestructibleSpec, PartSpec, Hit, DestructionEvent, ObjectState, PartState, JointSpec...the vocabulary of parts, joints, hits, events and state
ImpactIMPACT_CONTRACT, checkHit(hit)the fields a weapon or hazard must put in a Hit, per damage type
Own destructionDestructibleImpl, checkDestructible(impl, { materials })a module that owns its destruction (a car with its own panel rule)
WeaponsShot, Use, shotToHit(shot, point, normal?), shotExtras(shot, distance?)what a weapon produces, and the Hit a shot makes at a point
FluidsContainerSpec, LiquidId, ItemUseDefwhat an item says about the liquid it holds and how it is used
AnimationAnimationClipSpec, ItemAnimationContract, checkAnimation(clip, partIds)use animations an item brings (a door open, a pistol reload)
ModuleTestableModule, TestableItem, ModuleScenariowhat a module hands the test room

Destruction: a module owns its object

import type { DestructibleImpl } from '@adatechnology/game-contracts'
import { checkDestructible } from '@adatechnology/game-contracts'

const impl: DestructibleImpl = {
  id: 'rental_car_1',
  describe: () => ({ parts: [/* body, door_l, wheel_fl... in the impl's local space */] }),
  hit: (hit) => [/* events: every one has object === id and names a part listed by describe() */],
  state: () => ({ /* ObjectState */ }),
}

checkDestructible(impl, { materials: world.materials.keys() }) // { ok, problems }

Hits arrive in world space and events go out in world space. checkDestructible needs no world: it validates describe(), hits the impl with a 500 J ballistic hit, and checks that state() matches describe(), hit points never go negative, update(0.016) returns an array and every event is well-formed and JSON-serializable. The contracts package does not know your materials: pass their ids (the world's world.materials.keys()) or leave materials out to skip that check.

Cost contract (D8): the host reads describe() and state() per part per frame, so both are O(1), allocation-free and cached between changes (the same object comes back until a hit, tool, fire or pose change). checkDestructible(impl, { cost: true }) (or cost: { reads, ceilingMs, allocationBytes }) reads each 10 000 times and fails on a new object per read, on time over the ceiling (default 50 ms) and, in Node, on heap growth over the ceiling (default 1 MiB).

Weapons

const hit = shotToHit(shot, point) // { type: 'ballistic', energy: shot.energyAt(distance), caliber, direction, ... }
checkHit(hit)                       // [] when valid

Animations

A clip is plain data: keys with poses (offsets from the rest pose, Euler XYZ) for the item root and for named parts, plus events. checkAnimation(clip, partIds) verifies a snake_case id, a positive duration, ordered times inside the clip, finite vectors, that every moved part is one of partIds, and well-formed events.

const open: AnimationClipSpec = {
  id: 'open',
  duration: 1.2,
  keys: [{ t: 0 }, { t: 1.2, parts: { door_l: { rotation: [0, 1.1, 0] } } }],
  events: [{ t: 0.15, type: 'sound', data: { key: 'door_latch' } }],
}
checkAnimation(open, ['body', 'door_l']) // { ok: true, problems: [] }

A module for the test room

import type { TestableModule } from '@adatechnology/game-contracts'

export const RENTAL_CARS: TestableModule = {
  id: 'rental_cars',
  name: 'Rental cars',
  group: 'Rental cars',
  items: (locale) => [{ id: 'rental_car', name: 'Rental car', build: (THREE) => buildCar(THREE), impl: (root, id) => createCarImpl(root, id), animations: [open] }],
  scenarios: (locale) => [/* { id, name, run(ctx) } */],
}

room.loadModule(RENTAL_CARS) // items join the catalogue, scenarios become buttons, contract checks write ✓ / ✗ lines to the log

build receives the host's three.js namespace and returns its Object3D (both are unknown here: this package has no dependency on three.js). impl receives the object id the host gives the item and DestructibleImpl.id must equal it.

A bench for the module

A module can also declare a bench as data: controls (number, boolean, choice, action), layers (things the viewer turns on or off) and metrics (counters the host pulls with read() a few times a second). The host keeps the values, draws them, and lends the module a ModuleBench in attach (host.bench): value(id), layer(id), onChange(listener) (right after attach it gets one change per control and layer, in order), patch(id, { hidden, disabled, options, value }) (no echo) and look(eye, target). checkBench({ controls, layers, metrics }) checks the declaration (snake_case ids unique across the three, min < max, step > 0, defaults in range and among the options, max > 0). A choice's options may carry a group (the host lists them under that heading; the options of a group sit next to each other, and checkBench says so when they do not). ModuleBench.sheet(sheet) puts a card on the host's panel (BenchSheet: kicker, title, body, facts, steps, colour swatches, note and a timeline of segments whose playhead follows a module metric); a host with no sheet area leaves it out.

Effects the host lends

ModuleHost.effects is an EffectSink: play({ effect, point, direction?, normal?, seed?, param?, scale? }) starts an effect of the host's catalogue by id and answers a handle (or null when the host does not know it), stop(handle) ends a looping one, and configure, stats and catalog are optional. The explosion host event carries explosive (the id of the explosive), PartSpec.explodes.effect and the explode event name the effect of a part's blast.

controls: () => [
  { kind: 'choice', id: 'distance', name: 'Distance', options: [{ id: 'near', name: 'Near' }, { id: 'far', name: 'Far' }], default: 'near' },
  { kind: 'action', id: 'replay', name: 'Replay' },
],
layers: () => [{ id: 'smoke', name: 'Smoke' }],
metrics: () => [{ id: 'particles', name: 'Particles', max: 400, read: () => fx.particles }],

Tool events are named after a tool's cycle, not a firearm: mode, fault, clear (start / end) and safety, and shot carries rounds (cartridges spent) next to shots (projectiles, always 1 or more) and the mode; a dud round is its own misfire event, not a shot of zero. HostTool may report mode, fault, safety and heat (0..1). host.configureTool(settings) takes a Record<string, string> keyed by the id of the module's own control; the test room applies condition and ammo_quality and ignores other ids. host.player() returns the PlayerState (position, yaw, pitch, crouching, speed in m/s, running, cameraMode); a { type: 'player' } event tells when crouching or the camera mode changes.

Sound and weather the host lends

ModuleHost.audio? is an AudioSink (play(SoundRequest), stop(handle), and optionally loop, setListener, register): one shared sound engine, so every module is mixed, limited and panned the same way. ModuleHost.environment? is an EnvironmentBus (get, set(patch), on) holding an EnvironmentState (rain mm/h, wind, fogFar, visibility, nightFactor, temperatureC, wetness): the weather module writes it, the others read it. Both are optional, additive and generic; createEnvironmentBus(initial?) is a plain store that implements the bus, and DEFAULT_ENVIRONMENT is the calm dry day.

API

Everything is exported from the package root; see src/*.ts for the doc comments. Units: metres, seconds, joules, millimetres (calibre), degrees Celsius.

Ignition of a leak

Hit.ignition ({ spark, flame }), Hit.incendiary and Hit.tracer say what a round brings to a leak of flammable fluid; IgnitionRules / DEFAULT_IGNITION_RULES are the numbers of the container side (the fillCurve, the sparkTarget of the wall, fireNear), ignitionChance(hit, { sparkTarget, fill, fluid? }, rules?) is the chance that one round that went through lights the leak, fillFactor(fill, curve?) the curve and sparkTargetFactor(materialId, isMetal, rules?) the wall. game-destruction and game-vehicles use them; a plain bullet only leaks.

Categories (kinds with inheritance)

defineCategories(defs, { extra, patches, remove }) builds a CategoryRegistry: each CategoryDef has an id, an optional extends (any depth), defaults, requires (contract ids) and abstract. defaults(id) deep-merges along the chain (root first, arrays replace), requires(id) is the deduped union, chain(id), isA(id, ancestor) and check() (unknown parent, cycle, duplicate id) complete it. resolveEntry(registry, entry) puts the category defaults under an entry (the entry wins); checkCategorized(entries, registry, checkers, { allow }) runs the ContractChecker of every required contract on the resolved entry and reports "<id>" (<kind>): <problem>, required by <category>; allow lists known gaps that go to allowed instead of problems. Items only name their kind, so a game can insert a new parent above existing types (patches: { canned_food: { extends: 'preserved' } } with preserved extending the old parent) or add a child under any type, and every item keeps resolving, now with the extra defaults and requirements, without being edited.

Português

Os contratos de que todo módulo de jogo depende, e só isso: tipos mais alguns verificadores pequenos e puros, sem dependências em tempo de execução. Um carro, uma cadeira, uma pistola ou uma casa é um módulo; ele não precisa do mundo de destruição padrão, de um renderizador nem da sala de testes, só concordar com estas formas. Os pacotes de destruição, armas, fluidos e a sala de testes dependem deste e reexportam os tipos que antes definiam, então import { Hit } from '@adatechnology/game-destruction' continua funcionando.

  • Destruição própria: DestructibleImpl (o módulo manda no seu objeto) e checkDestructible(impl, { materiais }), que valida describe(), aplica um golpe de 500 J e confere eventos e estado sem precisar de mundo.
  • Impacto: IMPACT_CONTRACT e checkHit(hit) dizem quais campos cada tipo de dano exige.
  • Armas: Shot, Use e shotToHit(shot, ponto).
  • Fluidos: ContainerSpec, LiquidId e ItemUseDef.
  • Som e clima: ModuleHost.audio? (AudioSink) e ModuleHost.environment? (EnvironmentBus com EnvironmentState), emprestados pela sala; createEnvironmentBus() e DEFAULT_ENVIRONMENT (o dia seco e calmo).
  • Animações: AnimationClipSpec e checkAnimation(clipe, idsDasPeças) (uma porta open, uma pistola reload).
  • Módulo: TestableModule entrega itens, animações e cenários à sala de testes; room.loadModule(modulo) roda as verificações e escreve linhas ✓ / ✗ no log. Assim o módulo de um carro de aluguel já nasce com as suas animações e o seu jeito de quebrar.
  • Bancada: o módulo declara controls, layers e metrics como dados; a sala guarda os valores, desenha e empresta host.bench (ModuleBench). checkBench valida a declaração. Eventos de ciclo da ferramenta: mode, fault, clear, safety, e rounds no shot.

版本与发布记录

@adatechnology/game-contracts 共发布 27 个版本,首次发布于 2026/10/23;过去 12 个月发布了 27 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.25.0latest2026/11/06今天
0.24.02026/11/041 天前
0.23.02026/11/042 天前
0.22.02026/11/042 天前
0.21.02026/11/032 天前
0.20.02026/11/015 天前

关于 @adatechnology/game-contracts 的常见问题

@adatechnology/game-contracts 是什么?

The contracts every game module depends on, and nothing else: destruction (parts, hits, events, DestructibleImpl), weapons (shots), fluids (containers, item uses), item animations and the TestableModule a module hands the test room. Types plus tiny checke

如何安装 @adatechnology/game-contracts?

在项目目录运行 npm install @adatechnology/game-contracts,或使用 pnpm add / yarn add / bun add。

@adatechnology/game-contracts 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@adatechnology/game-contracts 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@adatechnology/game-contracts 可以商用吗?

@adatechnology/game-contracts 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@adatechnology/game-contracts 的下载量有多少?

根据 npm 官方下载统计,@adatechnology/game-contracts 在 2026/10/05 – 2026/11/03 这 30 天内被下载 10,843 次,日均约 361 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@adatechnology/game-contracts 还在维护吗?

最新版本 0.25.0 发布于 2026/11/06(今天);至今共发布 27 个版本,其中过去 12 个月发布了 27 个;首次发布于 2026/10/23。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。