@pkmn/engine 0.1.0-dev.cf6f5d2c → 0.1.0-dev.d56bdadd

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 (53) hide show
  1. package/README.md +55 -44
  2. package/build/pkg/addon.js +3 -2
  3. package/build/pkg/addon.js.map +1 -1
  4. package/build/pkg/data/ids.json +12 -12
  5. package/build/pkg/data/layout.json +27 -5
  6. package/build/pkg/data/protocol.json +69 -12
  7. package/build/pkg/data.d.ts +2 -2
  8. package/build/pkg/gen1.d.ts +2 -1
  9. package/build/pkg/gen1.js +38 -20
  10. package/build/pkg/gen1.js.map +1 -1
  11. package/build/pkg/index.d.ts +4 -2
  12. package/build/pkg/index.js.map +1 -1
  13. package/build/pkg/protocol.d.ts +4 -2
  14. package/build/pkg/protocol.js +60 -39
  15. package/build/pkg/protocol.js.map +1 -1
  16. package/build/test/display.js +7 -3
  17. package/build/test/display.js.map +1 -1
  18. package/build.zig +103 -73
  19. package/package.json +41 -20
  20. package/src/bin/install-pkmn-engine +10 -5
  21. package/src/lib/binding/node.zig +46 -141
  22. package/src/lib/binding/wasm.zig +4 -2
  23. package/src/lib/common/battle.zig +17 -0
  24. package/src/lib/common/data.zig +19 -31
  25. package/src/lib/common/debug.zig +20 -11
  26. package/src/lib/common/js.zig +118 -0
  27. package/src/lib/common/optional.zig +67 -0
  28. package/src/lib/common/options.zig +9 -0
  29. package/src/lib/common/protocol.zig +770 -208
  30. package/src/lib/common/rational.zig +353 -0
  31. package/src/lib/common/rng.zig +24 -15
  32. package/src/lib/common/util.zig +12 -0
  33. package/src/lib/gen1/README.md +269 -179
  34. package/src/lib/gen1/calc.zig +426 -0
  35. package/src/lib/gen1/chance.zig +1060 -0
  36. package/src/lib/gen1/data/moves.zig +202 -190
  37. package/src/lib/gen1/data/species.zig +4 -4
  38. package/src/lib/gen1/data/types.zig +10 -10
  39. package/src/lib/gen1/data.zig +85 -71
  40. package/src/lib/gen1/helpers.zig +577 -35
  41. package/src/lib/gen1/mechanics.zig +874 -608
  42. package/src/lib/gen2/README.md +105 -85
  43. package/src/lib/gen2/calc.zig +143 -0
  44. package/src/lib/gen2/chance.zig +1314 -0
  45. package/src/lib/gen2/data/items.zig +14 -20
  46. package/src/lib/gen2/data/moves.zig +664 -570
  47. package/src/lib/gen2/data/species.zig +2 -2
  48. package/src/lib/gen2/data/types.zig +137 -34
  49. package/src/lib/gen2/data.zig +124 -86
  50. package/src/lib/gen2/generated.zig +808 -0
  51. package/src/lib/gen2/helpers.zig +16 -22
  52. package/src/lib/gen2/mechanics.zig +3490 -12
  53. package/src/lib/pkmn.zig +61 -2
