@zardoy/flying-squid 0.0.132 → 0.0.134

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.
@@ -33,16 +33,15 @@ const server = function (serv) {
33
33
  // entity.friction = new Vec3(0.6, 0.6, 0.6)
34
34
  // entity.terminalvelocity = new Vec3(27, 27, 27)
35
35
  // }
36
- if (!entity.velocity || !entity.size)
36
+ // every half second (spread over the ticks by id) the clients get the absolute position of moving mobs and objects: clients that predict movement themselves drift (see sendAbsolute)
37
+ if (entity.type !== 'player' && entity.velocity && (serv.tickCount + entity.id) % 10 === 0 && (!entity.onGround || entity.velocity.norm() > 0.01))
38
+ entity.sendAbsolute();
39
+ if (!entity.velocity || !entity.size || entity.customMotion)
37
40
  return;
38
41
  const { position, onGround } = await entity.calculatePhysics(delta);
39
- if (entity.type === 'mob' ||
40
- entity.type === 'player' ||
41
- (entity.type === 'object' &&
42
- (entity.velocity.x !== 0 ||
43
- entity.velocity.y !== 0 ||
44
- entity.velocity.z !== 0)))
45
- entity.sendPosition(position, onGround);
42
+ // sendPosition does nothing when neither the position nor onGround changed; an object that just landed has no velocity left but still has to be moved
43
+ if (entity.type === 'mob' || entity.type === 'player' || entity.type === 'object')
44
+ await entity.sendPosition(position, onGround);
46
45
  }))
47
46
  .then(() => { ticking = false; })
48
47
  .catch((err) => setTimeout(() => { throw err; }, 0));
