@pkmn/engine 0.1.0-dev.5570b5c5 → 0.1.0-dev.59567a0b

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.
@@ -6,6 +6,13 @@ const expect = std.testing.expect;
6
6
  const expectEqual = std.testing.expectEqual;
7
7
  const expectError = std.testing.expectError;
8
8
 
9
+ const Int = if (@hasField(std.builtin.Type, "int")) .int else .Int;
10
+ const Float = if (@hasField(std.builtin.Type, "float")) .float else .Float;
11
+ const ComptimeInt =
12
+ if (@hasField(std.builtin.Type, "comptime_int")) .comptime_int else .ComptimeInt;
13
+ const ComptimeFloat =
14
+ if (@hasField(std.builtin.Type, "comptime_float")) .comptime_float else .ComptimeFloat;
15
+
9
16
  /// Specialization of a rational number used by the engine to compute probabilties.
10
17
  /// For performance reasons the rational is only reduced lazily and thus `reduce` must be
11
18
  /// invoked explicitly before reading.
@@ -22,15 +29,15 @@ pub fn Rational(comptime T: type) type {
22
29
  // start reducing when we get sufficiently close to the limit of the mantissa (in our domain
23
30
  // we expect updates to involve numbers < 2**10, so we should be safe not reducing before we
24
31
  // are 2**10 away from "overflowing" the mantissa)
25
- const REDUCE = if (@typeInfo(T) == .Float)
32
+ const REDUCE = if (@typeInfo(T) == Float)
26
33
  std.math.pow(T, 2, std.math.floatMantissaBits(T) - 10)
27
34
  else
28
35
  0;
29
36
 
30
37
  /// Possible error returned by operations on the Rational.
31
38
  pub const Error = switch (@typeInfo(T)) {
32
- .Int => error{Overflow},
33
- .Float => error{},
39
+ Int => error{Overflow},
40
+ Float => error{},
34
41
  else => unreachable,
35
42
  };
36
43
 
@@ -43,20 +50,19 @@ pub fn Rational(comptime T: type) type {
43
50
  /// Update the rational by multiplying its numerator by p and its denominator by q.
44
51
  /// Both p and q must be >= 1, and if computable at comptime must have no common factors.
45
52
  pub fn update(r: *Self, p: anytype, q: anytype) Error!void {
46
- // FIXME
47
- // std.debug.print("({d}/{d}) * ", .{ p, q });
53
+ // std.debug.print("({d}/{d}) * ", .{ p, q }); // DEBUG
48
54
  assert(p >= 1);
49
55
  assert(q >= 1);
50
56
 
51
57
  // If our parameters are not fully reduced they may prematurely
52
58
  // cause overflow/loss of precision after the multiplication below
53
59
  assert(switch (@typeInfo(@TypeOf(p, q))) {
54
- .ComptimeInt, .ComptimeFloat => comptime gcd(p, q),
60
+ ComptimeInt, ComptimeFloat => comptime gcd(p, q),
55
61
  else => 1,
56
62
  } == 1);
57
63
 
58
64
  switch (@typeInfo(T)) {
59
- .Int => {
65
+ Int => {
60
66
  // Greedily attempt to multiply and if it fails, reduce and try again
61
67
  r.multiplication(p, q) catch |err| switch (err) {
62
68
  error.Overflow => {
@@ -66,16 +72,16 @@ pub fn Rational(comptime T: type) type {
66
72
  else => unreachable,
67
73
  };
68
74
  },
69
- .Float => {
75
+ Float => {
70
76
  // Reduce in situations where we're likely to start losing precision
71
77
  if (r.q > REDUCE or r.p > REDUCE) r.reduce();
72
78
 
73
79
  r.p *= switch (@typeInfo(@TypeOf(p))) {
74
- .Float, .ComptimeFloat => p,
80
+ Float, ComptimeFloat => p,
75
81
  else => @floatFromInt(p),
76
82
  };
77
83
  r.q *= switch (@typeInfo(@TypeOf(q))) {
78
- .Float, .ComptimeFloat => q,
84
+ Float, ComptimeFloat => q,
79
85
  else => @floatFromInt(q),
80
86
  };
81
87
 
@@ -90,7 +96,7 @@ pub fn Rational(comptime T: type) type {
90
96
  /// Add two rationals using the identity (a/b) + (c/d) = (ad+bc)/(bd).
91
97
  pub fn add(r: *Self, s: *Self) Error!void {
92
98
  switch (@typeInfo(T)) {
93
- .Int => {
99
+ Int => {
94
100
  if (r.q == s.q) {
95
101
  r.p = std.math.add(T, r.p, s.p) catch |err| switch (err) {
96
102
  error.Overflow => val: {
@@ -111,7 +117,7 @@ pub fn Rational(comptime T: type) type {
111
117
  };
112
118
  }
113
119
  },
114
- .Float => {
120
+ Float => {
115
121
  if (r.q == s.q) {
116
122
  if (r.p > REDUCE) r.reduce();
117
123
  if (s.p > REDUCE) s.reduce();
@@ -136,7 +142,7 @@ pub fn Rational(comptime T: type) type {
136
142
  /// Multiplies two rationals.
137
143
  pub fn mul(r: *Self, s: *Self) Error!void {
138
144
  switch (@typeInfo(T)) {
139
- .Int => {
145
+ Int => {
140
146
  r.multiplication(s.p, s.q) catch |err| switch (err) {
141
147
  error.Overflow => {
142
148
  r.reduce();
@@ -146,7 +152,7 @@ pub fn Rational(comptime T: type) type {
146
152
  else => unreachable,
147
153
  };
148
154
  },
149
- .Float => {
155
+ Float => {
150
156
  if (r.q > REDUCE or r.p > REDUCE) r.reduce();
151
157
  if (s.q > REDUCE or s.p > REDUCE) s.reduce();
152
158
 
@@ -202,23 +208,74 @@ pub fn Rational(comptime T: type) type {
202
208
  };
203
209
  }
204
210
 
205
- // https://en.wikipedia.org/wiki/Euclidean_algorithm
206
211
  fn gcd(p: anytype, q: anytype) @TypeOf(p, q) {
207
212
  assert(p >= 1);
208
213
  assert(q >= 1);
209
214
 
210
- var a = p;
211
- var b = q;
212
- var c: @TypeOf(p, q) = undefined;
215
+ // convert comptime_int to a sized integer within this function so that @ctz will work
216
+ const T = switch (@TypeOf(p, q)) {
217
+ comptime_int => std.math.IntFittingRange(@min(p, q), @max(p, q)),
218
+ else => |U| U,
219
+ };
220
+
221
+ switch (@typeInfo(T)) {
222
+ Int => {
223
+ // std.math.gcd but without some checks because we have a stricter range
224
+ var x: T = @intCast(p);
225
+ var y: T = @intCast(q);
226
+
227
+ const xz = @ctz(x);
228
+ const yz = @ctz(y);
229
+ const shift = @min(xz, yz);
230
+ x >>= @intCast(xz);
231
+ y >>= @intCast(yz);
232
+
233
+ var diff = y -% x;
234
+ while (diff != 0) : (diff = y -% x) {
235
+ const zeros = @ctz(diff);
236
+ if (x > y) diff = -%diff;
237
+ y = @min(x, y);
238
+ x = diff >> @intCast(zeros);
239
+ }
213
240
 
214
- while (b != 0) {
215
- c = b;
216
- b = @mod(a, b);
217
- a = c;
241
+ const result = y << @intCast(shift);
242
+ assert(result > 0);
243
+ return result;
244
+ },
245
+ else => {
246
+ var a = p;
247
+ var b = q;
248
+ var c: T = undefined;
249
+
250
+ while (b != 0) {
251
+ c = b;
252
+ b = @mod(a, b);
253
+ a = c;
254
+ }
255
+
256
+ assert(a > 0);
257
+ return a;
258
+ },
218
259
  }
260
+ }
219
261
 
220
- assert(a > 0);
221
- return a;
262
+ test gcd {
263
+ const seed = if (@hasDecl(std.testing, "random_seed")) std.testing.random_seed else 0x12345678;
264
+ var prng = (if (@hasDecl(std, "Random")) std.Random else std.rand).DefaultPrng.init(seed);
265
+ var random = prng.random();
266
+
267
+ for (0..1000) |_| {
268
+ const a = random.int(u32);
269
+ const b = random.int(u32);
270
+ if (a == 0 or b == 0) continue;
271
+
272
+ try expectEqual(
273
+ gcd(a, b),
274
+ @as(u32, @intFromFloat(gcd(@as(f64, @floatFromInt(a)), @as(f64, @floatFromInt(b))))),
275
+ );
276
+ }
277
+
278
+ try expectEqual(gcd(300_000, @as(u32, 2_300_000)), 100_000); // NB: @ctz requires an @intCast
222
279
  }
223
280
 
224
281
  fn doTurn(r: anytype) !void {
@@ -355,3 +412,36 @@ test BigRational {
355
412
  try s.setRatio(71, 78);
356
413
  try expect((try s.order(r.val)) == .eq);
357
414
  }
415
+
416
+ test "minimum" {
417
+ // TODO: ziglang/zig#21069
418
+ if (builtin.mode == .ReleaseFast or builtin.mode == .ReleaseSmall) {
419
+ return error.SkipZigTest;
420
+ }
421
+ var r = try BigRational.init(std.testing.allocator);
422
+ defer r.deinit();
423
+ var s = try std.math.big.Rational.init(std.testing.allocator);
424
+ defer s.deinit();
425
+
426
+ try r.reset();
427
+
428
+ try r.update(1, 2); // Speed Tie
429
+ for (0..2) |_| {
430
+ try r.update(1, 2); // Confusion
431
+ try r.update(1, 2); // Infatuation
432
+ try r.update(3, 4); // Paralysis
433
+ // Population Bomb
434
+ for (0..10) |_| {
435
+ try r.update(9, 10); // Accuracy
436
+ try r.update(1, 15); // Damage roll
437
+ try r.update(1, 24); // Critical Hit
438
+ try r.update(9, 10); // King's Rock non-proc
439
+ }
440
+ }
441
+
442
+ const ZEROS = std.math.pow(u310, 10, 31);
443
+ const n = 36472996377170786403;
444
+ const d: u310 = 146267071761884981524886149560653378220687632500762654519853056 * ZEROS;
445
+ try s.setRatio(n, d);
446
+ try expect((try s.order(r.val)) == .eq);
447
+ }
@@ -74,7 +74,7 @@ pub const PSRNG = extern struct {
74
74
 
75
75
  test PSRNG {
76
76
  var psrng: PSRNG = .{ .src = .{ .seed = 0x0001000200030004 } };
77
- try expectEqual(121, psrng.range(u8, 0, 256));
77
+ try expectEqual(@as(u8, 121), psrng.range(u8, 0, 256));
78
78
  try expectEqual(false, psrng.chance(u8, 128, 256)); // 226 < 128
79
79
  }
80
80
 
@@ -111,9 +111,9 @@ test Gen12 {
111
111
  try expectEqual(e, rng.next());
112
112
  }
113
113
 
114
- try expectEqual(16, Gen12.percent(6) + 1);
115
- try expectEqual(16, Gen12.percent(7) - 1);
116
- try expectEqual(128, Gen12.percent(50) + 1);
114
+ try expectEqual(@as(u8, 16), Gen12.percent(6) + 1);
115
+ try expectEqual(@as(u8, 16), Gen12.percent(7) - 1);
116
+ try expectEqual(@as(u8, 128), Gen12.percent(50) + 1);
117
117
  }
118
118
 
119
119
  // https://pkmn.cc/pokeemerald/src/random.c
@@ -1,12 +1,61 @@
1
1
  const std = @import("std");
2
2
 
3
+ const expect = std.testing.expect;
3
4
  const expectEqual = std.testing.expectEqual;
4
5
 
6
+ const Pointer = if (@hasField(std.builtin.Type, "pointer")) .pointer else .Pointer;
7
+
5
8
  pub fn PointerType(comptime P: type, comptime C: type) type {
6
- return if (@typeInfo(P).Pointer.is_const) *const C else *C;
9
+ return if (@field(@typeInfo(P), @tagName(Pointer)).is_const) *const C else *C;
7
10
  }
8
11
 
9
12
  test PointerType {
10
13
  try expectEqual(*bool, PointerType(*u8, bool));
11
14
  try expectEqual(*const f64, PointerType(*const i32, f64));
12
15
  }
16
+
17
+ pub fn isPointerTo(p: anytype, comptime P: type) bool {
18
+ const info = @typeInfo(@TypeOf(p));
19
+ return switch (info) {
20
+ Pointer => @field(info, @tagName(Pointer)).child == P,
21
+ else => false,
22
+ };
23
+ }
24
+
25
+ test isPointerTo {
26
+ const S = struct {};
27
+ const s: S = .{};
28
+ try expect(!isPointerTo(s, S));
29
+ try expect(isPointerTo(&s, S));
30
+ }
31
+
32
+ // NOTE: std.mem.bytesAsValue backported from ziglang/zig#18061
33
+ pub fn bytesAsValue(comptime T: type, bytes: anytype) BytesAsValueReturnType(T, @TypeOf(bytes)) {
34
+ return @as(BytesAsValueReturnType(T, @TypeOf(bytes)), @ptrCast(bytes));
35
+ }
36
+
37
+ fn BytesAsValueReturnType(comptime T: type, comptime B: type) type {
38
+ return CopyPtrAttrs(B, .One, T);
39
+ }
40
+
41
+ fn CopyPtrAttrs(
42
+ comptime source: type,
43
+ comptime size: std.builtin.Type.Pointer.Size,
44
+ comptime child: type,
45
+ ) type {
46
+ const info = @field(@typeInfo(source), @tagName(Pointer));
47
+ const args = .{
48
+ .size = size,
49
+ .is_const = info.is_const,
50
+ .is_volatile = info.is_volatile,
51
+ .is_allowzero = info.is_allowzero,
52
+ .alignment = info.alignment,
53
+ .address_space = info.address_space,
54
+ .child = child,
55
+ .sentinel = null,
56
+ };
57
+ return @Type(if (@hasField(std.builtin.Type, "pointer"))
58
+ .{ .pointer = args }
59
+ else
60
+ .{ .Pointer = args });
61
+ }