@@ -0,0 +1,353 @@
1
+ const builtin = @import("builtin");
2
+ const std = @import("std");
3
+
4
+ const assert = std.debug.assert;
5
+ const expect = std.testing.expect;
6
+ const expectEqual = std.testing.expectEqual;
7
+ const expectError = std.testing.expectError;
8
+
9
+ /// Specialization of a rational number used by the engine to compute probabilties.
10
+ /// For performance reasons the rational is only reduced lazily and thus `reduce` must be
11
+ /// invoked explicitly before reading.
12
+ pub fn Rational(comptime T: type) type {
13
+ return extern struct {
14
+ const Self = @This();
15
+
16
+ /// Numerator. Must always be >= 1. Not guaranteed to be reduced in all cases.
17
+ p: T = 1,
18
+ /// Denominator. Must always be >= 1. Not guaranteed to be reduced in all cases.
19
+ q: T = 1,
20
+
21
+ // With floats we can't rely on an overflow bit to let us know when to reduce, so we instead
22
+ // start reducing when we get sufficiently close to the limit of the mantissa (in our domain
23
+ // we expect updates to involve numbers < 2**10, so we should be safe not reducing before we
24
+ // are 2**10 away from "overflowing" the mantissa)
25
+ const REDUCE = if (@typeInfo(T) == .Float)
26
+ std.math.pow(T, 2, std.math.floatMantissaBits(T) - 10)
27
+ else
28
+ 0;
29
+
30
+ /// Possible error returned by operations on the Rational.
31
+ pub const Error = switch (@typeInfo(T)) {
32
+ .Int => error{Overflow},
33
+ .Float => error{},
34
+ else => unreachable,
35
+ };
36
+
37
+ /// Resets the rational back to 1.
38
+ pub fn reset(r: *Self) void {
39
+ r.p = 1;
40
+ r.q = 1;
41
+ }
42
+
43
+ /// Update the rational by multiplying its numerator by p and its denominator by q.
44
+ /// Both p and q must be >= 1, and if computable at comptime must have no common factors.
45
+ pub fn update(r: *Self, p: anytype, q: anytype) Error!void {
46
+ // FIXME
47
+ // std.debug.print("({d}/{d}) * ", .{ p, q });
48
+ assert(p >= 1);
49
+ assert(q >= 1);
50
+
51
+ // If our parameters are not fully reduced they may prematurely
52
+ // cause overflow/loss of precision after the multiplication below
53
+ assert(switch (@typeInfo(@TypeOf(p, q))) {
54
+ .ComptimeInt, .ComptimeFloat => comptime gcd(p, q),
55
+ else => 1,
56
+ } == 1);
57
+
58
+ switch (@typeInfo(T)) {
59
+ .Int => {
60
+ // Greedily attempt to multiply and if it fails, reduce and try again
61
+ r.multiplication(p, q) catch |err| switch (err) {
62
+ error.Overflow => {
63
+ r.reduce();
64
+ try r.multiplication(p, q);
65
+ },
66
+ else => unreachable,
67
+ };
68
+ },
69
+ .Float => {
70
+ // Reduce in situations where we're likely to start losing precision
71
+ if (r.q > REDUCE or r.p > REDUCE) r.reduce();
72
+
73
+ r.p *= switch (@typeInfo(@TypeOf(p))) {
74
+ .Float, .ComptimeFloat => p,
75
+ else => @floatFromInt(p),
76
+ };
77
+ r.q *= switch (@typeInfo(@TypeOf(q))) {
78
+ .Float, .ComptimeFloat => q,
79
+ else => @floatFromInt(q),
80
+ };
81
+
82
+ // We should always be dealing with whole numbers
83
+ assert(std.math.modf(r.p).fpart == 0);
84
+ assert(std.math.modf(r.q).fpart == 0);
85
+ },
86
+ else => unreachable,
87
+ }
88
+ }
89
+
90
+ /// Add two rationals using the identity (a/b) + (c/d) = (ad+bc)/(bd).
91
+ pub fn add(r: *Self, s: *Self) Error!void {
92
+ switch (@typeInfo(T)) {
93
+ .Int => {
94
+ if (r.q == s.q) {
95
+ r.p = std.math.add(T, r.p, s.p) catch |err| switch (err) {
96
+ error.Overflow => val: {
97
+ r.reduce();
98
+ s.reduce();
99
+ break :val try std.math.add(T, r.p, s.p);
100
+ },
101
+ else => unreachable,
102
+ };
103
+ } else {
104
+ r.addition(s.p, s.q) catch |err| switch (err) {
105
+ error.Overflow => {
106
+ r.reduce();
107
+ s.reduce();
108
+ try r.addition(s.p, s.q);
109
+ },
110
+ else => unreachable,
111
+ };
112
+ }
113
+ },
114
+ .Float => {
115
+ if (r.q == s.q) {
116
+ if (r.p > REDUCE) r.reduce();
117
+ if (s.p > REDUCE) s.reduce();
118
+
119
+ r.p += s.p;
120
+ } else {
121
+ // Always reduce to minimize loss of precision from the multiplications
122
+ r.reduce();
123
+ s.reduce();
124
+
125
+ r.p = (r.p * s.q) + (r.q * s.p);
126
+ r.q *= s.q;
127
+ }
128
+
129
+ assert(std.math.modf(r.p).fpart == 0);
130
+ assert(std.math.modf(r.q).fpart == 0);
131
+ },
132
+ else => unreachable,
133
+ }
134
+ }
135
+
136
+ /// Multiplies two rationals.
137
+ pub fn mul(r: *Self, s: *Self) Error!void {
138
+ switch (@typeInfo(T)) {
139
+ .Int => {
140
+ r.multiplication(s.p, s.q) catch |err| switch (err) {
141
+ error.Overflow => {
142
+ r.reduce();
143
+ s.reduce();
144
+ try r.multiplication(s.p, s.q);
145
+ },
146
+ else => unreachable,
147
+ };
148
+ },
149
+ .Float => {
150
+ if (r.q > REDUCE or r.p > REDUCE) r.reduce();
151
+ if (s.q > REDUCE or s.p > REDUCE) s.reduce();
152
+
153
+ r.p *= s.p;
154
+ r.q *= s.q;
155
+
156
+ assert(std.math.modf(r.p).fpart == 0);
157
+ assert(std.math.modf(r.q).fpart == 0);
158
+ },
159
+ else => unreachable,
160
+ }
161
+ }
162
+
163
+ /// Normalize the rational by reducing by the greatest common divisor.
164
+ pub fn reduce(r: *Self) void {
165
+ const d = gcd(r.p, r.q);
166
+ if (d == 1) return;
167
+
168
+ assert(@mod(r.p, d) == 0);
169
+ assert(@mod(r.q, d) == 0);
170
+
171
+ r.p /= d;
172
+ r.q /= d;
173
+
174
+ assert(r.p >= 1);
175
+ assert(r.q >= 1);
176
+ }
177
+
178
+ pub fn format(
179
+ self: Self,
180
+ comptime fmt: []const u8,
181
+ opts: std.fmt.FormatOptions,
182
+ writer: anytype,
183
+ ) !void {
184
+ _ = .{ fmt, opts };
185
+ try writer.print("{d}/{d}", .{ self.p, self.q });
186
+ }
187
+
188
+ fn multiplication(r: *Self, p: anytype, q: anytype) !void {
189
+ r.p = try std.math.mul(T, r.p, p);
190
+ r.q = try std.math.mul(T, r.q, q);
191
+ }
192
+
193
+ fn addition(r: *Self, p: anytype, q: anytype) !void {
194
+ // (a/b) + (c/d) = (ad+bc)/(bd)
195
+ var d = try std.math.mul(T, r.q, q);
196
+ var n1 = try std.math.mul(T, r.p, q);
197
+ var n2 = try std.math.mul(T, r.q, p);
198
+
199
+ r.p = try std.math.add(T, n1, n2);
200
+ r.q = d;
201
+ }
202
+ };
203
+ }
204
+
205
+ // https://en.wikipedia.org/wiki/Euclidean_algorithm
206
+ fn gcd(p: anytype, q: anytype) @TypeOf(p, q) {
207
+ assert(p >= 1);
208
+ assert(q >= 1);
209
+
210
+ var a = p;
211
+ var b = q;
212
+ var c: @TypeOf(p, q) = undefined;
213
+
214
+ while (b != 0) {
215
+ c = b;
216
+ b = @mod(a, b);
217
+ a = c;
218
+ }
219
+
220
+ assert(a > 0);
221
+ return a;
222
+ }
223
+
224
+ fn doTurn(r: anytype) !void {
225
+ try r.update(1, 163); // Metronome
226
+ try r.update(33, 256); // Critical Hit (67 Speed)
227
+ try r.update(1, 39); // Damage roll
228
+ try r.update(89, 128); // Thunder accuracy (178/256)
229
+ try r.update(77, 256); // Thunder secondary proc
230
+ }
231
+
232
+ test Rational {
233
+ inline for (.{ u64, u128, f64 }) |t| {
234
+ var r: Rational(t) = .{};
235
+
236
+ var c: t = 128;
237
+ try r.update(c, 256);
238
+ try doTurn(&r);
239
+
240
+ r.reduce();
241
+ try expectEqual(Rational(t){ .p = 75383, .q = 35550920704 }, r);
242
+
243
+ try r.update(1, 4);
244
+ if (t == u64) {
245
+ try expectError(error.Overflow, doTurn(&r));
246
+ } else {
247
+ try doTurn(&r);
248
+ r.reduce();
249
+ try expectEqual(Rational(t){ .p = 5682596689, .q = 2527735925804191711232 }, r);
250
+ }
251
+
252
+ r.reset();
253
+
254
+ var s = Rational(t){ .p = 10, .q = 13 };
255
+ try r.mul(&s);
256
+ s = Rational(t){ .p = 3, .q = 4 };
257
+ try r.mul(&s);
258
+ try expectEqual(Rational(t){ .p = 30, .q = 52 }, r);
259
+
260
+ s = Rational(t){ .p = 1, .q = 3 };
261
+ try r.add(&s);
262
+ r.reduce();
263
+ try expectEqual(Rational(t){ .p = 71, .q = 78 }, r);
264
+ }
265
+ }
266
+
267
+ /// Adapter of std.math.big.Rational to the engines Rational interface.
268
+ pub const BigRational = struct {
269
+ /// The underlying rational number.
270
+ val: std.math.big.Rational,
271
+
272
+ /// Possible error returned by operations on the rational.
273
+ pub const Error = error{OutOfMemory};
274
+
275
+ /// Create a new BigRational wrapper. A small amount of memory will be allocated on
276
+ /// initialization. Not default initialized to 1 - you must explicitly `reset` first.
277
+ pub fn init(alloc: std.mem.Allocator) !BigRational {
278
+ return .{ .val = try std.math.big.Rational.init(alloc) };
279
+ }
280
+
281
+ /// Frees all memory associated with a rational.
282
+ pub fn deinit(r: *BigRational) void {
283
+ r.val.deinit();
284
+ }
285
+
286
+ /// Resets the rational back to 1.
287
+ pub fn reset(r: *BigRational) !void {
288
+ try r.val.setInt(1);
289
+ }
290
+
291
+ /// Update the rational by multiplying its numerator by p and its denominator by q.
292
+ /// Both p and q must be >= 1.
293
+ pub fn update(r: *BigRational, p: anytype, q: anytype) !void {
294
+ assert(p >= 1);
295
+ assert(q >= 1);
296
+
297
+ var s = try std.math.big.Rational.init(r.val.p.allocator);
298
+ defer s.deinit();
299
+ try s.setRatio(p, q);
300
+ try r.val.mul(r.val, s);
301
+ }
302
+
303
+ /// Adds two rationals.
304
+ pub fn add(r: *BigRational, s: *const BigRational) !void {
305
+ try r.val.add(r.val, s.val);
306
+ }
307
+
308
+ /// Multiplies two rationals.
309
+ pub fn mul(r: *BigRational, s: *const BigRational) !void {
310
+ try r.val.mul(r.val, s.val);
311
+ }
312
+ };
313
+
314
+ test BigRational {
315
+ var r = try BigRational.init(std.testing.allocator);
316
+ defer r.deinit();
317
+ var s = try std.math.big.Rational.init(std.testing.allocator);
318
+ defer s.deinit();
319
+
320
+ try r.reset();
321
+
322
+ var c: u8 = 128;
323
+ try r.update(c, 256);
324
+ try doTurn(&r);
325
+
326
+ try s.setRatio(75383, 35550920704);
327
+ try expect((try s.order(r.val)) == .eq);
328
+
329
+ try r.update(1, 4);
330
+ try doTurn(&r);
331
+
332
+ try s.setRatio(5682596689, 2527735925804191711232);
333
+ try expect((try s.order(r.val)) == .eq);
334
+
335
+ try r.reset();
336
+
337
+ var t = try BigRational.init(std.testing.allocator);
338
+ defer t.deinit();
339
+
340
+ try t.val.setRatio(10, 13);
341
+ try r.mul(&t);
342
+ try t.val.setRatio(3, 4);
343
+ try r.mul(&t);
344
+
345
+ try s.setRatio(15, 26);
346
+ try expect((try s.order(r.val)) == .eq);
347
+
348
+ try t.val.setRatio(1, 3);
349
+ try r.add(&t);
350
+
351
+ try s.setRatio(71, 78);
352
+ try expect((try s.order(r.val)) == .eq);
353
+ }
@@ -25,6 +25,11 @@ pub fn PRNG(comptime gen: comptime_int) type {
25
25
  pub fn next(self: *Self) Output(gen) {
26
26
  return self.src.next();
27
27
  }
28
+
29
+ pub fn advance(self: *Self, n: usize) void {
30
+ if (!options.advance) return;
31
+ for (0..n) |_| self.src.advance();
32
+ }
28
33
  };