@@ -2,6 +2,7 @@
2
2
  module.exports = {
3
3
  builtinPlugins: {
4
4
  'animations': require('./animations'),
5
+ 'bed': require('./bed'),
5
6
  'behavior': require('./behavior'),
6
7
  'blockUpdates': require('./blockUpdates'),
7
8
  'blocks': require('./blocks'),
@@ -22,6 +23,7 @@ module.exports = {
22
23
  'digging': require('./digging'),
23
24
  'dimensionCodec': require('./dimensionCodec'),
24
25
  'effects': require('./effects'),
26
+ 'endFight': require('./endFight'),
25
27
  'entities': require('./entities'),
26
28
  'errorHandler': require('./errorHandler'),
27
29
  'experience': require('./experience'),
@@ -37,6 +39,7 @@ module.exports = {
37
39
  'log': require('./log'),
38
40
  'logout': require('./logout'),
39
41
  'maps': require('./maps'),
42
+ 'mobs': require('./mobs'),
40
43
  'moderation': require('./moderation'),
41
44
  'particle': require('./particle'),
42
45
  'physics': require('./physics'),
@@ -45,6 +48,7 @@ module.exports = {
45
48
  'players': require('./players'),
46
49
  'pluginsFolder': require('./pluginsFolder'),
47
50
  'portal': require('./portal'),
51
+ 'projectiles': require('./projectiles'),
48
52
  'pvp': require('./pvp'),
49
53
  'recipes': require('./recipes'),
50
54
  'redstone': require('./redstone'),
@@ -57,6 +61,7 @@ module.exports = {
57
61
  'smelting': require('./smelting'),
58
62
  'sound': require('./sound'),
59
63
  'spawn': require('./spawn'),
64
+ 'spawners': require('./spawners'),
60
65
  'stats': require('./stats'),
61
66
  'tabComplete': require('./tabComplete'),
62
67
  'tick': require('./tick'),
@@ -0,0 +1,86 @@
1
+ import { Vec3 } from 'vec3';
2
+ /**
3
+ * Mobs with a small AI: they walk (or fly) at the nearest player and hurt it, wander when nothing is around, take damage, die and drop things.
4
+ * Everything is simplified on purpose: straight line movement with jumping over one block steps (no path finding), no line of sight, no spawning rules
5
+ * (mobs come from spawners, `/summon` and spawn eggs), no persistence.
6
+ *
7
+ * - `serv.mobDefs` behaviour table by mob name
8
+ * - `serv.entityTypeId` entity type id of a name for this version (`ender_pearl`, `blaze`, ...)
9
+ * - `serv.dropItem` drops an item entity
10
+ * - `serv.hurt` damage with armour, i-frames and knockback for players and mobs
11
+ * - `serv.explode` explosion: damage, knockback and (optionally) broken blocks
12
+ * - `serv.projectiles` see projectiles.ts
13
+ */
14
+ export type MobAi = 'melee' | 'creeper' | 'skeleton' | 'blaze' | 'wander' | 'neutral' | 'dragon' | 'none';
15
+ export interface MobDef {
16
+ health: number;
17
+ ai: MobAi;
18
+ /** blocks per second */
19
+ speed?: number;
20
+ /** half hearts */
21
+ damage?: number;
22
+ /** blocks a player is noticed from */
23
+ aggro?: number;
24
+ flies?: boolean;
25
+ xp?: number;
26
+ /** [item, min, max, chance 0..1] */
27
+ drops?: Array<[string, number, number, number?]>;
28
+ /** [width, height] when minecraft-data has none */
29
+ size?: [number, number];
30
+ }
31
+ export declare const defOf: (name: string | undefined) => MobDef | undefined;
32
+ /** armour points (half chestplates) of the armour a player wears: the sum over the four armour slots, 5..8 of the inventory window */
33
+ export declare function armorPoints(player: Player): number;
34
+ /** half hearts of damage a player deals with the item in hand */
35
+ export declare function weaponDamage(name: string | undefined): number;
36
+ export declare const server: (serv: Server, options: Options) => void;
37
+ /** mob side: damage, death, knockback bookkeeping */
38
+ export declare const entity: (entity: Entity, serv: Server) => void;
39
+ declare global {
40
+ interface Entity {
41
+ ai?: {
42
+ kind: MobAi;
43
+ def: MobDef;
44
+ state: Record<string, any>;
45
+ };
46
+ dead?: boolean;
47
+ maxHealth?: number;
48
+ lastHurt?: number;
49
+ lastHurtDamage?: number;
50
+ stunUntil?: number;
51
+ hitWall?: boolean;
52
+ yawDeg?: number;
53
+ sentYaw?: number;
54
+ /** not removed when far from every player */
55
+ persistent?: boolean;
56
+ deathAnimationMs?: number;
57
+ /** called instead of the default removal when a non-player entity runs out of health */
58
+ die: (killer?: Entity) => void;
59
+ }
60
+ interface Server {
61
+ mobDefs: Record<string, MobDef>;
62
+ entityTypeId: (names: string | string[], kind?: 'object' | 'mob') => number | undefined;
63
+ dropItem: (world: any, position: Vec3, name: string, count?: number, velocity?: Vec3) => Entity | undefined;
64
+ hurt: (target: Entity, damage: number, opts?: {
65
+ source?: Entity;
66
+ from?: Vec3;
67
+ knockback?: number;
68
+ maxDamage?: number;
69
+ }) => boolean;
70
+ explode: (world: any, pos: Vec3, power: number, opts?: {
71
+ breakBlocks?: boolean;
72
+ source?: Entity;
73
+ maxDamage?: number;
74
+ fire?: boolean;
75
+ }) => Promise<void>;
76
+ killMob: (mob: Entity, killer?: Entity) => void;
77
+ faceTowards: (mob: Entity, dx: number, dz: number, force?: boolean) => void;
78
+ projectiles?: {
79
+ shootArrow: (shooter: Entity, at: Vec3, opts?: {
80
+ damage?: number;
81
+ speed?: number;
82
+ }) => void;
83
+ shootFireball: (shooter: Entity, at: Vec3) => void;
84
+ };
85
+ }
86
+ }
@@ -0,0 +1,456 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.entity = exports.server = exports.defOf = void 0;
4
+ exports.armorPoints = armorPoints;
5
+ exports.weaponDamage = weaponDamage;
6
+ const vec3_1 = require("vec3");
7
+ const MOB_DEFS = {
8
+ zombie: { health: 20, ai: 'melee', speed: 3.2, damage: 3, aggro: 35, xp: 5, drops: [['rotten_flesh', 0, 2], ['iron_ingot', 1, 1, 0.025], ['carrot', 1, 1, 0.025], ['potato', 1, 1, 0.025]] },
9
+ husk: { health: 20, ai: 'melee', speed: 3.2, damage: 3, aggro: 35, xp: 5, drops: [['rotten_flesh', 0, 2]] },
10
+ drowned: { health: 20, ai: 'melee', speed: 3.2, damage: 3, aggro: 35, xp: 5, drops: [['rotten_flesh', 0, 2]] },
11
+ zombie_villager: { health: 20, ai: 'melee', speed: 3.2, damage: 3, aggro: 35, xp: 5, drops: [['rotten_flesh', 0, 2]] },
12
+ zombified_piglin: { health: 20, ai: 'neutral', speed: 4.5, damage: 5, aggro: 20, xp: 5, drops: [['rotten_flesh', 0, 1], ['gold_nugget', 0, 1], ['gold_ingot', 1, 1, 0.025]] },
13
+ zombie_pigman: { health: 20, ai: 'neutral', speed: 4.5, damage: 5, aggro: 20, xp: 5, drops: [['rotten_flesh', 0, 1], ['gold_nugget', 0, 1]] },
14
+ skeleton: { health: 20, ai: 'skeleton', speed: 3.2, damage: 3, aggro: 16, xp: 5, drops: [['bone', 0, 2], ['arrow', 0, 2]] },
15
+ stray: { health: 20, ai: 'skeleton', speed: 3.2, damage: 3, aggro: 16, xp: 5, drops: [['bone', 0, 2], ['arrow', 0, 2]] },
16
+ wither_skeleton: { health: 20, ai: 'melee', speed: 3.4, damage: 5, aggro: 16, xp: 5, drops: [['bone', 0, 2], ['coal', 0, 1, 0.33], ['wither_skeleton_skull', 1, 1, 0.025]], size: [0.7, 2.4] },
17
+ spider: { health: 16, ai: 'melee', speed: 5.0, damage: 2, aggro: 16, xp: 5, drops: [['string', 0, 2], ['spider_eye', 1, 1, 0.33]] },
18
+ cave_spider: { health: 12, ai: 'melee', speed: 5.0, damage: 2, aggro: 16, xp: 5, drops: [['string', 0, 2], ['spider_eye', 1, 1, 0.33]] },
19
+ silverfish: { health: 8, ai: 'melee', speed: 4.5, damage: 1, aggro: 12, xp: 5 },
20
+ creeper: { health: 20, ai: 'creeper', speed: 3.4, damage: 0, aggro: 16, xp: 5, drops: [['gunpowder', 0, 2]] },
21
+ enderman: { health: 40, ai: 'neutral', speed: 6, damage: 7, aggro: 64, xp: 5, drops: [['ender_pearl', 0, 1]] },
22
+ blaze: { health: 20, ai: 'blaze', speed: 3.5, damage: 5, aggro: 48, flies: true, xp: 10, drops: [['blaze_rod', 0, 1]] },
23
+ ghast: { health: 10, ai: 'none', flies: true, xp: 5, drops: [['ghast_tear', 0, 1], ['gunpowder', 0, 2]] },
24
+ magma_cube: { health: 16, ai: 'melee', speed: 3, damage: 4, aggro: 16, xp: 4, drops: [['magma_cream', 0, 1, 0.25]] },
25
+ slime: { health: 16, ai: 'melee', speed: 3, damage: 2, aggro: 16, xp: 4, drops: [['slime_ball', 0, 2]] },
26
+ witch: { health: 26, ai: 'melee', speed: 3.2, damage: 3, aggro: 16, xp: 5, drops: [['glass_bottle', 0, 2], ['redstone', 0, 2], ['stick', 0, 2], ['sugar', 0, 2]] },
27
+ piglin: { health: 16, ai: 'neutral', speed: 4.5, damage: 5, aggro: 16, xp: 5, drops: [['gold_ingot', 0, 1, 0.1]] },
28
+ piglin_brute: { health: 50, ai: 'melee', speed: 4.5, damage: 7, aggro: 24, xp: 20, drops: [['gold_ingot', 0, 1, 0.1]] },
29
+ hoglin: { health: 40, ai: 'melee', speed: 5, damage: 6, aggro: 16, xp: 5, drops: [['porkchop', 2, 4], ['leather', 0, 1]] },
30
+ cow: { health: 10, ai: 'wander', speed: 1.5, xp: 2, drops: [['leather', 0, 2], ['beef', 1, 3]] },
31
+ mooshroom: { health: 10, ai: 'wander', speed: 1.5, xp: 2, drops: [['leather', 0, 2], ['beef', 1, 3]] },
32
+ pig: { health: 10, ai: 'wander', speed: 1.5, xp: 2, drops: [['porkchop', 1, 3]] },
33
+ sheep: { health: 8, ai: 'wander', speed: 1.5, xp: 2, drops: [['white_wool', 1, 1], ['mutton', 1, 2]] },
34
+ chicken: { health: 4, ai: 'wander', speed: 1.5, xp: 2, drops: [['feather', 0, 2], ['chicken', 1, 1]] },
35
+ rabbit: { health: 3, ai: 'wander', speed: 3, xp: 2, drops: [['rabbit_hide', 0, 1], ['rabbit', 0, 1]] },
36
+ horse: { health: 22, ai: 'wander', speed: 2, xp: 2, drops: [['leather', 0, 2]] },
37
+ villager: { health: 20, ai: 'wander', speed: 1.2, xp: 0 },
38
+ wolf: { health: 8, ai: 'neutral', speed: 4.5, damage: 4, aggro: 8, xp: 2 },
39
+ ender_dragon: { health: 200, ai: 'dragon', flies: true, xp: 0, size: [16, 8] },
40
+ end_crystal: { health: 1, ai: 'none', xp: 0 }
41
+ };
42
+ /** names of older versions (1.8: `PigZombie`, `CaveSpider`, `EnderDragon`, ...) */
43
+ const norm = (name) => name.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
44
+ const ALIASES = { pigzombie: 'zombie_pigman', pig_zombie: 'zombie_pigman', ender_crystal: 'end_crystal', endercrystal: 'end_crystal', lavaslime: 'magma_cube', mushroom_cow: 'mooshroom', villager_golem: 'iron_golem' };
45
+ const defOf = (name) => {
46
+ if (!name)
47
+ return undefined;
48
+ const n = norm(name);
49
+ return MOB_DEFS[ALIASES[n] ?? n];
50
+ };
51
+ exports.defOf = defOf;
52
+ const ARMOR_POINTS = { leather: [1, 3, 2, 1], golden: [2, 5, 3, 1], gold: [2, 5, 3, 1], chainmail: [2, 5, 4, 1], iron: [2, 6, 5, 2], diamond: [3, 8, 6, 3], netherite: [3, 8, 6, 3], turtle: [2, 0, 0, 0] };
53
+ const ARMOR_PARTS = ['helmet', 'chestplate', 'leggings', 'boots'];
54
+ /** armour points (half chestplates) of the armour a player wears: the sum over the four armour slots, 5..8 of the inventory window */
55
+ function armorPoints(player) {
56
+ let total = 0;
57
+ for (let slot = 5; slot <= 8; slot++) {
58
+ const name = player.inventory?.slots[slot]?.name;
59
+ const m = name && /^(.*)_(helmet|chestplate|leggings|boots)$/.exec(name);
60
+ if (m)
61
+ total += ARMOR_POINTS[m[1]]?.[ARMOR_PARTS.indexOf(m[2])] ?? 0;
62
+ }
63
+ return total;
64
+ }
65
+ /** half hearts of damage a player deals with the item in hand */
66
+ function weaponDamage(name) {
67
+ if (!name)
68
+ return 1;
69
+ const m = /^(wooden|stone|golden|gold|iron|diamond|netherite)_(sword|axe|pickaxe|shovel|hoe)$/.exec(name);
70
+ if (m) {
71
+ const tier = { wooden: 0, golden: 0, gold: 0, stone: 1, iron: 2, diamond: 3, netherite: 4 }[m[1]];
72
+ switch (m[2]) {
73
+ case 'sword': return 4 + tier;
74
+ case 'axe': return [7, 9, 9, 9, 10][tier];
75
+ case 'pickaxe': return 2 + tier;
76
+ case 'shovel': return 2.5 + tier;
77
+ default: return 1;
78
+ }
79
+ }
80
+ if (name === 'trident')
81
+ return 9;
82
+ return 1;
83
+ }
84
+ const rand = (min, max) => min + Math.floor(Math.random() * (max - min + 1));
85
+ const server = function (serv, options) {
86
+ const mcData = serv.mcData;
87
+ const flat = serv.supportFeature('theFlattening');
88
+ serv.mobDefs = MOB_DEFS;
89
+ /** entity type id of the first name that exists in this version (`kind`: `object` / `mob` for 1.12 and older, where one name can exist twice) */
90
+ serv.entityTypeId = (names, kind) => {
91
+ for (const name of Array.isArray(names) ? names : [names]) {
92
+ const want = norm(name.replace(/^minecraft:/, ''));
93
+ for (const e of (mcData.entitiesArray ?? Object.values(mcData.entities))) {
94
+ if (norm(e.name) !== want && norm(e.name) !== want.replace(/_/g, ''))
95
+ continue;
96
+ if (kind && flat === false && e.type !== kind)
97
+ continue;
98
+ return e.id;
99
+ }
100
+ }
101
+ return undefined;
102
+ };
103
+ serv.dropItem = (world, position, name, count = 1, velocity) => {
104
+ const item = mcData.itemsByName[name] ?? mcData.blocksByName[name];
105
+ const entity = serv.entityTypeId(['item'], 'object');
106
+ if (!item || entity === undefined || count <= 0)
107
+ return undefined;
108
+ return serv.spawnObject(entity, world, position.clone(), {
109
+ velocity: velocity ?? new vec3_1.Vec3((Math.random() - 0.5) * 3, 4 + Math.random() * 2, (Math.random() - 0.5) * 3),
110
+ itemId: item.id,
111
+ itemCount: count,
112
+ pickupTime: 500,
113
+ deathTime: 5 * 60 * 1000
114
+ });
115
+ };
116
+ // ---------------------------------------------------------------- damage
117
+ /** hurts a player or mob: armour, 0.5 s of damage immunity, knockback away from `from`. Returns false when nothing happened. */
118
+ serv.hurt = (target, damage, { source, from, knockback = 6, maxDamage = Infinity } = {}) => {
119
+ if (!target || target.invincible || target.dead)
120
+ return false;
121
+ const now = Date.now();
122
+ if (target.lastHurt && now - target.lastHurt < 500 && damage <= (target.lastHurtDamage ?? 0))
123
+ return false;
124
+ if (target.type === 'player') {
125
+ const p = target;
126
+ if (p.gameMode === 1 || p.gameMode === 3 || !p.health || p.health <= 0)
127
+ return false;
128
+ damage *= 1 - Math.min(20, armorPoints(p)) / 25;
129
+ }
130
+ damage = Math.min(damage, maxDamage);
131
+ target.lastHurt = now;
132
+ target.lastHurtDamage = damage;
133
+ const dir = from ? target.position.minus(from) : new vec3_1.Vec3(0, 0, 0);
134
+ dir.y = 0;
135
+ const len = dir.norm();
136
+ const velocity = len > 0.01 ? new vec3_1.Vec3(dir.x / len * knockback, 5, dir.z / len * knockback) : new vec3_1.Vec3(0, 3, 0);
137
+ target.takeDamage({ damage, velocity, maxVelocity: new vec3_1.Vec3(12, 12, 12), animation: target.type === 'player', source });
138
+ if (target.type !== 'player' && target.health > 0)
139
+ target._writeOthersNearby('entity_status', { entityId: target.id, entityStatus: 2 });
140
+ return true;
141
+ };
142
+ // ---------------------------------------------------------------- explosions
143
+ serv.explode = async (world, pos, power, { breakBlocks = true, source, maxDamage = Infinity, fire = false } = {}) => {
144
+ serv._writeNearby('explosion', { x: pos.x, y: pos.y, z: pos.z, radius: power, affectedBlockRecords: [], playerMotionX: 0, playerMotionY: 0, playerMotionZ: 0 }, { world, position: pos });
145
+ const reach = power * 2;
146
+ for (const e of Object.values(serv.entities)) {
147
+ if (!e.ready || e.world !== world || e === source)
148
+ continue;
149
+ if (e.type !== 'player' && e.type !== 'mob')
150
+ continue;
151
+ const centre = e.position.offset(0, (e.size?.y ?? 1.8) / 2, 0);
152
+ const dist = centre.distanceTo(pos);
153
+ if (dist > reach)
154
+ continue;
155
+ const impact = 1 - dist / reach;
156
+ const damage = Math.floor((impact * impact + impact) / 2 * 7 * reach + 1);
157
+ serv.hurt(e, damage, { source, from: pos, knockback: 10 * impact + 2, maxDamage });
158
+ }
159
+ if (!breakBlocks)
160
+ return;
161
+ const r = Math.ceil(power);
162
+ for (let dx = -r; dx <= r; dx++) {
163
+ for (let dy = -r; dy <= r; dy++) {
164
+ for (let dz = -r; dz <= r; dz++) {
165
+ if (dx * dx + dy * dy + dz * dz > power * power)
166
+ continue;
167
+ const p = new vec3_1.Vec3(Math.floor(pos.x) + dx, Math.floor(pos.y) + dy, Math.floor(pos.z) + dz);
168
+ const block = await world.getBlock(p);
169
+ if (!block || block.type === 0 || ['bedrock', 'obsidian', 'end_portal', 'end_portal_frame', 'barrier', 'command_block', 'water', 'lava', 'end_gateway', 'crying_obsidian', 'reinforced_deepslate'].includes(block.name))
170
+ continue;
171
+ await serv.setBlockType(world, p, 0);
172
+ }
173
+ }
174
+ }
175
+ };
176
+ // ---------------------------------------------------------------- spawning: sizes, health, ai
177
+ const applyDef = (mob) => {
178
+ const def = (0, exports.defOf)(mob.name);
179
+ if (!def)
180
+ return;
181
+ const info = mcData.entitiesArray?.find(e => e.id === mob.entityType);
182
+ const w = info?.width ?? def.size?.[0] ?? 0.6;
183
+ const h = info?.height ?? def.size?.[1] ?? 1.8;
184
+ mob.size = new vec3_1.Vec3(w, h, w);
185
+ mob.health = def.health;
186
+ mob.maxHealth = def.health;
187
+ mob.friction = new vec3_1.Vec3(15, 0, 15);
188
+ if (def.flies) {
189
+ mob.noGravity = true;
190
+ mob.isFlyer = true;
191
+ }
192
+ if (def.ai !== 'none')
193
+ mob.ai = { kind: def.ai, def, state: {} };
194
+ };
195
+ serv.once('asap', () => {
196
+ const spawnMob = serv.spawnMob;
197
+ serv.spawnMob = (...args) => {
198
+ const mob = spawnMob(...args);
199
+ applyDef(mob);
200
+ mob.yawDeg = mob.yaw ?? 0;
201
+ serv.emit('mobSpawned', mob);
202
+ return mob;
203
+ };
204
+ });
205
+ const toByte = (deg) => { let b = Math.floor(((deg % 360) + 360) % 360 * 256 / 360); if (b > 127)
206
+ b -= 256; return b; };
207
+ /** turns a mob towards (dx, dz); the rotation packets are only sent when it changed noticeably */
208
+ const face = (mob, dx, dz, force = false) => {
209
+ if (Math.abs(dx) < 1e-3 && Math.abs(dz) < 1e-3)
210
+ return;
211
+ const yaw = Math.atan2(-dx, dz) * 180 / Math.PI;
212
+ const last = mob.sentYaw;
213
+ if (!force && last !== undefined && Math.abs(((yaw - last + 540) % 360) - 180) < 8)
214
+ return;
215
+ mob.sentYaw = yaw;
216
+ mob.yawDeg = yaw;
217
+ mob.yaw = yaw;
218
+ mob._writeOthersNearby('entity_look', { entityId: mob.id, yaw: toByte(yaw), pitch: 0, onGround: !!mob.onGround });
219
+ mob._writeOthersNearby('entity_head_rotation', { entityId: mob.id, headYaw: toByte(yaw) });
220
+ };
221
+ serv.faceTowards = face;
222
+ // ---------------------------------------------------------------- death
223
+ const startDeath = (mob, killer) => {
224
+ if (mob.dead)
225
+ return;
226
+ mob.dead = true;
227
+ mob.ai = undefined;
228
+ mob.velocity = new vec3_1.Vec3(0, 0, 0);
229
+ mob._writeOthersNearby('entity_status', { entityId: mob.id, entityStatus: 3 });
230
+ const def = (0, exports.defOf)(mob.name);
231
+ const lootingless = killer?.type === 'player';
232
+ if (def?.drops && (lootingless || !killer)) {
233
+ for (const [item, min, max, chance] of def.drops) {
234
+ if (chance !== undefined && Math.random() > chance)
235
+ continue;
236
+ serv.dropItem(mob.world, mob.position.offset(0, 0.5, 0), item, rand(min, max));
237
+ }
238
+ }
239
+ if (def?.xp && killer?.type === 'player') {
240
+ const p = killer;
241
+ p.setXp(p.xp + def.xp);
242
+ }
243
+ serv.emit('mobDied', mob, killer);
244
+ mob.setTimeout(() => { if (serv.entities[mob.id])
245
+ mob.destroy(); }, mob.deathAnimationMs ?? 900);
246
+ };
247
+ serv.killMob = startDeath;
248
+ // ---------------------------------------------------------------- ai
249
+ const targetsOf = (mob, range) => serv.players.filter(p => p.world === mob.world && (p.gameMode === 0 || p.gameMode === 2) && p.health > 0 && p.position.distanceTo(mob.position) <= range);
250
+ const nearest = (mob, range) => {
251
+ let best;
252
+ let bestD = Infinity;
253
+ for (const p of targetsOf(mob, range)) {
254
+ const d = p.position.distanceTo(mob.position);
255
+ if (d < bestD) {
256
+ best = p;
257
+ bestD = d;
258
+ }
259
+ }
260
+ return best;
261
+ };
262
+ const move = (mob, dx, dz, speed) => {
263
+ const len = Math.hypot(dx, dz);
264
+ if (len < 1e-3 || speed === 0) {
265
+ mob.velocity.x = 0;
266
+ mob.velocity.z = 0;
267
+ return;
268
+ }
269
+ mob.velocity.x = dx / len * speed;
270
+ mob.velocity.z = dz / len * speed;
271
+ face(mob, dx, dz);
272
+ // a block in the way: hop over it (one block steps), swim up in water
273
+ if (mob.onGround && mob.hitWall)
274
+ mob.velocity.y = 7.6;
275
+ if ((mob.inWater || mob.inLava) && !mob.isFlyer)
276
+ mob.velocity.y = Math.max(mob.velocity.y, 3);
277
+ };
278
+ const wander = (mob, speed, now) => {
279
+ const s = mob.ai.state;
280
+ if (!s.until || now > s.until) {
281
+ s.until = now + 2000 + Math.random() * 4000;
282
+ const a = Math.random() * Math.PI * 2;
283
+ s.dx = Math.random() < 0.4 ? 0 : Math.cos(a);
284
+ s.dz = Math.random() < 0.4 ? 0 : Math.sin(a);
285
+ }
286
+ move(mob, s.dx, s.dz, speed * 0.5);
287
+ };
288
+ const strike = (mob, target, damage, now, cooldown = 1000) => {
289
+ if (now - (mob.ai.state.lastHit ?? 0) < cooldown)
290
+ return;
291
+ mob.ai.state.lastHit = now;
292
+ mob._writeOthersNearby('animation', { entityId: mob.id, animation: 0 });
293
+ serv.hurt(target, damage, { source: mob, from: mob.position });
294
+ };
295
+ const tickMob = (mob, now) => {
296
+ const ai = mob.ai;
297
+ const def = ai.def;
298
+ const speed = def.speed ?? 3;
299
+ const provoked = ai.state.angryUntil > now ? serv.entities[ai.state.angryAt] : undefined;
300
+ switch (ai.kind) {
301
+ case 'melee':
302
+ case 'neutral': {
303
+ const target = ai.kind === 'neutral' ? provoked : nearest(mob, def.aggro ?? 16);
304
+ if (!target || target.world !== mob.world) {
305
+ if (ai.kind === 'neutral')
306
+ wander(mob, speed, now);
307
+ else
308
+ wander(mob, speed * 0.6, now);
309
+ return;
310
+ }
311
+ const dx = target.position.x - mob.position.x;
312
+ const dz = target.position.z - mob.position.z;
313
+ const dist = Math.hypot(dx, dz);
314
+ const reach = (mob.size.x / 2) + 0.6 + 0.3;
315
+ move(mob, dx, dz, dist > reach * 0.8 ? speed : 0);
316
+ face(mob, dx, dz);
317
+ if (dist < reach + 0.4 && Math.abs(target.position.y - mob.position.y) < 1.8)
318
+ strike(mob, target, def.damage ?? 2, now);
319
+ return;
320
+ }
321
+ case 'creeper': {
322
+ const target = nearest(mob, def.aggro ?? 16);
323
+ const s = ai.state;
324
+ if (!target) {
325
+ s.fuse = undefined;
326
+ wander(mob, speed * 0.6, now);
327
+ return;
328
+ }
329
+ const dx = target.position.x - mob.position.x;
330
+ const dz = target.position.z - mob.position.z;
331
+ const dist = Math.hypot(dx, dz);
332
+ face(mob, dx, dz);
333
+ if (dist < 3 && Math.abs(target.position.y - mob.position.y) < 2) {
334
+ s.fuse ??= now;
335
+ move(mob, 0, 0, 0);
336
+ if (now - s.fuse >= 1500) {
337
+ const world = mob.world;
338
+ const pos = mob.position.offset(0, 0.5, 0);
339
+ mob.dead = true;
340
+ mob.ai = undefined;
341
+ mob.destroy();
342
+ void serv.explode(world, pos, 3, { source: mob, breakBlocks: serv.gamerules?.mobGriefing !== false });
343
+ }
344
+ }
345
+ else {
346
+ s.fuse = undefined;
347
+ move(mob, dx, dz, speed);
348
+ }
349
+ return;
350
+ }
351
+ case 'skeleton': {
352
+ const target = nearest(mob, def.aggro ?? 16);
353
+ if (!target) {
354
+ wander(mob, speed * 0.6, now);
355
+ return;
356
+ }
357
+ const dx = target.position.x - mob.position.x;
358
+ const dz = target.position.z - mob.position.z;
359
+ const dist = Math.hypot(dx, dz);
360
+ face(mob, dx, dz);
361
+ if (dist > 10)
362
+ move(mob, dx, dz, speed);
363
+ else if (dist < 5)
364
+ move(mob, -dx, -dz, speed);
365
+ else
366
+ move(mob, 0, 0, 0);
367
+ if (now - (ai.state.lastShot ?? 0) > 2000 && dist < 14) {
368
+ ai.state.lastShot = now;
369
+ serv.projectiles?.shootArrow(mob, target.position.offset(0, 1.2, 0), { damage: 3 });
370
+ }
371
+ return;
372
+ }
373
+ case 'blaze': {
374
+ const target = nearest(mob, def.aggro ?? 48);
375
+ const s = ai.state;
376
+ if (!target) {
377
+ mob.velocity.set(0, Math.sin(now / 700) * 0.6, 0);
378
+ return;
379
+ }
380
+ const dx = target.position.x - mob.position.x;
381
+ const dz = target.position.z - mob.position.z;
382
+ const dist = Math.hypot(dx, dz);
383
+ face(mob, dx, dz);
384
+ // hover 2-5 blocks above the player's feet, drift sideways while shooting, come closer when far away
385
+ const wantY = target.position.y + 2.5 + Math.sin(now / 900 + mob.id) * 1.5;
386
+ const vy = Math.max(-3.5, Math.min(3.5, (wantY - mob.position.y) * 2.5));
387
+ const side = Math.sin(now / 1500 + mob.id * 3) * 1.5;
388
+ const ux = dist > 0.01 ? dx / dist : 0;
389
+ const uz = dist > 0.01 ? dz / dist : 0;
390
+ const approach = dist > 14 ? speed : dist < 6 ? -speed * 0.7 : 0;
391
+ mob.velocity.set(ux * approach - uz * side, vy, uz * approach + ux * side);
392
+ if (mob.hitWall && vy < 1)
393
+ mob.velocity.y = 3;
394
+ // three fireballs in a row, then a pause (Blaze: 3 shots, 100 ticks cooldown)
395
+ if (dist < 20) {
396
+ s.burst ??= 0;
397
+ const gap = s.burst > 0 ? 300 : 3000;
398
+ if (now - (s.lastShot ?? 0) > gap) {
399
+ s.lastShot = now;
400
+ s.burst = s.burst >= 2 ? 0 : s.burst + 1;
401
+ serv.projectiles?.shootFireball(mob, target.position.offset(0, 0.9, 0));
402
+ }
403
+ }
404
+ return;
405
+ }
406
+ case 'wander': {
407
+ if (ai.state.fleeUntil > now) {
408
+ const a = serv.entities[ai.state.angryAt];
409
+ if (a) {
410
+ move(mob, mob.position.x - a.position.x, mob.position.z - a.position.z, speed * 2.2);
411
+ return;
412
+ }
413
+ }
414
+ wander(mob, speed, now);
415
+ return;
416
+ }
417
+ default:
418
+ }
419
+ };
420
+ let tickN = 0;
421
+ serv.on('tick', () => {
422
+ const now = Date.now();
423
+ tickN++;
424
+ for (const mob of Object.values(serv.entities)) {
425
+ if (!mob.ai || !mob.ready || mob.dead || mob.type !== 'mob')
426
+ continue;
427
+ if (mob.ai.kind === 'dragon')
428
+ continue;
429
+ if (mob.stunUntil && now < mob.stunUntil)
430
+ continue;
431
+ try {
432
+ tickMob(mob, now);
433
+ }
434
+ catch (e) {
435
+ serv.warn?.('mob ai: ' + e.stack);
436
+ }
437
+ }
438
+ // mobs far away from every player disappear (their chunks are not simulated)
439
+ if (tickN % 100 === 0) {
440
+ for (const mob of Object.values(serv.entities)) {
441
+ if (!mob.ai || mob.type !== 'mob' || mob.ai.kind === 'dragon' || mob.persistent)
442
+ continue;
443
+ if (!serv.players.some(p => p.world === mob.world && p.position.distanceTo(mob.position) < 128))
444
+ mob.destroy();
445
+ }
446
+ }
447
+ });
448
+ serv.on('mobDied', () => { });
449
+ };
450
+ exports.server = server;
451
+ /** mob side: damage, death, knockback bookkeeping */
452
+ const entity = function (entity, serv) {
453
+ entity.die = (killer) => { serv.killMob(entity, killer); };
454
+ entity.hitWall = false;
455
+ };
456
+ exports.entity = entity;
@@ -5,7 +5,13 @@ declare global {
5
5
  interface Entity {
6
6
  /** Gravity of entity (non-players) to calculate physics. */
7
7
  gravity: Vec3;
8
- /** Decreases velocity when touching blocks */
8
+ /** Deceleration (blocks/s^2) of the horizontal velocity while standing on something */
9
9
  friction: Vec3;
10
+ /** Flying entities (blaze, dragon) ignore liquids; with `noGravity` they stay in the air */
11
+ isFlyer?: boolean;
12
+ /** No gravity (flying mobs, projectiles that fly straight) */
13
+ noGravity?: boolean;
14
+ inWater?: boolean;
15
+ inLava?: boolean;
10
16
  }
11
17
  }