29
34
  }
30
35
 
@@ -47,7 +52,7 @@ pub const PSRNG = extern struct {
47
52
  }
48
53
 
49
54
  pub fn range(self: *PSRNG, comptime T: type, from: T, to: Bound(T)) T {
50
- return @intCast(T, @as(u64, self.src.next()) * (to - from) / divisor + from);
55
+ return @intCast(@as(u64, self.src.next()) * (to - from) / divisor + from);
51
56
  }
52
57
 
53
58
  pub fn chance(self: *PSRNG, comptime T: type, numerator: T, denominator: Bound(T)) bool {
@@ -64,7 +69,7 @@ pub const PSRNG = extern struct {
64
69
  };
65
70
 
66
71
  test PSRNG {
67
- var psrng = PSRNG{ .src = .{ .seed = 0x0001000200030004 } };
72
+ var psrng: PSRNG = .{ .src = .{ .seed = 0x0001000200030004 } };
68
73
  try expectEqual(@as(u8, 121), psrng.range(u8, 0, 256));
69
74
  try expectEqual(false, psrng.chance(u8, 128, 256)); // 226 < 128
70
75
  }
@@ -72,28 +77,32 @@ test PSRNG {
72
77
  // https://pkmn.cc/pokered/engine/battle/core.asm#L6644-L6693
73
78
  // https://pkmn.cc/pokecrystal/engine/battle/core.asm#L6922-L6938
74
79
  pub const Gen12 = extern struct {
75
- seed: [10]u8,
80
+ seed: [9]u8,
76
81
  index: u8 = 0,
77
82
 
78
83
  comptime {
79
- assert(@sizeOf(Gen12) == 11);
84
+ assert(@sizeOf(Gen12) == 10);
80
85
  }
81
86
 
82
- pub fn percent(p: u8) u8 {
83
- return @intCast(u8, (@as(u16, p) * 0xFF) / 100);
87
+ pub fn percent(comptime p: comptime_int) u8 {
88
+ return @intCast((@as(u16, p) * 0xFF) / 100);
84
89
  }
85
90
 
86
91
  pub fn next(self: *Gen12) u8 {
87
92
  const val = 5 *% self.seed[self.index] +% 1;
88
93
  self.seed[self.index] = val;
89
- self.index = (self.index + 1) % 10;
94
+ self.index = (self.index + 1) % 9;
90
95
  return val;
91
96
  }
97
+
98
+ pub fn advance(self: *Gen12) void {
99
+ _ = self.next();
100
+ }
92
101
  };
93
102
 
94
103
  test Gen12 {
95
- const expected = [_]u8{ 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 31, 56, 81 };
96
- var rng = Gen12{ .seed = .{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } };
104
+ const expected = [_]u8{ 6, 11, 16, 21, 26, 31, 36, 41, 46, 31, 56, 81 };
105
+ var rng: Gen12 = .{ .seed = .{ 1, 2, 3, 4, 5, 6, 7, 8, 9 } };
97
106
  for (expected) |e| {
98
107
  try expectEqual(e, rng.next());
99
108
  }
@@ -114,7 +123,7 @@ pub const Gen34 = extern struct {
114
123
 
115
124
  pub fn next(self: *Gen34) u16 {
116
125
  self.advance();
117
- return @intCast(u16, self.seed >> 16);
126
+ return @intCast(self.seed >> 16);
118
127
  }
119
128
 
120
129
  pub fn advance(self: *Gen34) void {
@@ -129,7 +138,7 @@ test Gen34 {
129
138
  .{ 0x80000000, 5, 0x0E425287 }, .{ 0x80000000, 10, 0x6F2CF4B2 },
130
139
  };
131
140
  for (data) |d| {
132
- var rng = Gen34{ .seed = d[0] };
141
+ var rng: Gen34 = .{ .seed = d[0] };
133
142
  for (0..d[1]) |_| _ = rng.next();
134
143
  try expectEqual(d[2], rng.seed);
135
144
  }
@@ -144,7 +153,7 @@ pub const Gen56 = extern struct {
144
153
 
145
154
  pub fn next(self: *Gen56) u32 {
146
155
  self.advance();
147
- return @intCast(u32, self.seed >> 32);
156
+ return @intCast(self.seed >> 32);
148
157
  }
149
158
 
150
159
  pub fn advance(self: *Gen56) void {
@@ -161,7 +170,7 @@ test Gen56 {
161
170
  .{ 0x8000000000000000, 10, 0xE7795501267F125A },
162
171
  };
163
172
  for (data) |d| {
164
- var rng = Gen56{ .seed = d[0] };
173
+ var rng: Gen56 = .{ .seed = d[0] };
165
174
  for (0..d[1]) |_| _ = rng.next();
166
175
  try expectEqual(d[2], rng.seed);
167
176
  }
@@ -190,7 +199,7 @@ pub fn FixedRNG(comptime gen: comptime_int, comptime len: usize) type {
190
199
 
191
200
  pub fn range(self: *Self, comptime T: type, from: T, to: Bound(T)) T {
192
201
  assert(showdown);
193
- return @intCast(T, @as(u64, self.next()) * (to - from) / divisor + from);
202
+ return @intCast(@as(u64, self.next()) * (to - from) / divisor + from);
194
203
  }
195
204
 
196
205
  pub fn chance(
@@ -213,7 +222,7 @@ pub fn FixedRNG(comptime gen: comptime_int, comptime len: usize) type {
213
222
  test FixedRNG {
214
223
  const Type = if (showdown) u32 else u8;
215
224
  const expected = [_]Type{ 42, 255, 0 };
216
- var rng = FixedRNG(1, expected.len){ .rolls = expected };
225
+ var rng: FixedRNG(1, expected.len) = .{ .rolls = expected };
217
226
  for (expected) |e| {
218
227
  try expectEqual(e, rng.next());
219
228
  }
@@ -0,0 +1,12 @@
1
+ const std = @import("std");
2
+
3
+ const expectEqual = std.testing.expectEqual;
4
+
5
+ pub fn PointerType(comptime P: type, comptime C: type) type {
6
+ return if (@typeInfo(P).Pointer.is_const) *const C else *C;
7
+ }
8
+
9
+ test PointerType {
10
+ try expectEqual(*bool, PointerType(*u8, bool));
11
+ try expectEqual(*const f64, PointerType(*const i32, f64));
12
+ }