Merge main and #607 into perf/versioned-behaviours-cache

level/data.rs, level/mod.rs: load, load_with_behaviour_json and
load_with_gameplay all go through one cached() helper (try the snapshot,
build and store on a miss), so #607's client path keeps this cache.
Resolution from contrib-review-1's validated integration, without #601.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-17 08:15:49 +02:00
33 changed files with 4198 additions and 82 deletions
@@ -0,0 +1,379 @@
{
"scope": "Assets + BlockFacts + Behaviours loader only; no full startup or first frame",
"resources": "/srv/bob-data/horizon/.local/horizon-client/26.3",
"repeats": 10,
"ordering": [
[
"released",
"retained"
],
[
"retained",
"released"
],
[
"released",
"retained"
],
[
"retained",
"released"
],
[
"released",
"retained"
],
[
"retained",
"released"
],
[
"released",
"retained"
],
[
"retained",
"released"
],
[
"released",
"retained"
],
[
"retained",
"released"
]
],
"load_average_before": [
8.2421875,
6.56396484375,
6.39208984375
],
"load_average_after": [
7.98095703125,
6.6455078125,
6.4248046875
],
"executables": {
"released": {
"path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-integrated",
"mode": "deferred",
"sha256": "a52d6a7efc7b3198ef0dd8150325f56a3fe5d0c5883fd6d14c4b0c281866ce7c"
},
"retained": {
"path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-integrated",
"mode": "deferred-held",
"sha256": "a52d6a7efc7b3198ef0dd8150325f56a3fe5d0c5883fd6d14c4b0c281866ce7c"
}
},
"metrics": {
"released": {
"phase_ms": {
"median": 482.591,
"p25": 444.276,
"p75": 586.92,
"min": 430.128,
"max": 736.543,
"samples": [
529.244,
606.146,
449.23,
442.624,
669.108,
511.519,
736.543,
432.616,
430.128,
453.663
]
},
"total_ms": {
"median": 987.004,
"p25": 932.885,
"p75": 1134.876,
"min": 914.242,
"max": 1201.759,
"samples": [
1055.119,
1161.462,
968.629,
914.242,
1201.759,
1005.379,
1200.01,
928.249,
935.775,
931.921
]
},
"cpu_ms": {
"median": 1004.675,
"p25": 936.465,
"p75": 1116.791,
"min": 908.327,
"max": 1241.168,
"samples": [
1074.425,
1130.913,
984.832,
931.205,
1186.169,
1024.519,
1241.168,
908.327,
952.245,
927.15
]
},
"peak_rss_kib": {
"median": 268124.0,
"p25": 267753.0,
"p75": 268455.0,
"min": 267708,
"max": 268700,
"samples": [
268268,
268500,
267744,
267724,
267708,
267780,
268700,
268496,
268332,
267980
]
},
"behaviour_json_ms": {
"median": 24.371,
"p25": 22.469,
"p75": 28.486,
"min": 20.662,
"max": 35.297,
"samples": [
33.387,
35.297,
24.732,
24.011,
27.699,
28.748,
23.623,
22.084,
20.662,
21.266
]
},
"facts_ms": {
"median": 292.77,
"p25": 270.649,
"p75": 383.193,
"min": 264.691,
"max": 443.291,
"samples": [
346.613,
398.468,
274.673,
264.691,
443.291,
292.926,
395.387,
267.232,
269.308,
292.615
]
},
"behaviours_ms": {
"median": 148.635,
"p25": 141.329,
"p75": 181.741,
"min": 136.361,
"max": 307.004,
"samples": [
145.009,
168.982,
146.535,
150.736,
194.604,
185.994,
307.004,
140.102,
136.785,
136.361
]
},
"post_rss_kib": {
"median": 268668.0,
"p25": 268246.0,
"p75": 268922.0,
"min": 268048.0,
"max": 269012.0,
"samples": [
268668.0,
268936.0,
268108.0,
268088.0,
268048.0,
268668.0,
268880.0,
269012.0,
268960.0,
268660.0
]
}
},
"retained": {
"phase_ms": {
"median": 487.954,
"p25": 471.456,
"p75": 531.586,
"min": 401.516,
"max": 834.154,
"samples": [
486.974,
613.755,
540.535,
470.333,
488.934,
474.825,
834.154,
504.74,
401.516,
440.381
]
},
"total_ms": {
"median": 1038.875,
"p25": 989.724,
"p75": 1079.197,
"min": 880.933,
"max": 1746.386,
"samples": [
996.407,
1067.467,
1082.69,
1103.131,
1010.283,
1068.719,
1746.386,
987.496,
890.46,
880.933
]
},
"cpu_ms": {
"median": 1035.537,
"p25": 982.276,
"p75": 1082.698,
"min": 908.774,
"max": 1660.068,
"samples": [
1011.712,
1087.688,
1076.523,
1084.757,
998.654,
1059.363,
1660.068,
976.817,
912.849,
908.774
]
},
"peak_rss_kib": {
"median": 268150.0,
"p25": 267537.0,
"p75": 268614.0,
"min": 267268,
"max": 268848,
"samples": [
268748,
267968,
267268,
268332,
267540,
268560,
267492,
268632,
267536,
268848
]
},
"behaviour_json_ms": {
"median": 23.208,
"p25": 22.305,
"p75": 26.544,
"min": 20.059,
"max": 32.669,
"samples": [
32.669,
22.62,
22.2,
27.331,
25.088,
27.029,
23.488,
20.977,
22.928,
20.059
]
},
"facts_ms": {
"median": 304.44,
"p25": 291.562,
"p75": 330.991,
"min": 244.758,
"max": 384.634,
"samples": [
307.936,
374.145,
336.931,
300.944,
290.81,
293.817,
384.634,
313.171,
244.758,
279.303
]
},
"behaviours_ms": {
"median": 162.285,
"p25": 143.135,
"p75": 179.31,
"min": 133.83,
"max": 426.031,
"samples": [
146.367,
216.988,
181.402,
142.058,
173.036,
153.978,
426.031,
170.592,
133.83,
141.017
]
},
"post_rss_kib": {
"median": 268694.0,
"p25": 268116.0,
"p75": 269056.0,
"min": 267988.0,
"max": 269212.0,
"samples": [
269212.0,
268564.0,
268096.0,
268824.0,
268176.0,
269032.0,
267988.0,
269064.0,
268044.0,
269120.0
]
}
}
}
}
@@ -0,0 +1,176 @@
{
"scope": "Isolated gameplay-facts.json validation/typed decoding; includes JSON file read",
"resources": "/srv/bob-data/horizon/.local/horizon-client/26.3",
"repeats": 10,
"load_averages_before_after": [
[
14.7451171875,
8.8994140625,
6.89599609375
],
[
14.7451171875,
8.8994140625,
6.89599609375
]
],
"binary_sha256": "c2be9140c792720499d70c5806b8def0472734264ad72486d01365447e0cc2d7",
"metrics": {
"validate": {
"phase_ms": {
"median": 117.417,
"p25": 114.101,
"p75": 158.855,
"min": 109.199,
"max": 173.408,
"samples": [
109.199,
113.958,
110.195,
118.987,
171.275,
124.701,
170.24,
173.408,
115.848,
114.531
]
},
"total_ms": {
"median": 139.933,
"p25": 133.863,
"p75": 193.565,
"min": 129.75,
"max": 276.311,
"samples": [
276.311,
135.448,
129.75,
138.452,
195.127,
141.413,
188.88,
199.802,
133.335,
132.094
]
},
"cpu_ms": {
"median": 138.849,
"p25": 134.285,
"p75": 168.881,
"min": 129.089,
"max": 190.82,
"samples": [
140.962,
136.06,
129.089,
139.059,
189.478,
138.639,
178.187,
190.82,
133.693,
132.716
]
},
"peak_rss_kib": {
"median": 56654.0,
"p25": 56642.0,
"p75": 56704.0,
"min": 56616,
"max": 56724,
"samples": [
56620,
56656,
56640,
56720,
56616,
56724,
56652,
56720,
56648,
56656
]
}
},
"typed": {
"phase_ms": {
"median": 115.873,
"p25": 109.422,
"p75": 129.67,
"min": 100.872,
"max": 183.923,
"samples": [
116.965,
132.071,
100.872,
105.098,
122.468,
170.777,
107.997,
183.923,
113.699,
114.781
]
},
"total_ms": {
"median": 133.883,
"p25": 126.939,
"p75": 155.913,
"min": 117.54,
"max": 210.164,
"samples": [
135.04,
159.38,
117.54,
122.391,
145.512,
189.132,
125.846,
210.164,
130.217,
132.727
]
},
"cpu_ms": {
"median": 134.375,
"p25": 126.231,
"p75": 154.675,
"min": 118.132,
"max": 204.242,
"samples": [
135.633,
157.961,
118.132,
122.77,
144.816,
178.293,
124.755,
204.242,
130.661,
133.117
]
},
"peak_rss_kib": {
"median": 83974.0,
"p25": 82744.0,
"p75": 84490.0,
"min": 82332,
"max": 84596,
"samples": [
83596,
84596,
82332,
82424,
84288,
82460,
84532,
83660,
84364,
84536
]
}
}
}
}
@@ -0,0 +1,453 @@
{
"scope": "Assets + BlockFacts + Behaviours loader only; no full startup or first frame",
"resources": "/srv/bob-data/horizon/.local/horizon-client/26.3",
"repeats": 8,
"ordering": [
[
"baseline",
"a01d47f2",
"cf837118",
"cd61e11b",
"current"
],
[
"current",
"cd61e11b",
"cf837118",
"a01d47f2",
"baseline"
],
[
"baseline",
"a01d47f2",
"cf837118",
"cd61e11b",
"current"
],
[
"current",
"cd61e11b",
"cf837118",
"a01d47f2",
"baseline"
],
[
"baseline",
"a01d47f2",
"cf837118",
"cd61e11b",
"current"
],
[
"current",
"cd61e11b",
"cf837118",
"a01d47f2",
"baseline"
],
[
"baseline",
"a01d47f2",
"cf837118",
"cd61e11b",
"current"
],
[
"current",
"cd61e11b",
"cf837118",
"a01d47f2",
"baseline"
]
],
"load_average_before": [
10.57958984375,
8.45947265625,
6.8134765625
],
"load_average_after": [
7.158203125,
7.7998046875,
6.66455078125
],
"executables": {
"baseline": {
"path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-e422bd13",
"mode": "baseline",
"sha256": "bf61f2e6c92e001be3c3bc93cf8072cc6af6fd1d7bcfa7273045960948ec89e7"
},
"a01d47f2": {
"path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-a01d47f2",
"mode": "shared",
"sha256": "88be56f8dbd28d0b4abd6c672486ba758df96ba18f68da45b94db14231dd3eea"
},
"cf837118": {
"path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-cf837118",
"mode": "deferred",
"sha256": "f1b044cd9ac2f67c644fb40bd7ecbe38128ec739a8112d57fc36f05fe9036a52"
},
"cd61e11b": {
"path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-cd61e11b",
"mode": "deferred",
"sha256": "fb2d3725b09ee38f85b49901f7053a6fe339b980a2b2dac6930a8ded22c139e8"
},
"current": {
"path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-new",
"mode": "deferred",
"sha256": "84eb1baae8e138f52e300b0b44f1339fca38e70db6e06126e78db776ea3e5cd0"
}
},
"metrics": {
"baseline": {
"phase_ms": {
"median": 1277.781,
"p25": 1271.23,
"p75": 1296.157,
"min": 1223.341,
"max": 1338.745,
"samples": [
1265.934,
1223.341,
1274.931,
1289.177,
1338.745,
1317.096,
1272.995,
1280.631
]
},
"total_ms": {
"median": 1711.802,
"p25": 1695.745,
"p75": 1754.276,
"min": 1645.69,
"max": 2887.078,
"samples": [
2887.078,
1645.69,
1690.413,
1711.459,
1761.859,
1751.748,
1697.522,
1712.144
]
},
"cpu_ms": {
"median": 1769.996,
"p25": 1748.925,
"p75": 1807.254,
"min": 1705.167,
"max": 1950.463,
"samples": [
1950.463,
1705.167,
1749.023,
1768.05,
1804.543,
1815.386,
1771.942,
1748.632
]
},
"peak_rss_kib": {
"median": 820180.0,
"p25": 820030.0,
"p75": 820502.0,
"min": 819472,
"max": 820884,
"samples": [
819472,
820416,
820060,
820096,
820264,
820884,
819940,
820760
]
}
},
"a01d47f2": {
"phase_ms": {
"median": 430.783,
"p25": 427.542,
"p75": 451.763,
"min": 423.035,
"max": 550.345,
"samples": [
491.599,
423.035,
428.85,
427.694,
432.715,
427.084,
438.484,
550.345
]
},
"total_ms": {
"median": 868.457,
"p25": 863.709,
"p75": 932.066,
"min": 837.75,
"max": 997.779,
"samples": [
911.935,
837.75,
865.419,
868.626,
858.578,
997.779,
868.288,
992.46
]
},
"cpu_ms": {
"median": 897.639,
"p25": 887.661,
"p75": 944.363,
"min": 865.497,
"max": 1001.635,
"samples": [
925.321,
865.497,
899.505,
895.774,
876.929,
1001.635,
891.239,
1001.488
]
},
"peak_rss_kib": {
"median": 351906.0,
"p25": 351505.0,
"p75": 352181.0,
"min": 351176,
"max": 352440,
"samples": [
352008,
352120,
351352,
351556,
351804,
351176,
352440,
352364
]
}
},
"cf837118": {
"phase_ms": {
"median": 408.459,
"p25": 398.987,
"p75": 428.585,
"min": 387.999,
"max": 524.425,
"samples": [
433.521,
387.999,
412.195,
397.366,
404.724,
399.527,
426.939,
524.425
]
},
"total_ms": {
"median": 851.294,
"p25": 823.291,
"p75": 890.55,
"min": 801.356,
"max": 1030.737,
"samples": [
892.054,
801.356,
840.381,
818.285,
862.208,
824.96,
890.049,
1030.737
]
},
"cpu_ms": {
"median": 870.765,
"p25": 850.849,
"p75": 907.922,
"min": 825.718,
"max": 1041.996,
"samples": [
906.657,
825.718,
866.472,
843.591,
875.058,
853.268,
911.715,
1041.996
]
},
"peak_rss_kib": {
"median": 274172.0,
"p25": 273909.0,
"p75": 274438.0,
"min": 273668,
"max": 274964,
"samples": [
274372,
274964,
273668,
273972,
274552,
274400,
273840,
273932
]
}
},
"cd61e11b": {
"phase_ms": {
"median": 419.114,
"p25": 404.191,
"p75": 460.634,
"min": 388.557,
"max": 735.687,
"samples": [
457.971,
418.303,
388.557,
405.041,
419.925,
401.64,
468.624,
735.687
]
},
"total_ms": {
"median": 840.723,
"p25": 835.398,
"p75": 917.995,
"min": 811.43,
"max": 1565.471,
"samples": [
906.328,
837.706,
811.43,
835.727,
843.74,
834.412,
952.996,
1565.471
]
},
"cpu_ms": {
"median": 863.404,
"p25": 858.916,
"p75": 934.2,
"min": 833.955,
"max": 1550.132,
"samples": [
916.017,
864.82,
833.955,
859.057,
861.989,
858.494,
988.748,
1550.132
]
},
"peak_rss_kib": {
"median": 267508.0,
"p25": 267310.0,
"p75": 267890.0,
"min": 267172,
"max": 268412,
"samples": [
267304,
268292,
267312,
267756,
267340,
267676,
267172,
268412
]
}
},
"current": {
"phase_ms": {
"median": 406.779,
"p25": 397.839,
"p75": 413.957,
"min": 385.028,
"max": 552.051,
"samples": [
387.136,
385.028,
409.317,
404.242,
401.407,
411.451,
421.476,
552.051
]
},
"total_ms": {
"median": 819.787,
"p25": 814.211,
"p75": 855.69,
"min": 800.867,
"max": 1128.453,
"samples": [
808.685,
800.867,
816.053,
817.907,
821.667,
843.26,
892.982,
1128.453
]
},
"cpu_ms": {
"median": 847.078,
"p25": 836.598,
"p75": 877.524,
"min": 826.002,
"max": 1134.369,
"samples": [
834.665,
826.002,
837.243,
842.86,
851.296,
864.892,
915.419,
1134.369
]
},
"peak_rss_kib": {
"median": 267956.0,
"p25": 267612.0,
"p75": 268326.0,
"min": 267308,
"max": 268428,
"samples": [
268428,
267308,
268260,
267516,
267652,
268312,
268368,
267644
]
}
}
},
"experiment_note": "Experimental projection variant (reused sounds, Arc-keyed string pools and direct flags); reverted after mixed CPU/RSS evidence. Current in this file is not the final PR version."
}
@@ -0,0 +1,582 @@
{
"scope": "Assets + BlockFacts + Behaviours loader only; no full startup or first frame",
"resources": "/srv/bob-data/horizon/.local/horizon-client/26.3",
"repeats": 10,
"ordering": [
[
"baseline",
"a01d47f2",
"cf837118",
"cd61e11b",
"current"
],
[
"current",
"cd61e11b",
"cf837118",
"a01d47f2",
"baseline"
],
[
"baseline",
"a01d47f2",
"cf837118",
"cd61e11b",
"current"
],
[
"current",
"cd61e11b",
"cf837118",
"a01d47f2",
"baseline"
],
[
"baseline",
"a01d47f2",
"cf837118",
"cd61e11b",
"current"
],
[
"current",
"cd61e11b",
"cf837118",
"a01d47f2",
"baseline"
],
[
"baseline",
"a01d47f2",
"cf837118",
"cd61e11b",
"current"
],
[
"current",
"cd61e11b",
"cf837118",
"a01d47f2",
"baseline"
],
[
"baseline",
"a01d47f2",
"cf837118",
"cd61e11b",
"current"
],
[
"current",
"cd61e11b",
"cf837118",
"a01d47f2",
"baseline"
]
],
"load_average_before": [
11.4921875,
7.46875,
6.69677734375
],
"load_average_after": [
17.763671875,
11.39013671875,
8.20556640625
],
"executables": {
"baseline": {
"path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-e422bd13",
"mode": "baseline",
"sha256": "bf61f2e6c92e001be3c3bc93cf8072cc6af6fd1d7bcfa7273045960948ec89e7"
},
"a01d47f2": {
"path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-a01d47f2",
"mode": "shared",
"sha256": "88be56f8dbd28d0b4abd6c672486ba758df96ba18f68da45b94db14231dd3eea"
},
"cf837118": {
"path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-cf837118",
"mode": "deferred",
"sha256": "f1b044cd9ac2f67c644fb40bd7ecbe38128ec739a8112d57fc36f05fe9036a52"
},
"cd61e11b": {
"path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-cd61e11b",
"mode": "deferred",
"sha256": "fb2d3725b09ee38f85b49901f7053a6fe339b980a2b2dac6930a8ded22c139e8"
},
"current": {
"path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-integrated",
"mode": "deferred",
"sha256": "a52d6a7efc7b3198ef0dd8150325f56a3fe5d0c5883fd6d14c4b0c281866ce7c"
}
},
"metrics": {
"baseline": {
"phase_ms": {
"median": 1506.588,
"p25": 1388.314,
"p75": 2119.85,
"min": 1319.319,
"max": 3143.124,
"samples": [
3143.124,
2483.307,
2124.952,
2104.544,
1525.153,
1396.75,
1381.771,
1488.022,
1385.502,
1319.319
]
},
"total_ms": {
"median": 1962.122,
"p25": 1858.188,
"p75": 3152.608,
"min": 1804.713,
"max": 4136.912,
"samples": [
4136.912,
3250.285,
3134.13,
3158.767,
2001.229,
1883.076,
1849.892,
1923.016,
1818.34,
1804.713
]
},
"cpu_ms": {
"median": 1969.296,
"p25": 1893.348,
"p75": 2694.824,
"min": 1842.049,
"max": 3059.824,
"samples": [
3059.824,
2765.392,
2698.837,
2682.786,
2026.89,
1911.703,
1888.282,
1908.545,
1859.233,
1842.049
]
},
"peak_rss_kib": {
"median": 819952.0,
"p25": 819778.0,
"p75": 820164.0,
"min": 818944,
"max": 820304,
"samples": [
819956,
819744,
818944,
818984,
820128,
820176,
819948,
820236,
819880,
820304
]
}
},
"a01d47f2": {
"phase_ms": {
"median": 666.765,
"p25": 520.278,
"p75": 1156.022,
"min": 450.677,
"max": 1882.249,
"samples": [
1001.208,
1309.911,
1207.627,
1882.249,
747.233,
544.933,
512.06,
450.677,
466.596,
586.298
]
},
"total_ms": {
"median": 1141.968,
"p25": 974.723,
"p75": 2326.553,
"min": 922.496,
"max": 3158.114,
"samples": [
2374.699,
2275.18,
2343.677,
3158.114,
1267.594,
1006.411,
964.16,
922.496,
936.687,
1016.342
]
},
"cpu_ms": {
"median": 1106.901,
"p25": 973.629,
"p75": 1525.998,
"min": 929.573,
"max": 1568.573,
"samples": [
1545.278,
1568.573,
1468.158,
1563.377,
1196.236,
1017.565,
960.219,
929.573,
946.096,
1013.861
]
},
"peak_rss_kib": {
"median": 351564.0,
"p25": 351148.0,
"p75": 352106.0,
"min": 350416,
"max": 353368,
"samples": [
351572,
351268,
351108,
350416,
351656,
353368,
352256,
351556,
350964,
352308
]
}
},
"cf837118": {
"phase_ms": {
"median": 505.124,
"p25": 435.315,
"p75": 1103.87,
"min": 417.056,
"max": 1875.147,
"samples": [
1875.147,
1129.722,
1066.305,
1116.391,
461.019,
423.38,
417.056,
445.353,
549.229,
431.969
]
},
"total_ms": {
"median": 1209.375,
"p25": 895.862,
"p75": 2133.144,
"min": 872.434,
"max": 2936.234,
"samples": [
2936.234,
2215.538,
1885.964,
2695.131,
1378.495,
879.351,
897.968,
895.16,
1040.255,
872.434
]
},
"cpu_ms": {
"median": 1068.41,
"p25": 896.926,
"p75": 1488.578,
"min": 882.398,
"max": 1570.652,
"samples": [
1530.601,
1520.851,
1391.76,
1570.652,
1116.403,
900.779,
894.039,
895.642,
1020.417,
882.398
]
},
"peak_rss_kib": {
"median": 273832.0,
"p25": 273592.0,
"p75": 274131.0,
"min": 272732,
"max": 274976,
"samples": [
274080,
272732,
273560,
273468,
274200,
274148,
273728,
273936,
274976,
273688
]
}
},
"cd61e11b": {
"phase_ms": {
"median": 429.481,
"p25": 410.043,
"p75": 1178.091,
"min": 399.576,
"max": 1644.881,
"samples": [
1194.624,
1128.491,
1644.881,
1428.78,
405.544,
434.62,
424.341,
414.829,
408.447,
399.576
]
},
"total_ms": {
"median": 902.865,
"p25": 868.889,
"p75": 2443.447,
"min": 827.16,
"max": 2961.261,
"samples": [
2682.056,
2199.278,
2524.837,
2961.261,
884.838,
885.282,
848.79,
863.573,
920.448,
827.16
]
},
"cpu_ms": {
"median": 920.917,
"p25": 869.777,
"p75": 1475.629,
"min": 840.036,
"max": 1626.459,
"samples": [
1518.201,
1496.456,
1413.149,
1626.459,
893.762,
899.049,
861.782,
861.417,
942.785,
840.036
]
},
"peak_rss_kib": {
"median": 267762.0,
"p25": 267612.0,
"p75": 267966.0,
"min": 266300,
"max": 268636,
"samples": [
266672,
268636,
266300,
267596,
267660,
268280,
267968,
267680,
267960,
267844
]
}
},
"current": {
"phase_ms": {
"median": 460.489,
"p25": 429.004,
"p75": 986.935,
"min": 404.103,
"max": 1300.033,
"samples": [
992.891,
1126.098,
1300.033,
969.067,
443.604,
408.397,
472.429,
424.137,
448.549,
404.103
]
},
"total_ms": {
"median": 935.623,
"p25": 874.18,
"p75": 2282.679,
"min": 839.642,
"max": 2965.198,
"samples": [
2320.566,
2169.019,
2965.198,
2531.591,
924.347,
839.642,
946.899,
873.617,
875.87,
854.328
]
},
"cpu_ms": {
"median": 950.702,
"p25": 892.992,
"p75": 1540.918,
"min": 861.669,
"max": 1586.478,
"samples": [
1557.765,
1503.564,
1553.369,
1586.478,
931.391,
861.669,
970.013,
888.14,
907.549,
868.73
]
},
"peak_rss_kib": {
"median": 268010.0,
"p25": 267013.0,
"p75": 268385.0,
"min": 266144,
"max": 268876,
"samples": [
266824,
267580,
266516,
266144,
267976,
268304,
268044,
268480,
268412,
268876
]
},
"behaviour_json_ms": {
"median": 34.288,
"p25": 23.085,
"p75": 37.474,
"min": 20.137,
"max": 70.397,
"samples": [
37.07,
70.397,
37.609,
38.225,
34.568,
21.094,
23.469,
22.957,
34.008,
20.137
]
},
"facts_ms": {
"median": 272.839,
"p25": 256.553,
"p75": 618.472,
"min": 248.146,
"max": 780.388,
"samples": [
625.908,
693.735,
780.388,
596.165,
272.718,
249.954,
272.959,
264.913,
253.767,
248.146
]
},
"behaviours_ms": {
"median": 162.633,
"p25": 133.345,
"p75": 326.117,
"min": 132.828,
"max": 476.9,
"samples": [
325.198,
356.28,
476.9,
326.424,
132.828,
133.946,
167.929,
133.144,
157.337,
132.934
]
},
"post_rss_kib": {
"median": 268408.0,
"p25": 267369.0,
"p75": 268861.0,
"min": 267052.0,
"max": 269072.0,
"samples": [
267084.0,
268056.0,
267052.0,
267140.0,
268184.0,
268632.0,
268660.0,
269072.0,
268928.0,
268960.0
]
}
}
}
}
@@ -0,0 +1,188 @@
{
"scope": "Assets + block facts + behaviours loader only; excludes full startup",
"resources": ".local/horizon-client/26.3",
"repeats": 5,
"comparison": "historical cf837118 release binary",
"reference_binary": "target/release/examples/shared_json_startup_profile-cf837118",
"metrics": {
"baseline": {
"phase_ms": {
"median": 1462.003,
"samples": [
1639.999,
1506.864,
1429.844,
1462.003,
1346.061
]
},
"total_ms": {
"median": 1922.795,
"samples": [
3383.516,
1990.554,
1912.354,
1922.795,
1777.912
]
},
"cpu_ms": {
"median": 1961.459,
"samples": [
2419.086,
2021.457,
1951.587,
1961.459,
1839.984
]
},
"peak_rss_kib": {
"median": 820912,
"samples": [
819956,
821052,
820912,
821792,
820424
]
}
},
"pr607": {
"phase_ms": {
"median": 486.715,
"samples": [
460.738,
442.013,
623.053,
486.715,
550.652
]
},
"total_ms": {
"median": 948.089,
"samples": [
923.057,
935.599,
1109.64,
948.089,
1052.546
]
},
"cpu_ms": {
"median": 968.424,
"samples": [
928.489,
946.932,
1128.431,
968.424,
1079.642
]
},
"peak_rss_kib": {
"median": 351796,
"samples": [
351796,
351844,
351536,
351532,
351988
]
}
},
"cf837118": {
"phase_ms": {
"median": 474.268,
"samples": [
443.122,
474.268,
520.497,
433.525,
532.058
]
},
"total_ms": {
"median": 945.87,
"samples": [
934.722,
945.87,
1006.539,
888.201,
1032.6
]
},
"cpu_ms": {
"median": 953.668,
"samples": [
941.957,
953.668,
1029.122,
903.574,
1065.025
]
},
"peak_rss_kib": {
"median": 274476,
"samples": [
273448,
274844,
274476,
274556,
274252
]
}
},
"current": {
"phase_ms": {
"median": 445.924,
"samples": [
472.165,
427.797,
419.288,
445.924,
524.211
]
},
"total_ms": {
"median": 999.669,
"samples": [
999.669,
892.616,
1051.427,
940.595,
1112.158
]
},
"cpu_ms": {
"median": 1001.24,
"samples": [
1001.24,
887.874,
1051.732,
951.495,
1132.208
]
},
"peak_rss_kib": {
"median": 267604,
"samples": [
267716,
267920,
267448,
267604,
267344
]
}
}
},
"builds": {
"current": "release example built at cf837118 + current uncommitted delta in PR #607 worktree",
"historical": "release example built at exact cf837118 commit, with same Cargo release profile and shared dependency target"
},
"mode_commits": {
"baseline": "independent loader algorithm at e422bd13, executed in current binary",
"pr607": "shared early construction algorithm at a01d47f2, executed in current binary",
"cf837118": "exact historical binary at cf837118, deferred mode",
"current": "current PR worktree, deferred mode with interned strings"
},
"limitations": "Loader-only (Assets + BlockFacts + Behaviours), no full client startup or first-frame timing. Same release profile but different compilation contexts for historical binary; hardware activity and cache warmth vary. CPU and elapsed differences between cf837118 and current are mixed and may be noise. Peak RSS is whole-process Linux ru_maxrss."
}
@@ -0,0 +1,93 @@
{
"scope": "Assets + block facts + behaviours loader only; excludes full startup",
"resources": ".local/horizon-client/26.3",
"repeats": 5,
"metrics": {
"baseline": {
"phase_ms": {
"median": 4730.402,
"samples": [
3258.541,
6539.764,
4773.735,
3980.032,
4730.402
]
},
"total_ms": {
"median": 6325.026,
"samples": [
6596.141,
7627.893,
6296.443,
5435.408,
6325.026
]
},
"cpu_ms": {
"median": 3199.722,
"samples": [
3322.801,
3199.722,
3227.438,
3042.687,
3144.658
]
},
"peak_rss_kib": {
"median": 820000,
"samples": [
818540,
820400,
819352,
820000,
820128
]
}
},
"shared": {
"phase_ms": {
"median": 1180.588,
"samples": [
869.228,
842.213,
1180.588,
1560.087,
1728.575
]
},
"total_ms": {
"median": 2260.709,
"samples": [
1632.489,
1553.753,
2260.709,
2879.728,
3388.639
]
},
"cpu_ms": {
"median": 1603.393,
"samples": [
1568.288,
1432.106,
1603.393,
1604.423,
1619.02
]
},
"peak_rss_kib": {
"median": 351728,
"samples": [
353256,
353664,
351728,
350724,
351668
]
}
}
},
"build": "cargo build --release -p horizon-client --example shared_json_startup_profile",
"limitations": "Loader-only wall-clock timings under concurrent machine load; not full startup or time to first frame. RSS includes Assets::load."
}
@@ -0,0 +1,227 @@
{
"scope": "Assets + block facts + behaviours loader only; excludes full startup",
"resources": ".local/horizon-client/26.3",
"repeats": 5,
"metrics": {
"baseline": {
"phase_ms": {
"median": 1996.921,
"samples": [
2213.335,
1453.207,
1637.901,
1996.921,
2010.335
],
"range": [
1453.207,
2213.335
]
},
"total_ms": {
"median": 4728.136,
"samples": [
5628.975,
2147.329,
2162.696,
4728.136,
6404.524
],
"range": [
2147.329,
6404.524
]
},
"cpu_ms": {
"median": 2514.776,
"samples": [
2919.908,
2088.239,
2212.892,
2716.104,
2514.776
],
"range": [
2088.239,
2919.908
]
},
"peak_rss_kib": {
"median": 819824,
"samples": [
819824,
820872,
820744,
818980,
818816
]
}
},
"pr607": {
"phase_ms": {
"median": 586.707,
"samples": [
464.424,
739.67,
586.707,
1373.307,
509.266
],
"range": [
464.424,
1373.307
]
},
"total_ms": {
"median": 1128.6,
"samples": [
954.73,
1764.614,
1128.6,
4312.528,
1030.735
],
"range": [
954.73,
4312.528
]
},
"cpu_ms": {
"median": 1145.826,
"samples": [
981.058,
1465.79,
1145.826,
1736.807,
1056.992
],
"range": [
981.058,
1736.807
]
},
"peak_rss_kib": {
"median": 351900,
"samples": [
352164,
351816,
351900,
352348,
350492
]
}
},
"shared": {
"phase_ms": {
"median": 560.117,
"samples": [
522.284,
1255.75,
560.117,
2151.064,
479.329
],
"range": [
479.329,
2151.064
]
},
"total_ms": {
"median": 1101.305,
"samples": [
1011.715,
2565.449,
1101.305,
2960.186,
1006.817
],
"range": [
1006.817,
2960.186
]
},
"cpu_ms": {
"median": 1128.214,
"samples": [
1035.19,
1565.383,
1128.214,
1494.36,
1031.198
],
"range": [
1031.198,
1565.383
]
},
"peak_rss_kib": {
"median": 351532,
"samples": [
351624,
350540,
351532,
351716,
350076
]
}
},
"deferred": {
"phase_ms": {
"median": 564.046,
"samples": [
433.35,
665.149,
587.456,
564.046,
497.422
],
"range": [
433.35,
665.149
]
},
"total_ms": {
"median": 1143.129,
"samples": [
885.053,
1143.129,
1195.869,
1074.27,
1162.103
],
"range": [
885.053,
1195.869
]
},
"cpu_ms": {
"median": 1114.261,
"samples": [
910.946,
1128.96,
1194.638,
1114.261,
1073.823
],
"range": [
910.946,
1194.638
]
},
"peak_rss_kib": {
"median": 273776,
"samples": [
274320,
273860,
272548,
273776,
272520
]
}
}
},
"baseline_commit": "e422bd13",
"pr607_commit": "a01d47f2",
"measurement": "same optimized binary, isolated processes in alternating forward/reverse four-mode runs",
"limitations": "Includes Assets::load, BlockFacts, Behaviours; excludes complete client startup, pack/mod root resolution, graphics and first frame. Different modes emulate the original independent, PR #607 at a01d47f2, paired and deferred startup sequences in the same release build. Machine was not idle. Elapsed times show high variance; no statistically established gain between PR, paired and deferred modes."
}
@@ -0,0 +1,453 @@
{
"scope": "Assets + BlockFacts + Behaviours loader only; no full startup or first frame",
"resources": "/srv/bob-data/horizon/.local/horizon-client/26.3",
"repeats": 8,
"ordering": [
[
"cf837118",
"cd61e11b",
"arc-key",
"reused-sounds",
"current"
],
[
"current",
"reused-sounds",
"arc-key",
"cd61e11b",
"cf837118"
],
[
"cf837118",
"cd61e11b",
"arc-key",
"reused-sounds",
"current"
],
[
"current",
"reused-sounds",
"arc-key",
"cd61e11b",
"cf837118"
],
[
"cf837118",
"cd61e11b",
"arc-key",
"reused-sounds",
"current"
],
[
"current",
"reused-sounds",
"arc-key",
"cd61e11b",
"cf837118"
],
[
"cf837118",
"cd61e11b",
"arc-key",
"reused-sounds",
"current"
],
[
"current",
"reused-sounds",
"arc-key",
"cd61e11b",
"cf837118"
]
],
"load_average_before": [
10.9873046875,
8.37646484375,
6.91015625
],
"load_average_after": [
8.6962890625,
8.1591796875,
6.90087890625
],
"executables": {
"cf837118": {
"path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-cf837118",
"mode": "deferred",
"sha256": "f1b044cd9ac2f67c644fb40bd7ecbe38128ec739a8112d57fc36f05fe9036a52"
},
"cd61e11b": {
"path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-cd61e11b",
"mode": "deferred",
"sha256": "fb2d3725b09ee38f85b49901f7053a6fe339b980a2b2dac6930a8ded22c139e8"
},
"arc-key": {
"path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-arcpool",
"mode": "deferred",
"sha256": "8cbb53d01afedf5c7a5da0e36c9f8c3569f34def9bc51488fe8699e7f615a131"
},
"reused-sounds": {
"path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-reusesounds",
"mode": "deferred",
"sha256": "f45794bfbdbb3f9b5d34c375d397191ac67984b3ae91268aa3fdd02f2c1b7b98"
},
"current": {
"path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-new",
"mode": "deferred",
"sha256": "84eb1baae8e138f52e300b0b44f1339fca38e70db6e06126e78db776ea3e5cd0"
}
},
"metrics": {
"cf837118": {
"phase_ms": {
"median": 424.082,
"p25": 417.508,
"p75": 430.923,
"min": 395.439,
"max": 948.609,
"samples": [
948.609,
425.085,
425.571,
417.945,
395.439,
416.197,
423.078,
446.98
]
},
"total_ms": {
"median": 853.026,
"p25": 839.421,
"p75": 867.731,
"min": 813.144,
"max": 1906.081,
"samples": [
1906.081,
861.641,
864.233,
844.411,
813.144,
830.783,
842.3,
878.226
]
},
"cpu_ms": {
"median": 876.143,
"p25": 862.934,
"p75": 891.4,
"min": 837.769,
"max": 1517.372,
"samples": [
1517.372,
885.13,
887.888,
865.404,
837.769,
855.526,
867.157,
901.937
]
},
"peak_rss_kib": {
"median": 273904.0,
"p25": 273717.0,
"p75": 274142.0,
"min": 273648,
"max": 274836,
"samples": [
273648,
273936,
273872,
274836,
274064,
274376,
273740,
273648
]
}
},
"cd61e11b": {
"phase_ms": {
"median": 422.356,
"p25": 406.294,
"p75": 425.846,
"min": 394.111,
"max": 472.536,
"samples": [
425.832,
420.666,
472.536,
425.886,
400.588,
394.111,
424.047,
408.196
]
},
"total_ms": {
"median": 852.475,
"p25": 828.474,
"p75": 876.413,
"min": 817.3,
"max": 951.587,
"samples": [
951.587,
865.442,
899.564,
868.696,
823.74,
817.3,
839.508,
830.052
]
},
"cpu_ms": {
"median": 875.04,
"p25": 850.012,
"p75": 900.57,
"min": 837.672,
"max": 938.285,
"samples": [
938.285,
888.533,
926.846,
891.812,
845.956,
837.672,
861.548,
851.364
]
},
"peak_rss_kib": {
"median": 268086.0,
"p25": 267719.0,
"p75": 268486.0,
"min": 267444,
"max": 268920,
"samples": [
267776,
268660,
267752,
268920,
268428,
268396,
267444,
267620
]
}
},
"arc-key": {
"phase_ms": {
"median": 421.422,
"p25": 401.781,
"p75": 451.774,
"min": 394.041,
"max": 472.337,
"samples": [
446.155,
472.337,
468.632,
420.636,
400.91,
394.041,
422.207,
402.072
]
},
"total_ms": {
"median": 866.601,
"p25": 822.563,
"p75": 918.038,
"min": 817.092,
"max": 1001.287,
"samples": [
1001.287,
918.457,
917.898,
892.666,
817.092,
824.225,
840.536,
817.576
]
},
"cpu_ms": {
"median": 887.84,
"p25": 844.533,
"p75": 937.331,
"min": 838.687,
"max": 991.212,
"samples": [
991.212,
949.048,
933.425,
911.921,
838.687,
845.021,
863.759,
843.069
]
},
"peak_rss_kib": {
"median": 267728.0,
"p25": 267598.0,
"p75": 268039.0,
"min": 267452,
"max": 268636,
"samples": [
268264,
267616,
267840,
267964,
268636,
267452,
267580,
267604
]
}
},
"reused-sounds": {
"phase_ms": {
"median": 421.683,
"p25": 412.913,
"p75": 439.098,
"min": 395.338,
"max": 487.446,
"samples": [
487.446,
434.111,
402.815,
416.279,
424.524,
454.058,
395.338,
418.842
]
},
"total_ms": {
"median": 879.846,
"p25": 845.021,
"p75": 901.166,
"min": 823.721,
"max": 1013.539,
"samples": [
1013.539,
892.033,
928.565,
884.284,
847.853,
875.407,
823.721,
836.527
]
},
"cpu_ms": {
"median": 894.546,
"p25": 871.499,
"p75": 921.844,
"min": 844.891,
"max": 1028.688,
"samples": [
1028.688,
913.48,
946.935,
903.785,
868.684,
885.308,
844.891,
872.438
]
},
"peak_rss_kib": {
"median": 267960.0,
"p25": 267678.0,
"p75": 268133.0,
"min": 267212,
"max": 268404,
"samples": [
267212,
267888,
268404,
267692,
268096,
267636,
268244,
268032
]
}
},
"current": {
"phase_ms": {
"median": 411.403,
"p25": 406.814,
"p75": 452.869,
"min": 391.768,
"max": 532.402,
"samples": [
532.402,
442.563,
408.857,
410.202,
483.788,
391.768,
400.683,
412.604
]
},
"total_ms": {
"median": 905.017,
"p25": 851.488,
"p75": 937.934,
"min": 818.206,
"max": 1075.445,
"samples": [
1075.445,
878.155,
837.627,
955.655,
932.027,
818.206,
856.108,
931.88
]
},
"cpu_ms": {
"median": 922.9,
"p25": 874.849,
"p75": 956.282,
"min": 839.639,
"max": 1067.693,
"samples": [
1067.693,
900.18,
862.137,
970.356,
951.591,
839.639,
879.086,
945.62
]
},
"peak_rss_kib": {
"median": 268354.0,
"p25": 267889.0,
"p75": 268492.0,
"min": 267056,
"max": 268820,
"samples": [
268008,
268384,
268564,
268820,
267056,
267532,
268324,
268468
]
}
}
},
"experiment_note": "Exploratory variants (Arc-key pool, reused sounds, combined proposal) alongside cd61e11b; none gave a robust consistent improvement and all were reverted."
}
@@ -0,0 +1,33 @@
//! Profile the two mandatory passes over gameplay-facts.json independently.
//! Build with `cargo build --release -p horizon-client --example gameplay_decode_profile`.
//! Each invocation runs one phase in a separate process for CPU/RSS measurements.
#[allow(dead_code)]
#[path = "../src/blocks/decode.rs"]
mod decode;
use std::{hint::black_box, path::Path, time::Instant};
// The included private decoder expects the parent crate Result alias.
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn main() -> Result<()> {
let mut args = std::env::args().skip(1);
let root = args.next().ok_or("expected resource directory")?;
let mode = args.next().ok_or("expected validate or typed")?;
if mode != "validate" && mode != "typed" {
return Err("expected validate or typed".into());
}
let total = Instant::now();
let bytes = std::fs::read(Path::new(&root).join("gameplay-facts.json"))?;
let started = Instant::now();
if mode == "validate" {
let parsed: decode::Validate = serde_json::from_slice(&bytes)?;
black_box(parsed);
} else {
let parsed: decode::Gameplay<'_> = serde_json::from_slice(&bytes)?;
black_box(parsed);
}
println!("phase_ms={:.3}", started.elapsed().as_secs_f64() * 1000.0);
println!("total_ms={:.3}", total.elapsed().as_secs_f64() * 1000.0);
Ok(())
}
@@ -0,0 +1,74 @@
//! Profile the fact and behaviour table phase of client startup.
//! Run each mode in a separate process to capture CPU usage and peak RSS.
//! The deferred mode evaluates both phases contiguously for fair loader comparison;
//! actual client startup performs other initialization between these phases.
use horizon_client::{assets::Assets, blocks::BlockFacts};
use horizon_world::level::Behaviours;
use std::{path::Path, time::Instant};
fn resident_kib() -> Option<u64> {
let status = std::fs::read_to_string("/proc/self/status").ok()?;
let line = status.lines().find(|line| line.starts_with("VmRSS:"))?;
line.split_whitespace().nth(1)?.parse().ok()
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = std::env::args().skip(1);
let root = args.next().ok_or("expected resource directory")?;
let mode = args
.next()
.ok_or("expected baseline, pr607, shared, deferred or deferred-held")?;
if !["baseline", "pr607", "shared", "deferred", "deferred-held"].contains(&mode.as_str()) {
return Err("expected baseline, pr607, shared, deferred or deferred-held".into());
}
let root = Path::new(&root);
let total = Instant::now();
let assets = Assets::load(root)?;
let started = Instant::now();
let mut retained_inputs = None;
let mut subphases = None;
let (facts, behaviours) = if mode == "baseline" {
(
BlockFacts::load(root, assets.registry)?,
Behaviours::load(assets.registry, root)?,
)
} else if mode == "pr607" {
// Original PR #607 sequence at a01d47f2, retained as a same-build comparator.
let json: serde_json::Value = serde_json::from_reader(std::io::BufReader::new(
std::fs::File::open(root.join("block-behaviours.json"))?,
))?;
BlockFacts::load_with_behaviours(root, assets.registry, &json)?
} else if mode == "shared" {
BlockFacts::load_pair(root, assets.registry)?
} else {
let parse_started = Instant::now();
let json: serde_json::Value = serde_json::from_reader(std::io::BufReader::new(
std::fs::File::open(root.join("block-behaviours.json"))?,
))?;
let parse_ms = parse_started.elapsed().as_secs_f64() * 1000.0;
let facts_started = Instant::now();
let (facts, gameplay) = BlockFacts::load_with_projection(root, assets.registry, &json)?;
let facts_ms = facts_started.elapsed().as_secs_f64() * 1000.0;
let behaviours_started = Instant::now();
let behaviours = Behaviours::load_with_gameplay(assets.registry, root, &json, &gameplay)?;
let behaviours_ms = behaviours_started.elapsed().as_secs_f64() * 1000.0;
subphases = Some((parse_ms, facts_ms, behaviours_ms));
if mode == "deferred-held" {
retained_inputs = Some((json, gameplay));
}
(facts, behaviours)
};
println!("phase_ms={:.3}", started.elapsed().as_secs_f64() * 1000.0);
println!("total_ms={:.3}", total.elapsed().as_secs_f64() * 1000.0);
println!("states={}", facts.states.len());
if let Some((parse, facts, behaviours)) = subphases {
println!("behaviour_json_ms={parse:.3}");
println!("facts_ms={facts:.3}");
println!("behaviours_ms={behaviours:.3}");
}
if let Some(rss) = resident_kib() {
println!("post_rss_kib={rss}");
}
std::hint::black_box((facts, behaviours, retained_inputs));
Ok(())
}
@@ -0,0 +1,47 @@
//! Transport for the vanilla quad sorting / viewpoint parity gate.
use horizon_client::gfx::translucency::{SortState, Sorter, quad_center};
use serde::Deserialize;
use serde_json::json;
use std::{
fs,
io::{BufWriter, Write},
};
#[derive(Deserialize)]
struct Case {
origin: [i32; 3],
quads: Vec<[[f32; 3]; 4]>,
cameras: Vec<[f64; 3]>,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().skip(1).collect();
let [input, output] = args.as_slice() else {
return Err("usage: translucency_fixture INPUT OUTPUT".into());
};
let mut out = BufWriter::new(fs::File::create(output)?);
for line in fs::read_to_string(input)?.lines() {
let case: Case = serde_json::from_str(line)?;
let centers: Vec<_> = case.quads.iter().map(|q| quad_center(q[0], q[2])).collect();
let mut state = SortState::new(centers.clone());
let mut sorter = Sorter::default();
let mut cache_sorter = Sorter::default();
let frames: Vec<_> = case
.cameras
.iter()
.map(|&camera| {
let update = state
.update(camera, case.origin, &mut cache_sorter)
.is_some();
let local = std::array::from_fn(|i| (camera[i] - f64::from(case.origin[i])) as f32);
json!({"indices": sorter.sort(&centers, local), "update": update})
})
.collect();
let bits: Vec<_> = centers
.iter()
.map(|c| c.map(|f| f.to_bits() as i32))
.collect();
writeln!(out, "{}", json!({"centers": bits, "frames": frames}))?;
}
Ok(())
}
+236 -13
View File
@@ -2,7 +2,10 @@
//! (`gameplay-facts.json`), indexed by registry state ID.
mod decode;
use crate::Result;
use horizon_world::registry::{BlockRegistry, BlockStateId};
use horizon_world::{
level::{Behaviours, GameplayStateSource},
registry::{BlockRegistry, BlockStateId},
};
use serde_json::Value;
use std::{
collections::HashMap,
@@ -107,12 +110,178 @@ impl StateFacts {
self.classes.iter().any(|c| &**c == name)
}
}
/// Compact, owned behaviour inputs retained until the normal behaviour startup stage.
/// No borrowed gameplay JSON or process-wide cache survives the fact loader.
pub struct GameplayProjection {
flags: u16,
emission: u64,
dampening: u64,
hardness: f64,
push: Arc<str>,
volume: f64,
pitch: f64,
place: Arc<str>,
break_sound: Arc<str>,
fall: Arc<str>,
}
impl GameplayProjection {
fn from_entry(entry: &decode::Entry<'_>, strings: &mut HashMap<String, Arc<str>>) -> Self {
fn intern(strings: &mut HashMap<String, Arc<str>>, value: &str) -> Arc<str> {
if let Some(existing) = strings.get(value) {
return Arc::clone(existing);
}
let value_arc: Arc<str> = Arc::from(value);
strings.insert(value.to_owned(), Arc::clone(&value_arc));
value_arc
}
const FLAGS: [&str; 11] = [
"replaceable",
"random_ticks",
"solid_render",
"liquid",
"block_entity",
"ignited_by_lava",
"can_occlude",
"full_collision",
"skylight_down",
"requires_tool",
"shape_occlusion",
];
Self {
flags: FLAGS.iter().enumerate().fold(0, |flags, (i, name)| {
flags | ((u16::from(entry.flag(name))) << i)
}),
emission: entry.unsigned("emission"),
dampening: entry.unsigned("dampening"),
hardness: entry.number("hardness"),
push: intern(strings, entry.text("push")),
volume: entry.sound_number("volume"),
pitch: entry.sound_number("pitch"),
place: intern(strings, entry.sound_id("place")),
break_sound: intern(strings, entry.sound_id("break")),
fall: intern(strings, entry.sound_id("fall")),
}
}
}
impl GameplayStateSource for GameplayProjection {
fn flag(&self, name: &str) -> bool {
const FLAGS: [&str; 11] = [
"replaceable",
"random_ticks",
"solid_render",
"liquid",
"block_entity",
"ignited_by_lava",
"can_occlude",
"full_collision",
"skylight_down",
"requires_tool",
"shape_occlusion",
];
FLAGS
.iter()
.position(|field| *field == name)
.is_some_and(|index| self.flags & (1 << index) != 0)
}
fn unsigned(&self, name: &str) -> u64 {
match name {
"emission" => self.emission,
"dampening" => self.dampening,
_ => 0,
}
}
fn number(&self, name: &str) -> f64 {
if name == "hardness" {
self.hardness
} else {
0.0
}
}
fn text(&self, name: &str) -> &str {
if name == "push" { &self.push } else { "" }
}
fn sound_number(&self, name: &str) -> f64 {
match name {
"volume" => self.volume,
"pitch" => self.pitch,
_ => 1.0,
}
}
fn sound_id(&self, name: &str) -> &str {
match name {
"place" => &self.place,
"break" => &self.break_sound,
"fall" => &self.fall,
_ => "",
}
}
}
pub struct BlockFacts {
pub states: Vec<StateFacts>,
pub air: BlockStateId,
}
impl BlockFacts {
pub fn load(root: &Path, registry: &BlockRegistry) -> Result<Self> {
let behaviours: Value = serde_json::from_reader(BufReader::new(File::open(
root.join("block-behaviours.json"),
)?))?;
Self::load_with_behaviour_json(root, registry, &behaviours)
}
/// Load both tables from one resource root, sharing each JSON decode.
/// No data is cached across calls: changes to prepared packs or mods are read again.
pub fn load_pair(root: &Path, registry: &BlockRegistry) -> Result<(Self, Behaviours)> {
let behaviours: Value = serde_json::from_reader(BufReader::new(File::open(
root.join("block-behaviours.json"),
)?))?;
Self::load_with_behaviours(root, registry, &behaviours)
}
/// Decode state facts once, retaining only the small owned fields needed later.
pub fn load_with_projection(
root: &Path,
registry: &BlockRegistry,
behaviours: &Value,
) -> Result<(Self, Vec<GameplayProjection>)> {
Self::load_with_callback(root, registry, behaviours, |entries| {
let mut strings = HashMap::new();
Ok(entries
.iter()
.map(|entry| GameplayProjection::from_entry(entry, &mut strings))
.collect())
})
}
pub fn load_with_behaviour_json(
root: &Path,
registry: &BlockRegistry,
behaviours: &Value,
) -> Result<Self> {
Ok(Self::load_with_callback(root, registry, behaviours, |_| Ok(()))?.0)
}
/// Build both tables from the same behaviour document and gameplay decoder.
pub fn load_with_behaviours(
root: &Path,
registry: &BlockRegistry,
behaviours: &Value,
) -> Result<(Self, Behaviours)> {
Self::load_with_callback(root, registry, behaviours, |entries| {
Ok(Behaviours::load_with_gameplay(
registry, root, behaviours, entries,
)?)
})
}
fn load_with_callback<T>(
root: &Path,
registry: &BlockRegistry,
behaviours: &Value,
callback: impl FnOnce(&[decode::Entry<'_>]) -> Result<T>,
) -> Result<(Self, T)> {
let bytes = fs::read(root.join("gameplay-facts.json"))?;
serde_json::from_slice::<decode::Validate>(&bytes)?;
let raw: decode::Gameplay<'_> = serde_json::from_slice(&bytes)?;
@@ -125,9 +294,6 @@ impl BlockFacts {
return Err("gameplay facts do not match the block registry".into());
}
// Class chains and per-state behaviour flags exported from the actual block objects.
let behaviours: Value = serde_json::from_reader(BufReader::new(File::open(
root.join("block-behaviours.json"),
)?))?;
let behaviour_states = behaviours["states"]
.as_array()
.filter(|s| s.len() == registry.len())
@@ -221,13 +387,13 @@ impl BlockFacts {
outline,
outline_edges,
name: intern(&state.name),
emission: entry.emission as u8,
dampening: entry.dampening as u8,
emission: entry.emission.as_f64().unwrap_or(0.0) as u8,
dampening: entry.dampening.as_f64().unwrap_or(0.0) as u8,
skylight_down: entry.skylight_down,
shape_occlusion: entry.shape_occlusion,
can_occlude: entry.can_occlude,
solid_render: entry.solid_render,
hardness: entry.hardness as f32,
hardness: entry.hardness.as_f64().unwrap_or(0.0) as f32,
requires_tool: entry.requires_tool,
replaceable: entry.replaceable,
random_ticks: entry.random_ticks,
@@ -264,12 +430,16 @@ impl BlockFacts {
.ok_or("missing block behaviour class chain")?,
});
}
Ok(Self {
states,
air: registry
.default_state("minecraft:air")
.ok_or("missing air")?,
})
let extra = callback(entries)?;
Ok((
Self {
states,
air: registry
.default_state("minecraft:air")
.ok_or("missing air")?,
},
extra,
))
}
pub fn get(&self, id: BlockStateId) -> &StateFacts {
&self.states[id.0 as usize]
@@ -281,3 +451,56 @@ impl BlockFacts {
)
}
}
impl GameplayStateSource for decode::Entry<'_> {
fn flag(&self, name: &str) -> bool {
match name {
"replaceable" => self.replaceable,
"random_ticks" => self.random_ticks,
"solid_render" => self.solid_render,
"liquid" => self.liquid,
"block_entity" => self.block_entity,
"ignited_by_lava" => self.ignited_by_lava,
"can_occlude" => self.can_occlude,
"full_collision" => self.full_collision,
"skylight_down" => self.skylight_down,
"requires_tool" => self.requires_tool,
"shape_occlusion" => self.shape_occlusion,
_ => false,
}
}
fn unsigned(&self, name: &str) -> u64 {
match name {
"emission" => self.emission.as_u64().unwrap_or(0),
"dampening" => self.dampening.as_u64().unwrap_or(0),
_ => 0,
}
}
fn number(&self, name: &str) -> f64 {
match name {
"hardness" => self.hardness.as_f64().unwrap_or(0.0),
_ => 0.0,
}
}
fn text(&self, name: &str) -> &str {
match name {
"push" => self.push.as_deref().unwrap_or(""),
_ => "",
}
}
fn sound_number(&self, name: &str) -> f64 {
match name {
"volume" => self.sound.volume,
"pitch" => self.sound.pitch,
_ => 1.0,
}
}
fn sound_id(&self, name: &str) -> &str {
match name {
"place" => self.sound.place.id.as_deref().unwrap_or(""),
"break" => self.sound.r#break.id.as_deref().unwrap_or(""),
"fall" => self.sound.fall.id.as_deref().unwrap_or(""),
_ => "",
}
}
}
+6 -3
View File
@@ -155,17 +155,20 @@ object!(Sound<'a> {
});
object!(Entry<'a> {
id: Option<u64> = None => value(unsigned),
emission: f64 = 0.0 => value(number),
dampening: f64 = 0.0 => value(number),
emission: Value = Value::Null => typed,
dampening: Value = Value::Null => typed,
skylight_down: bool = false => value(flag),
shape_occlusion: bool = false => value(flag),
can_occlude: bool = false => value(flag),
solid_render: bool = false => value(flag),
hardness: f64 = 0.0 => value(number),
hardness: Value = Value::Null => typed,
requires_tool: bool = false => value(flag),
replaceable: bool = false => value(flag),
random_ticks: bool = false => value(flag),
block_entity: bool = false => value(flag),
liquid: bool = false => value(flag),
ignited_by_lava: bool = false => value(flag),
push: Option<String> = None => value(text),
render_shape: Option<String> = None => value(text),
full_collision: bool = false => value(flag),
friction: f64 = 0.0 => value(number),
@@ -89,9 +89,9 @@ fn typed_fields_keep_defaults_duplicates_and_wrong_type_behavior() -> crate::Res
assert_eq!(entries[1].id, None);
let e = &entries[2];
assert_eq!(e.id, Some(2));
assert_eq!(e.emission, 4.5);
assert_eq!(e.dampening, 0.0);
assert_eq!(e.hardness.to_bits(), (-0.0f64).to_bits());
assert_eq!(e.emission.as_f64(), Some(4.5));
assert_eq!(e.dampening.as_f64().unwrap_or(0.0), 0.0);
assert_eq!(e.hardness.as_f64().unwrap().to_bits(), (-0.0f64).to_bits());
assert!(e.skylight_down && e.outline_offset.unwrap_or(e.offset));
assert_eq!(e.item, None);
assert_eq!(e.render_shape, None);
+43 -3
View File
@@ -3104,6 +3104,7 @@ impl Game<'_> {
self.eye = 1.62;
self.previous_eye = 1.62;
self.clock.reset();
self.capture_loaded_world();
Ok(())
}
fn tick(&mut self) -> Result<()> {
@@ -3661,6 +3662,10 @@ impl Game<'_> {
) || self.book.is_some())
}
fn capture(&mut self, capture: bool) {
// MouseHandler.grabMouse never captures an inactive window.
if capture && !self.focused {
return;
}
if !capture {
self.stop_mining();
}
@@ -3679,6 +3684,16 @@ impl Game<'_> {
}
window.set_cursor_visible(!self.captured);
}
/// LevelLoadingScreen.onClose -> Gui.setScreen(null) -> grabMouse.
fn capture_loaded_world(&mut self) {
// Loading may finish after focus was lost or another screen opened.
if self.title.is_none()
&& self.screen == Screen::Playing
&& !self.remote.as_ref().is_some_and(|r| r.chat_input.is_some())
{
self.capture(true);
}
}
fn draw_item(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) {
// `GuiGraphics.renderItem`: the resolved item model (tints, foil and
// special renderers included), then the decorations.
@@ -8460,12 +8475,23 @@ impl Game<'_> {
let debug_lines = horizon_client::gizmos::camera_relative(&lines, at, view);
let debug_lines_on_top = horizon_client::gizmos::camera_relative(&on_top, at, view);
let debug_crosshair = horizon_client::gizmos::camera_relative(&crosshair.on_top, at, view);
// LevelRenderer.renderHitOutline: the outline shape's edges.
// LevelExtractor.extractBlockOutline: model translucency controls draw order.
let mut outline_after_terrain = false;
let outline = if self.screen == Screen::Playing && !self.spectator() {
self.pick()
.map(|h| {
let state = self.world.block(h.pos[0], h.pos[1], h.pos[2]);
let f = self.res.facts.get(state);
outline_after_terrain = self
.pack
.assets
.model_catalog
.collect(state, BlockPos::new(h.pos[0], h.pos[1], h.pos[2]))
.is_ok_and(|models| {
models
.iter()
.any(|(_, model)| model.faces.iter().any(|f| f.translucent))
});
let o = if f.outline_offset {
self.pack
.context
@@ -8615,6 +8641,7 @@ impl Game<'_> {
}),
dark_disc: self.dark_disc(camera),
outline,
outline_after_terrain,
debug_lines: &debug_lines,
debug_lines_on_top: &debug_lines_on_top,
debug_crosshair: &debug_crosshair,
@@ -10222,7 +10249,11 @@ pub fn run() -> Result<()> {
let root = options.resources.clone();
let assets = Arc::new(assets);
log::info!("load assets: {:.2}s", started.elapsed().as_secs_f32());
let facts = BlockFacts::load(&root, assets.registry)?;
let behaviour_json: serde_json::Value = serde_json::from_reader(std::io::BufReader::new(
std::fs::File::open(root.join("block-behaviours.json"))?,
))?;
let (facts, gameplay_projection) =
BlockFacts::load_with_projection(&root, assets.registry, &behaviour_json)?;
let mob_data = horizon_client::mobs::MobData::load(&root, &facts);
horizon_client::mobs::trial_spawner::load_registry(&root);
log::info!("load facts: {:.2}s", started.elapsed().as_secs_f32());
@@ -10289,7 +10320,12 @@ pub fn run() -> Result<()> {
ambient: horizon_client::ambience::AmbientTables::load(&root),
nether_environment: Environment::load_dimension(&root, "the_nether", false)?,
end_environment: Environment::load_dimension(&root, "the_end", false)?,
behaviours: Behaviours::load(registry_owner.registry, &root)?,
behaviours: Behaviours::load_with_gameplay(
registry_owner.registry,
&root,
&behaviour_json,
&gameplay_projection,
)?,
mob_types: MobTypes::load(&root)?
.types
.into_iter()
@@ -10301,6 +10337,10 @@ pub fn run() -> Result<()> {
player_arm: horizon_client::mobs::load_model(&root, "minecraft:player#main")
.and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")),
});
// Both inputs are needed only while constructing the behaviour tables.
// Release their owned JSON/Arc buffers before entering the long-lived game loop.
drop(gameplay_projection);
drop(behaviour_json);
let mut settings = Settings::load(&std::env::current_dir()?.join("options.txt"));
horizon_client::ui_theme::load_preferences(&std::env::current_dir()?);
// Scripted and frame-limited runs (the parity harnesses) see vanilla's
+1
View File
@@ -1918,6 +1918,7 @@ impl Game<'_> {
if let Some(r) = self.remote.as_mut() {
r.loaded_sent = true;
}
self.capture_loaded_world();
}
let stick = self.pad_move();
let Some(player) = self.player.as_mut() else {
+87 -14
View File
@@ -64,6 +64,7 @@ mod pack_stages;
pub mod panorama;
mod resident;
mod timing;
pub mod translucency;
pub(crate) mod upload;
mod world_post;
@@ -98,6 +99,8 @@ struct SectionGpu {
translucent: u32,
/// The solid quads by facing: back-facing groups are skipped.
faces: crate::mesher::FaceGroups,
sort: translucency::SortState,
sorted_indices: Option<(u32, u64)>,
}
/// Line segments the hit outline can hold.
const MAX_OUTLINE_EDGES: u64 = 256;
@@ -133,6 +136,8 @@ pub struct Frame<'a> {
pub dark_disc: bool,
/// The hit block outline as line segments (from, to) in world space.
pub outline: Vec<[f64; 6]>,
/// `BlockOutlineRenderState.isTranslucent`: draw after translucent terrain.
pub outline_after_terrain: bool,
/// `lines` with a colour and pixel width (`gizmos::camera_relative`):
/// the fishing line and debug gizmos, depth tested, then gizmos drawn
/// over everything.
@@ -318,6 +323,9 @@ pub struct Renderer {
depth: wgpu::TextureView,
sections: resident::Resident<SectionGpu>,
arena: arena::Arena,
sorted_indices: arena::Arena,
translucent_sorter: translucency::Sorter,
translucency_cursor: usize,
/// `DrawIndexedIndirectArgs` for this frame's solid then translucent draws.
indirect: wgpu::Buffer,
indirect_capacity: u64,
@@ -329,8 +337,8 @@ pub struct Renderer {
/// `DrawIndexedIndirectArgs` words: index count, instance count, first
/// index, base vertex, first instance.
draws: Vec<[u32; 5]>,
/// The arena page of each of `draws`.
draw_pages: Vec<u32>,
/// Vertex arena page and optional sorted index arena page of each draw.
draw_pages: Vec<(u32, Option<u32>)>,
/// Block-entity blocks per meshed section (world position, state id).
block_entities: HashMap<SectionKey, Vec<([i32; 3], u32)>>,
/// VisGraph face connectivity per meshed section (cave culling).
@@ -836,7 +844,7 @@ impl Renderer {
&terrain_buffers,
tri,
Some(wgpu::Face::Back),
false,
true,
true,
Some(alpha_blend),
);
@@ -869,7 +877,7 @@ impl Renderer {
&line_buffers,
wgpu::PrimitiveTopology::TriangleStrip,
None,
false,
true,
true,
Some(alpha_blend),
);
@@ -1633,6 +1641,7 @@ impl Renderer {
std::mem::size_of::<TerrainVertex>() as u64,
1 << 20,
);
let sorted_indices = arena::Arena::indices(&device, 1 << 16);
let indirect = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Section draws"),
size: 1024 * 20,
@@ -1726,6 +1735,9 @@ impl Renderer {
depth,
sections: resident::Resident::default(),
arena,
sorted_indices,
translucent_sorter: translucency::Sorter::default(),
translucency_cursor: 0,
indirect,
indirect_capacity: 1024,
multi_draw,
@@ -1910,6 +1922,10 @@ impl Renderer {
}
let vertices = (mesh.solid.len() + mesh.translucent.len()) as u64;
let (page, start) = self.arena.alloc(&self.device, &self.queue, vertices);
let sorted_indices = (translucent > 0).then(|| {
self.sorted_indices
.alloc(&self.device, &self.queue, u64::from(translucent) * 6)
});
let stride = std::mem::size_of::<TerrainVertex>() as u64;
for (offset, part) in [(0, &mesh.solid), (mesh.solid.len(), &mesh.translucent)] {
if !part.is_empty() {
@@ -1930,6 +1946,15 @@ impl Renderer {
solid,
translucent,
faces: mesh.faces,
sort: translucency::SortState::new(
mesh.translucent
.as_chunks::<4>()
.0
.iter()
.map(|q| translucency::quad_center(q[0].pos, q[2].pos))
.collect(),
),
sorted_indices,
},
);
}
@@ -1940,17 +1965,19 @@ impl Renderer {
fn draw_sections(&self, pass: &mut wgpu::RenderPass<'_>, first: u32, count: u32) {
let (mut i, end) = (first as usize, (first + count) as usize);
while i < end {
let page = self.draw_pages[i];
let (page, index_page) = self.draw_pages[i];
let run = self.draw_pages[i..end]
.iter()
.take_while(|&&p| p == page)
.take_while(|&&p| p == (page, index_page))
.count();
pass.set_vertex_buffer(0, self.arena.buffer(page).slice(..));
let indices = index_page.map_or(&self.indices, |p| self.sorted_indices.buffer(p));
pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32);
if self.multi_draw {
pass.multi_draw_indexed_indirect(&self.indirect, i as u64 * 20, run as u32);
} else {
for d in &self.draws[i..i + run] {
pass.draw_indexed(0..d[0], d[3] as i32, d[4]..d[4] + 1);
pass.draw_indexed(d[2]..d[2] + d[0], d[3] as i32, d[4]..d[4] + 1);
}
}
i += run;
@@ -1958,6 +1985,10 @@ impl Renderer {
}
fn release_section(&mut self, key: SectionKey) {
if let Some(s) = self.sections.remove(key) {
if let Some((page, start)) = s.sorted_indices {
self.sorted_indices
.release(page, start, u64::from(s.translucent) * 6);
}
self.arena
.release(s.page, s.start, u64::from(s.solid + s.translucent) * 4);
}
@@ -1970,6 +2001,8 @@ impl Renderer {
self.block_entities.clear();
self.sections.clear();
self.arena.clear();
self.sorted_indices.clear();
self.translucency_cursor = 0;
self.occlusion.clear();
}
pub fn remove(&mut self, key: SectionKey) {
@@ -2391,19 +2424,51 @@ impl Renderer {
s.faces.ranges(eye - Vec3::from(v.origin), |first, quads| {
let first = s.start + u64::from(first) * 4;
self.draws.push([quads * 6, 1, 0, first as u32, i as u32]);
self.draw_pages.push(s.page);
self.draw_pages.push((s.page, None));
});
}
let solid_draws = self.draws.len() as u32;
// LevelRenderer: nearby sections each frame, plus a rotating eighth
// (at least 15) of the visible list. Cached views avoid needless sorts.
let count = visible.len();
let budget = (count / 8).max(15).min(count);
self.translucency_cursor %= count.max(1);
for (i, v) in visible.iter().enumerate().rev() {
let s = self.sections.get(v.slot);
if s.translucent > 0 {
let s = self.sections.get_mut(v.slot);
if let Some((index_page, index_start)) = s.sorted_indices {
let nearby = (v.key.0 - camera_section.0).abs() <= 2
&& (v.key.1 - camera_section.1).abs() <= 2
&& (v.key.2 - camera_section.2).abs() <= 2;
let scheduled = (i + count - self.translucency_cursor) % count < budget;
let origin = [
v.key.0 * 16,
crate::chunk::MIN_Y + v.key.1 * 16,
v.key.2 * 16,
];
if (!s.sort.is_sorted() || nearby || scheduled)
&& let Some(indices) =
s.sort
.update(camera.to_array(), origin, &mut self.translucent_sorter)
{
self.uploads.buffer(
&mut encoder,
self.sorted_indices.buffer(index_page),
index_start * 4,
bytemuck::cast_slice(indices),
);
}
let first = s.start + u64::from(s.solid) * 4;
self.draws
.push([s.translucent * 6, 1, 0, first as u32, i as u32]);
self.draw_pages.push(s.page);
self.draws.push([
s.translucent * 6,
1,
index_start as u32,
first as u32,
i as u32,
]);
self.draw_pages.push((s.page, Some(index_page)));
}
}
self.translucency_cursor += budget;
let translucent_draws = self.draws.len() as u32 - solid_draws;
if self.multi_draw && !self.draws.is_empty() {
if self.draws.len() as u64 > self.indirect_capacity {
@@ -2665,7 +2730,7 @@ impl Renderer {
pass.draw_indexed(0..additive_quads * 6, (world_quads * 4) as i32, 0..1);
pass.set_bind_group(0, &self.group, &[]);
}
if outline_edges > 0 {
if outline_edges > 0 && !frame.outline_after_terrain {
pass.set_pipeline(&self.lines);
pass.set_vertex_buffer(0, self.outline.slice(..));
pass.draw(0..4, 0..outline_edges as u32);
@@ -2684,6 +2749,14 @@ impl Renderer {
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
pass.set_vertex_buffer(1, self.instances.slice(..));
self.draw_sections(&mut pass, solid_draws, translucent_draws);
// LevelRenderer.executeClassicTransparency: translucent targets'
// outlines follow terrain, so its blending cannot wash them out.
if outline_edges > 0 && frame.outline_after_terrain {
pass.set_pipeline(&self.lines);
pass.set_vertex_buffer(0, self.outline.slice(..));
pass.draw(0..4, 0..outline_edges as u32);
}
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
// LevelRenderer: the world border after translucent terrain and weather.
if let Some(b) = frame.border.as_ref().filter(|_| !frame.title) {
pass.set_pipeline(&self.border_pipeline);
+24 -8
View File
@@ -52,31 +52,47 @@ pub struct Arena {
pages: Vec<Page>,
stride: u64,
page_limit: u64,
usage: wgpu::BufferUsages,
}
impl Arena {
pub fn new(device: &wgpu::Device, stride: u64, capacity: u64) -> Self {
Self::with_usage(device, stride, capacity, wgpu::BufferUsages::VERTEX)
}
pub fn indices(device: &wgpu::Device, capacity: u64) -> Self {
Self::with_usage(device, 4, capacity, wgpu::BufferUsages::INDEX)
}
fn with_usage(
device: &wgpu::Device,
stride: u64,
capacity: u64,
usage: wgpu::BufferUsages,
) -> Self {
// 256 MiB pages, or less where the device's buffers are smaller.
let bytes = device.limits().max_buffer_size.min(256 << 20);
let page_limit = (bytes / stride) / GRAIN * GRAIN;
let capacity = capacity.next_multiple_of(GRAIN).min(page_limit);
Self {
pages: vec![Page {
buffer: Self::create(device, stride, capacity),
buffer: Self::create(device, stride, capacity, usage),
capacity,
free: FreeList::new(capacity),
}],
stride,
page_limit,
usage,
}
}
fn create(device: &wgpu::Device, stride: u64, capacity: u64) -> wgpu::Buffer {
fn create(
device: &wgpu::Device,
stride: u64,
capacity: u64,
usage: wgpu::BufferUsages,
) -> wgpu::Buffer {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Section vertex arena"),
label: Some("Section buffer arena"),
size: capacity * stride,
usage: wgpu::BufferUsages::VERTEX
| wgpu::BufferUsages::COPY_DST
| wgpu::BufferUsages::COPY_SRC,
usage: usage | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
})
}
@@ -121,7 +137,7 @@ impl Arena {
let mut free = FreeList::new(capacity);
let start = free.take(len).expect("a new page fits one section");
self.pages.push(Page {
buffer: Self::create(device, self.stride, capacity),
buffer: Self::create(device, self.stride, capacity, self.usage),
capacity,
free,
});
@@ -133,7 +149,7 @@ impl Arena {
}
fn grow(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, page: usize, capacity: u64) {
let capacity = capacity.next_multiple_of(GRAIN).min(self.page_limit);
let buffer = Self::create(device, self.stride, capacity);
let buffer = Self::create(device, self.stride, capacity, self.usage);
let old = &mut self.pages[page];
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Grow section arena"),
@@ -58,6 +58,9 @@ impl<T> Resident<T> {
pub fn get(&self, slot: u32) -> &T {
&self.items[slot as usize].1
}
pub fn get_mut(&mut self, slot: u32) -> &mut T {
&mut self.items[slot as usize].1
}
pub fn clear(&mut self) {
self.items.clear();
self.slots.clear();
@@ -0,0 +1,119 @@
//! Vanilla 26.3 MeshData.SortState / VertexSorting.byDistance.
//! Keep vertex order intact; only the quad indices change as the camera moves.
/// MeshData.decodeQuadCentroids uses the opposite corners, not all four vertices.
pub fn quad_center(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
std::array::from_fn(|i| (a[i] + b[i]) / 2.0)
}
#[derive(Default)]
pub struct Sorter {
order: Vec<(u32, f32)>,
indices: Vec<u32>,
}
impl Sorter {
pub fn sort(&mut self, centers: &[[f32; 3]], camera: [f32; 3]) -> &[u32] {
self.order.clear();
self.order.extend(centers.iter().enumerate().map(|(i, c)| {
let [x, y, z] = std::array::from_fn(|j| camera[j] - c[j]);
(i as u32, x * x + y * y + z * z)
}));
// VertexSorting uses a stable merge sort, preserving mesh order for ties.
self.order.sort_by(|a, b| b.1.total_cmp(&a.1));
self.indices.clear();
for &(quad, _) in &self.order {
let v = quad * 4;
self.indices.extend([v, v + 1, v + 2, v + 2, v + 3, v]);
}
&self.indices
}
}
pub struct SortState {
centers: Vec<[f32; 3]>,
last: Option<([i32; 3], [i32; 3])>,
}
impl SortState {
pub fn new(centers: Vec<[f32; 3]>) -> Self {
Self {
centers,
last: None,
}
}
pub fn is_sorted(&self) -> bool {
self.last.is_some()
}
/// TranslucencyPointOfView and ResortTransparencyTask: diagonal views keep
/// their ordering until the point of view changes; aligned views also
/// resort on crossing a block boundary. Sub-block movement needs no upload.
pub fn update<'a>(
&mut self,
camera: [f64; 3],
origin: [i32; 3],
sorter: &'a mut Sorter,
) -> Option<&'a [u32]> {
let block = camera.map(|v| v.floor() as i32);
let pov = std::array::from_fn(|i| ((block[i] >> 4) - (origin[i] >> 4)).clamp(-1, 1));
if let Some((last_block, last_pov)) = self.last
&& last_pov == pov
&& (last_block == block || !pov.contains(&0))
{
return None;
}
self.last = Some((block, pov));
Some(sorter.sort(
&self.centers,
std::array::from_fn(|i| (camera[i] - f64::from(origin[i])) as f32),
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn equal_distances_keep_mesh_order_and_triangle_winding() {
let mut sorter = Sorter::default();
assert_eq!(
sorter.sort(
&[[1.0, 0.0, 0.0], [-1.0, 0.0, 0.0], [4.0, 0.0, 0.0]],
[0.0; 3]
),
&[8, 9, 10, 10, 11, 8, 0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4]
);
assert!(sorter.sort(&[], [0.0; 3]).is_empty());
}
#[test]
fn movement_reverses_faces_without_moving_vertices() {
let centers = [[0.5, 0.5, 0.0], [0.5, 0.5, 1.0]];
let mut sorter = Sorter::default();
assert_eq!(sorter.sort(&centers, [0.5, 0.5, -2.0])[0], 4);
assert_eq!(sorter.sort(&centers, [0.5, 0.5, 3.0])[0], 0);
}
#[test]
fn cached_viewpoint_handles_negative_and_large_coordinates() {
let origin = [-30_000_000, -64, 30_000_000];
let mut state = SortState::new(vec![[0.5; 3]]);
let mut sorter = Sorter::default();
let camera = [-29_999_999.5, -63.5, 30_000_000.5];
assert!(state.update(camera, origin, &mut sorter).is_some());
assert!(state.update(camera, origin, &mut sorter).is_none());
assert!(
state
.update([-29_999_999.1, -63.1, 30_000_000.9], origin, &mut sorter)
.is_none()
);
assert!(
state
.update([-29_999_998.9, -63.1, 30_000_000.9], origin, &mut sorter)
.is_some()
);
}
}
+228 -2
View File
@@ -49,8 +49,13 @@ fn tags_merge_without_repeats() {
}
fn prepared() -> Option<PathBuf> {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
root.join("gameplay-facts.json").exists().then_some(root)
let manifest = Path::new(env!("CARGO_MANIFEST_DIR"));
[
manifest.join("../../.local/horizon-client/26.3"),
manifest.join("../../../../.local/horizon-client/26.3"),
]
.into_iter()
.find(|root| root.join("gameplay-facts.json").exists())
}
/// A content mod folder: a full block, a door and an item-less glass from
@@ -146,6 +151,46 @@ fn content_root_loads_with_every_table() {
let old_facts = BlockFacts::load(&base, old).unwrap();
let facts = BlockFacts::load(&root, new).unwrap();
let shared_json: serde_json::Value = serde_json::from_reader(std::io::BufReader::new(
fs::File::open(root.join("block-behaviours.json")).unwrap(),
))
.unwrap();
let (shared_facts, shared_behaviours) =
BlockFacts::load_with_behaviours(&root, new, &shared_json).unwrap();
let independent_behaviours = horizon_world::level::Behaviours::load(new, &root).unwrap();
let (deferred_facts, gameplay) =
BlockFacts::load_with_projection(&root, new, &shared_json).unwrap();
let deferred_behaviours =
horizon_world::level::Behaviours::load_with_gameplay(new, &root, &shared_json, &gameplay)
.unwrap();
assert_eq!(shared_facts.states.len(), facts.states.len());
for state in [ruby, ruby_door, BlockStateId(n + 65)] {
assert_eq!(shared_facts.get(state).hardness, facts.get(state).hardness);
assert_eq!(
deferred_facts.get(state).hardness,
facts.get(state).hardness
);
assert_eq!(deferred_facts.get(state).classes, facts.get(state).classes);
assert_eq!(
deferred_behaviours.facts(state).flags,
independent_behaviours.facts(state).flags
);
assert_eq!(
deferred_behaviours.data(state).sounds.place,
independent_behaviours.data(state).sounds.place
);
assert_eq!(shared_facts.get(state).emission, facts.get(state).emission);
assert_eq!(shared_facts.get(state).classes, facts.get(state).classes);
assert_eq!(
shared_behaviours.facts(state).flags,
independent_behaviours.facts(state).flags,
);
assert_eq!(
shared_behaviours.data(state).sounds.place,
independent_behaviours.data(state).sounds.place,
);
}
let (a, b) = (old_facts.get(iron), facts.get(ruby));
assert_eq!((b.hardness, b.emission, b.friction), (4.0, 3, 0.8));
assert_eq!(b.explosion_resistance, a.explosion_resistance);
@@ -256,3 +301,184 @@ fn no_content_keeps_the_base_root() {
}
use horizon_world::registry::BlockStateId;
#[test]
fn shared_behaviour_document_matches_independent_loaders() {
let Some(root) = prepared() else { return };
let assets = Assets::load(&root).expect("assets");
let doc: serde_json::Value = serde_json::from_reader(std::io::BufReader::new(
std::fs::File::open(root.join("block-behaviours.json")).unwrap(),
))
.unwrap();
let original = BlockFacts::load(&root, assets.registry).unwrap();
let (shared, b) = BlockFacts::load_with_behaviours(&root, assets.registry, &doc).unwrap();
let (deferred_facts, projection) =
BlockFacts::load_with_projection(&root, assets.registry, &doc).unwrap();
let deferred = horizon_world::level::Behaviours::load_with_gameplay(
assets.registry,
&root,
&doc,
&projection,
)
.unwrap();
assert_eq!(deferred_facts.states.len(), shared.states.len());
assert_eq!(original.states.len(), shared.states.len());
for (a, b) in original.states.iter().zip(&shared.states) {
assert_eq!(a.classes, b.classes);
assert_eq!(a.legacy_solid, b.legacy_solid);
assert_eq!(a.sturdy_full, b.sturdy_full);
assert_eq!(a.emission, b.emission);
assert_eq!(a.dampening, b.dampening);
assert_eq!(a.hardness, b.hardness);
assert_eq!(a.sounds.volume, b.sounds.volume);
assert_eq!(a.sounds.pitch, b.sounds.pitch);
}
let a = horizon_world::level::Behaviours::load(assets.registry, &root).unwrap();
for id in 0..assets.registry.len() {
let state = horizon_world::registry::BlockStateId(id as u32);
let (a_state, b_state) = (a.facts(state), b.facts(state));
let deferred_state = deferred.facts(state);
assert_eq!(b_state.flags, deferred_state.flags);
assert_eq!(b_state.emission, deferred_state.emission);
assert_eq!(b_state.dampening, deferred_state.dampening);
assert_eq!(b_state.hardness, deferred_state.hardness);
assert_eq!(b_state.push, deferred_state.push);
assert_eq!(a_state.flags, b_state.flags);
assert_eq!(a_state.sturdy, b_state.sturdy);
assert_eq!(a_state.weak, b_state.weak);
assert_eq!(a_state.strong, b_state.strong);
assert_eq!(a_state.fluid, b_state.fluid);
assert_eq!(a_state.emission, b_state.emission);
assert_eq!(a_state.dampening, b_state.dampening);
assert_eq!(a_state.hardness, b_state.hardness);
assert_eq!(a_state.push, b_state.push);
assert_eq!(a_state.instrument, b_state.instrument);
assert_eq!(a_state.shape, b_state.shape);
let (a_sound, b_sound) = (&a.data(state).sounds, &b.data(state).sounds);
assert_eq!(a_sound.volume, b_sound.volume);
assert_eq!(a_sound.pitch, b_sound.pitch);
assert_eq!(a_sound.place, b_sound.place);
assert_eq!(a_sound.break_, b_sound.break_);
assert_eq!(a_sound.fall, b_sound.fall);
}
}
#[cfg(unix)]
#[test]
fn independent_reloads_read_changed_behaviour_json_and_report_invalid_files() {
let Some(base) = prepared() else { return };
let scratch = std::env::temp_dir().join(format!("horizon-json-reloads-{}", std::process::id()));
let _ = fs::remove_dir_all(&scratch);
fs::create_dir_all(&scratch).unwrap();
// Keep the remaining resource tree intact without copying a huge prepared client.
for entry in fs::read_dir(&base).unwrap() {
let entry = entry.unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink(entry.path(), scratch.join(entry.file_name())).unwrap();
}
let assets = Assets::load(&base).unwrap();
let registry = assets.registry;
let original = fs::read(base.join("block-behaviours.json")).unwrap();
fs::remove_file(scratch.join("block-behaviours.json")).unwrap();
fs::write(scratch.join("block-behaviours.json"), &original).unwrap();
// Independent facts and behaviours can load first, followed by paired data.
let independent_first = BlockFacts::load(&scratch, registry).unwrap();
let independent_world_first =
horizon_world::level::Behaviours::load(registry, &scratch).unwrap();
let (facts, paired_world) = BlockFacts::load_pair(&scratch, registry).unwrap();
assert_eq!(facts.states.len(), registry.len());
for state in [0, 1, registry.len() - 1] {
let state = horizon_world::registry::BlockStateId(state as u32);
assert_eq!(
facts.get(state).classes,
independent_first.get(state).classes
);
assert_eq!(
facts.get(state).sounds.place,
independent_first.get(state).sounds.place
);
assert_eq!(
paired_world.facts(state).flags,
independent_world_first.facts(state).flags
);
}
// Override one exported state bit at the same path and verify that a later
// independent and paired read sees it while the original resource root does not.
let mut changed: serde_json::Value = serde_json::from_slice(&original).unwrap();
let original_bits = changed["states"][0][1].as_u64().unwrap();
changed["states"][0][1] = (original_bits ^ 1).into();
fs::write(
scratch.join("block-behaviours.json"),
serde_json::to_vec(&changed).unwrap(),
)
.unwrap();
let changed_pair = BlockFacts::load_pair(&scratch, registry).unwrap();
let changed_independent = BlockFacts::load(&scratch, registry).unwrap();
let base_facts = BlockFacts::load(&base, registry).unwrap();
let state = horizon_world::registry::BlockStateId(0);
assert_ne!(
changed_pair.0.get(state).legacy_solid,
base_facts.get(state).legacy_solid
);
assert_eq!(
changed_pair.0.get(state).legacy_solid,
changed_independent.get(state).legacy_solid
);
// The world loader sees the same overridden legacy solidity flag.
let changed_world = horizon_world::level::Behaviours::load(registry, &scratch).unwrap();
assert_eq!(
changed_world.facts(state).flags & 1 != 0,
changed_pair.0.get(state).legacy_solid
);
fs::write(scratch.join("block-behaviours.json"), b"{").unwrap();
let paired_error = BlockFacts::load_pair(&scratch, registry)
.err()
.unwrap()
.to_string();
let independent_error = BlockFacts::load(&scratch, registry)
.err()
.unwrap()
.to_string();
assert_eq!(paired_error, independent_error);
assert!(horizon_world::level::Behaviours::load(registry, &scratch).is_err());
fs::write(scratch.join("block-behaviours.json"), b"{}").unwrap();
assert!(BlockFacts::load_pair(&scratch, registry).is_err());
assert!(BlockFacts::load(&scratch, registry).is_err());
assert!(horizon_world::level::Behaviours::load(registry, &scratch).is_err());
fs::write(scratch.join("block-behaviours.json"), original).unwrap();
assert_eq!(
BlockFacts::load_pair(&scratch, registry)
.unwrap()
.0
.states
.len(),
registry.len()
);
fs::remove_file(scratch.join("gameplay-facts.json")).unwrap();
fs::write(scratch.join("gameplay-facts.json"), b"{\"states\":[]}").unwrap();
assert!(BlockFacts::load_pair(&scratch, registry).is_err());
assert!(BlockFacts::load(&scratch, registry).is_err());
assert!(horizon_world::level::Behaviours::load(registry, &scratch).is_err());
fs::write(scratch.join("gameplay-facts.json"), b"{").unwrap();
assert!(BlockFacts::load_pair(&scratch, registry).is_err());
assert!(BlockFacts::load(&scratch, registry).is_err());
assert!(horizon_world::level::Behaviours::load(registry, &scratch).is_err());
fs::write(
scratch.join("gameplay-facts.json"),
fs::read(base.join("gameplay-facts.json")).unwrap(),
)
.unwrap();
assert_eq!(
BlockFacts::load_pair(&scratch, registry)
.unwrap()
.0
.states
.len(),
registry.len()
);
fs::remove_dir_all(&scratch).unwrap();
}
@@ -155,7 +155,7 @@ mod tick_parity {
position::{BlockPos, ChunkPos},
random::{LegacyRandom, RandomSource},
};
use horizon_world::level::{Behaviours, LevelAccess, LevelEvent, Ticks, data};
use horizon_world::level::{LevelAccess, LevelEvent, Ticks, data};
use std::{cell::RefCell, path::PathBuf};
#[derive(Clone)]
@@ -208,7 +208,14 @@ mod tick_parity {
let root = std::env::var_os("HORIZON_RESOURCES")
.map(PathBuf::from)
.unwrap_or_else(|| {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3")
let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let local = manifest.join("../../.local/horizon-client/26.3");
if local.join("gameplay-facts.json").exists() {
local
} else {
// The branch worktree lives below the main checkout.
manifest.join("../../../../.local/horizon-client/26.3")
}
});
if !root.join("gameplay-facts.json").exists() {
eprintln!(
@@ -218,8 +225,7 @@ mod tick_parity {
return;
}
let registry = data::load_registry(&root).unwrap();
let mut facts = BlockFacts::load(&root, &registry).unwrap();
let behaviours = Behaviours::load(&registry, &root).unwrap();
let (mut facts, behaviours) = BlockFacts::load_pair(&root, &registry).unwrap();
let grass = registry.default_state("minecraft:grass_block").unwrap();
let chunk = |x| {
let mut c = Chunk::empty(x, 0);
+96 -32
View File
@@ -1,6 +1,6 @@
//! Behaviour tables built once from the pinned client resources.
use super::{
Behaviours,
Behaviours, GameplayStateSource,
classes::{Class, ClassSet, Interface},
states::{BlockId, PropKey, StateTable},
};
@@ -656,29 +656,79 @@ pub fn load_registry(root: &Path) -> io::Result<BlockRegistry> {
}
pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result<Behaviours> {
cached(registry, root, || load_uncached(registry, root))
}
/// [`load`] with `block-behaviours.json` already parsed by the caller.
pub(super) fn load_with_behaviour_json(
registry: &BlockRegistry,
root: &Path,
behaviour: &Value,
) -> io::Result<Behaviours> {
cached(registry, root, || {
build_with_behaviour_json(registry, root, behaviour)
})
}
/// [`load`] with the client's typed gameplay projection. The snapshot is
/// still tried first: on a hit the projection is not needed.
pub(super) fn load_with_gameplay<G: GameplayStateSource>(
registry: &BlockRegistry,
root: &Path,
behaviour: &Value,
gameplay_states: &[G],
) -> io::Result<Behaviours> {
cached(registry, root, || {
build_with_gameplay(registry, root, behaviour, gameplay_states)
})
}
/// The snapshot when it matches, else `build` and refresh the snapshot.
fn cached(
registry: &BlockRegistry,
root: &Path,
build: impl FnOnce() -> io::Result<Behaviours>,
) -> io::Result<Behaviours> {
if let Some(behaviours) = cache::load(registry, root) {
return Ok(behaviours);
}
let behaviours = load_uncached(registry, root)?;
let behaviours = build()?;
cache::store(registry, root, &behaviours);
Ok(behaviours)
}
fn load_uncached(registry: &BlockRegistry, root: &Path) -> io::Result<Behaviours> {
let behaviour = read_json(&root.join("block-behaviours.json"))?;
build_with_behaviour_json(registry, root, &behaviour)
}
fn build_with_behaviour_json(
registry: &BlockRegistry,
root: &Path,
behaviour: &Value,
) -> io::Result<Behaviours> {
let gameplay = read_json(&root.join("gameplay-facts.json"))?;
let gameplay_states = gameplay["states"]
.as_array()
.ok_or_else(|| fail("missing gameplay states"))?;
build_with_gameplay(registry, root, behaviour, gameplay_states)
}
fn build_with_gameplay<G: GameplayStateSource>(
registry: &BlockRegistry,
root: &Path,
behaviour: &Value,
gameplay_states: &[G],
) -> io::Result<Behaviours> {
let mut table = StateTable::new(registry)?;
let props = Props::resolve(&mut table);
let named = Named::resolve(&table)?;
let behaviour = read_json(&root.join("block-behaviours.json"))?;
let gameplay = read_json(&root.join("gameplay-facts.json"))?;
let blocks_json = behaviour["blocks"]
.as_array()
.ok_or_else(|| fail("missing behaviour blocks"))?;
let states_json = behaviour["states"]
.as_array()
.ok_or_else(|| fail("missing behaviour states"))?;
let gameplay_states = gameplay["states"]
.as_array()
.ok_or_else(|| fail("missing gameplay states"))?;
if blocks_json.len() != table.block_count()
|| states_json.len() != table.state_count()
|| gameplay_states.len() != table.state_count()
@@ -810,7 +860,7 @@ fn load_uncached(registry: &BlockRegistry, root: &Path) -> io::Result<Behaviours
.as_array()
.ok_or_else(|| fail("invalid behaviour state row"))?;
let int = |i: usize| row.get(i).and_then(Value::as_i64).unwrap_or(0);
let gb = |key: &str| game.get(key).and_then(Value::as_bool).unwrap_or(false);
let gb = |key: &str| game.flag(key);
let mut flags = int(1) as u32 & 0x7f;
for (key, bit) in [
("replaceable", state_flags::REPLACEABLE),
@@ -844,14 +894,10 @@ fn load_uncached(registry: &BlockRegistry, root: &Path) -> io::Result<Behaviours
weak: int(5) as u32,
strong: int(6) as u32,
fluid,
emission: game.get("emission").and_then(Value::as_u64).unwrap_or(0) as u8,
dampening: game.get("dampening").and_then(Value::as_u64).unwrap_or(0) as u8,
hardness: game.get("hardness").and_then(Value::as_f64).unwrap_or(0.0) as f32,
push: match game
.get("push")
.and_then(Value::as_str)
.unwrap_or("PUSH_PULL")
{
emission: game.unsigned("emission") as u8,
dampening: game.unsigned("dampening") as u8,
hardness: game.number("hardness") as f32,
push: match game.text("push") {
"PUSH" => PushReaction::Push,
"POPPED" => PushReaction::Popped,
"IMMOVEABLE" => PushReaction::Immoveable,
@@ -963,23 +1009,13 @@ fn load_uncached(registry: &BlockRegistry, root: &Path) -> io::Result<Behaviours
_ => Direction::Up,
};
let default = table.default_state(block);
let sound = &gameplay_states[default.0 as usize]["sound"];
let sound_id = |key: &str, strings: &mut HashMap<String, Arc<str>>| {
interned(
strings,
sound
.get(key)
.and_then(|s| s.get("id"))
.and_then(Value::as_str)
.unwrap_or(""),
)
};
let sound = &gameplay_states[default.0 as usize];
let sounds = Arc::new(Sounds {
volume: sound.get("volume").and_then(Value::as_f64).unwrap_or(1.0) as f32,
pitch: sound.get("pitch").and_then(Value::as_f64).unwrap_or(1.0) as f32,
place: sound_id("place", &mut strings),
break_: sound_id("break", &mut strings),
fall: sound_id("fall", &mut strings),
volume: sound.sound_number("volume") as f32,
pitch: sound.sound_number("pitch") as f32,
place: interned(&mut strings, sound.sound_id("place")),
break_: interned(&mut strings, sound.sound_id("break")),
fall: interned(&mut strings, sound.sound_id("fall")),
});
blocks.push(BlockData {
class,
@@ -1157,3 +1193,31 @@ fn instrument_index(name: &str) -> u8 {
.position(|n| n.eq_ignore_ascii_case(name))
.map_or(0, |i| i as u8)
}
impl GameplayStateSource for Value {
fn flag(&self, name: &str) -> bool {
self.get(name).and_then(Value::as_bool).unwrap_or(false)
}
fn unsigned(&self, name: &str) -> u64 {
self.get(name).and_then(Value::as_u64).unwrap_or(0)
}
fn number(&self, name: &str) -> f64 {
self.get(name).and_then(Value::as_f64).unwrap_or(0.0)
}
fn text(&self, name: &str) -> &str {
self.get(name).and_then(Value::as_str).unwrap_or("")
}
fn sound_number(&self, name: &str) -> f64 {
self.get("sound")
.and_then(|s| s.get(name))
.and_then(Value::as_f64)
.unwrap_or(1.0)
}
fn sound_id(&self, name: &str) -> &str {
self.get("sound")
.and_then(|s| s.get(name))
.and_then(|s| s.get("id"))
.and_then(Value::as_str)
.unwrap_or("")
}
}
+29
View File
@@ -431,6 +431,17 @@ pub fn raw_brightness<L: LevelAccess + ?Sized>(level: &L, pos: BlockPos, sky_dar
(level.sky_light(pos) - sky_darken).max(level.block_light(pos))
}
/// Access only the gameplay fields needed by level behaviour tables.
/// Both the JSON fallback and the client's typed decoder implement this.
pub trait GameplayStateSource {
fn flag(&self, name: &str) -> bool;
fn unsigned(&self, name: &str) -> u64;
fn number(&self, name: &str) -> f64;
fn text(&self, name: &str) -> &str;
fn sound_number(&self, name: &str) -> f64;
fn sound_id(&self, name: &str) -> &str;
}
/// Immutable vanilla block-behaviour tables. Build once with [`Behaviours::load`].
pub struct Behaviours {
pub table: StateTable,
@@ -456,6 +467,24 @@ impl Behaviours {
pub fn load(registry: &BlockRegistry, resources_dir: &Path) -> io::Result<Self> {
data::load(registry, resources_dir)
}
/// Reuse the client's typed gameplay projection while it is borrowed from the JSON bytes.
pub fn load_with_gameplay<G: GameplayStateSource>(
registry: &BlockRegistry,
resources_dir: &Path,
behaviour: &serde_json::Value,
gameplay: &[G],
) -> io::Result<Self> {
data::load_with_gameplay(registry, resources_dir, behaviour, gameplay)
}
pub fn load_with_behaviour_json(
registry: &BlockRegistry,
resources_dir: &Path,
behaviour: &serde_json::Value,
) -> io::Result<Self> {
data::load_with_behaviour_json(registry, resources_dir, behaviour)
}
/// Keep a snapshot of the resolved tables in `dir` (a game folder's
/// `.horizon-cache`), so later launches of the same build restore it instead
/// of resolving the resources again. Without it, [`Self::load`] never caches.
Binary file not shown.

After

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 232 KiB

@@ -0,0 +1,63 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import com.mojang.blaze3d.vertex.*;
import com.mojang.renderpearl.api.pipeline.IndexType;
import java.nio.*;
import java.nio.file.*;
import net.minecraft.client.renderer.chunk.TranslucencyPointOfView;
import net.minecraft.core.BlockPos;
import net.minecraft.core.SectionPos;
import net.minecraft.world.phys.Vec3;
/** Original probe calling the pinned game's centroid, sorting and index writers. */
public final class VanillaTranslucencyOracle {
public static void main(String[] args) throws Exception {
try (var out = Files.newBufferedWriter(Path.of(args[1]))) {
for (String line : Files.readAllLines(Path.of(args[0]))) {
JsonObject input = JsonParser.parseString(line).getAsJsonObject();
JsonArray quads = input.getAsJsonArray("quads");
ByteBuffer vertices = ByteBuffer.allocate(quads.size() * 48).order(ByteOrder.nativeOrder());
for (JsonElement quad : quads)
for (JsonElement vertex : quad.getAsJsonArray())
for (JsonElement component : vertex.getAsJsonArray()) vertices.putFloat(component.getAsFloat());
vertices.flip();
CompactVectorArray centers = new CompactVectorArray(quads.size());
MeshData.decodeQuadCentroids(vertices, quads.size() * 4, DefaultVertexFormat.POSITION, centers, 0);
JsonArray centerBits = new JsonArray();
for (int i = 0; i < centers.size(); i++) {
JsonArray c = new JsonArray();
c.add(Float.floatToIntBits(centers.getX(i)));
c.add(Float.floatToIntBits(centers.getY(i)));
c.add(Float.floatToIntBits(centers.getZ(i)));
centerBits.add(c);
}
JsonArray origin = input.getAsJsonArray("origin");
int ox = origin.get(0).getAsInt(), oy = origin.get(1).getAsInt(), oz = origin.get(2).getAsInt();
long section = SectionPos.asLong(ox >> 4, oy >> 4, oz >> 4);
BlockPos lastBlock = null;
TranslucencyPointOfView lastPov = null;
JsonArray frames = new JsonArray();
for (JsonElement element : input.getAsJsonArray("cameras")) {
JsonArray c = element.getAsJsonArray();
Vec3 camera = new Vec3(c.get(0).getAsDouble(), c.get(1).getAsDouble(), c.get(2).getAsDouble());
BlockPos block = BlockPos.containing(camera);
TranslucencyPointOfView pov = TranslucencyPointOfView.of(camera, section);
boolean update = lastPov == null || !lastPov.equals(pov) || (!block.equals(lastBlock) && pov.isAxisAligned());
if (update) { lastPov = pov; lastBlock = block; }
var sorting = VertexSorting.byDistance((float)(camera.x - ox), (float)(camera.y - oy), (float)(camera.z - oz));
ByteBuffer buffer = ByteBuffer.allocate(quads.size() * 24).order(ByteOrder.nativeOrder());
new MeshData.SortState(centers, IndexType.INT).writeSortedIndexBuffer(buffer, sorting);
buffer.flip();
JsonArray indices = new JsonArray();
while (buffer.hasRemaining()) indices.add(buffer.getInt());
JsonObject frame = new JsonObject();
frame.add("indices", indices); frame.addProperty("update", update); frames.add(frame);
}
JsonObject result = new JsonObject();
result.add("centers", centerBits); result.add("frames", frames);
out.write(result.toString()); out.newLine();
}
}
}
}
+155
View File
@@ -0,0 +1,155 @@
"""Exercise the client's capture methods without opening or focusing an OS window.
The fixture substitutes only winit and mouse state. Method bodies come from the
client, so the assertions observe grab attempts, visibility and stored capture
state. Native Windows delivery remains a manual check. Vanilla 26.3 reference:
LevelLoadingScreen.tick/onClose, Gui.setScreen, MouseHandler.grabMouse/releaseMouse.
"""
from pathlib import Path
import os
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
def method(source, name):
start = source.index(f" fn {name}(")
opening = source.index("{", start)
depth = 1
end = opening + 1
while depth:
depth += (source[end] == "{") - (source[end] == "}")
end += 1
return source[start:end]
class WorldInputCaptureTests(unittest.TestCase):
def test_loading_completion_wiring(self):
game = (ROOT / "crates/horizon-client/src/game.rs").read_text(encoding="utf-8")
remote = (ROOT / "crates/horizon-client/src/game/remote.rs").read_text(encoding="utf-8")
spawn = method(game, "spawn_player")
self.assertLess(spawn.index("self.player = Some(player)"),
spawn.index("self.capture_loaded_world()"))
tick = remote[remote.index(" pub(super) fn tick_remote("):]
ready = tick[tick.index("if self.remote.as_ref().is_some_and(|r| !r.loaded_sent)"):]
self.assertLess(ready.index("r.loaded_sent = true"),
ready.index("self.capture_loaded_world()"))
self.assertLess(ready.index("self.capture_loaded_world()"),
ready.index("let stick = self.pad_move()"))
@unittest.skipUnless(shutil.which("rustc"), "requires Rust")
def test_capture_lifecycle(self):
source = (ROOT / "crates/horizon-client/src/game.rs").read_text(encoding="utf-8")
fixture = r'''
use std::cell::Cell;
#[derive(Clone, Copy, PartialEq)]
enum Screen { Playing, Paused, Inventory }
enum CursorGrabMode { Locked, Confined, None }
#[derive(Default)]
struct Window { grabs: Cell<u32>, visible: Cell<bool>, fail: bool }
impl Window {
fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), ()> {
if !matches!(mode, CursorGrabMode::None) {
self.grabs.set(self.grabs.get() + 1);
}
if self.fail { Err(()) } else { Ok(()) }
}
fn set_cursor_visible(&self, visible: bool) { self.visible.set(visible); }
}
#[derive(Default)]
struct Mouse { ignore_first: bool }
impl Mouse { fn set_ignore_first_move(&mut self) { self.ignore_first = true; } }
struct Remote { chat_input: Option<()> }
struct Game {
focused: bool, agent_pointer: bool, window: Option<Window>, mouse: Mouse,
captured: bool, title: Option<()>, screen: Screen, remote: Option<Remote>,
mining: bool,
}
impl Default for Game {
fn default() -> Self {
Self { focused: true, agent_pointer: false, window: Some(Window::default()),
mouse: Mouse::default(), captured: false, title: None,
screen: Screen::Playing, remote: None, mining: false }
}
}
impl Game {
fn stop_mining(&mut self) { self.mining = false; }
METHODS
}
fn main() {
// New and existing worlds, returning to title, and reopening a world.
for remote in [false, true] {
let mut game = Game::default();
if remote { game.remote = Some(Remote { chat_input: None }); }
for _ in 0..3 {
game.title = Some(());
game.capture(false);
game.capture_loaded_world();
assert!(!game.captured);
game.title = None;
game.capture_loaded_world();
assert!(game.captured);
assert!(game.mouse.ignore_first);
assert!(!game.window.as_ref().unwrap().visible.get());
for screen in [Screen::Paused, Screen::Inventory] {
game.screen = screen;
game.mining = true;
game.capture(false);
assert!(!game.mining);
game.capture_loaded_world();
assert!(!game.captured);
assert!(game.window.as_ref().unwrap().visible.get());
game.screen = Screen::Playing;
game.capture(true);
assert!(game.captured);
}
}
// Alt+Tab during loading: no native grab or agent-pointer reset.
game.focused = false;
game.mining = true;
game.capture(false);
assert!(!game.mining);
assert!(!game.captured);
assert!(game.window.as_ref().unwrap().visible.get());
game.agent_pointer = true;
let grabs = game.window.as_ref().unwrap().grabs.get();
game.capture_loaded_world();
game.capture(true);
assert!(!game.captured);
assert!(game.agent_pointer);
assert_eq!(game.window.as_ref().unwrap().grabs.get(), grabs);
game.focused = true;
assert!(!game.captured); // Focus alone does not resume gameplay.
game.capture(true); // Click or resume action.
assert!(game.captured);
}
let mut game = Game::default();
game.remote = Some(Remote { chat_input: Some(()) });
game.capture_loaded_world();
assert!(!game.captured);
assert_eq!(game.window.as_ref().unwrap().grabs.get(), 0);
game.remote = None;
game.window.as_mut().unwrap().fail = true;
game.capture_loaded_world();
assert!(!game.captured);
assert!(game.window.as_ref().unwrap().visible.get());
}
'''
fixture = fixture.replace("METHODS", method(source, "capture") + "\n" +
method(source, "capture_loaded_world"))
with tempfile.TemporaryDirectory(prefix="horizon-input-") as folder:
folder = Path(folder)
rust = folder / "capture.rs"
binary = folder / ("capture.exe" if os.name == "nt" else "capture")
rust.write_text(fixture, encoding="utf-8")
subprocess.run(["rustc", "--edition=2024", str(rust), "-o", str(binary)],
check=True, capture_output=True, text=True, timeout=60)
subprocess.run([str(binary)], check=True, capture_output=True, text=True, timeout=10)
if __name__ == "__main__":
unittest.main()
+85
View File
@@ -0,0 +1,85 @@
# Reproducing PR #607 block-facts startup profiles
These are loader-only measurements. They include `Assets::load`, `BlockFacts`, and
`Behaviours` and exclude content root preparation, graphics, input setup, first
frame, and the rest of the client startup sequence. No full-client startup gain
has been measured. The prepared `26.3` resource root must match the revision.
## Historical release builds
From the PR branch checkout, use an absolute prepared resource-root path and a
single, explicit Cargo release profile for each detached historical worktree:
```sh
PR_ROOT="$(pwd)"
BENCH_ROOT="$(mktemp -d)"
mkdir -p "$BENCH_ROOT/bin"
CARGO_TARGET_DIR="$BENCH_ROOT/target"
export CARGO_TARGET_DIR
for entry in baseline:e422bd13 a01:a01d47f2 cf:cf837118 cd:cd61e11b; do
name="${entry%%:*}"
revision="${entry#*:}"
git worktree add --detach "$BENCH_ROOT/$name" "$revision"
done
# e422bd13 predates the profiler; add the same baseline example source used
# for the benchmark, without changing any production implementation.
cp "$PR_ROOT/tools/baseline_loader_profile.rs" \
"$BENCH_ROOT/baseline/crates/horizon-client/examples/shared_json_startup_profile.rs"
for name in baseline a01 cf cd; do
(cd "$BENCH_ROOT/$name" && \
cargo build --offline --release -p horizon-client --example shared_json_startup_profile)
cp "$CARGO_TARGET_DIR/release/examples/shared_json_startup_profile" \
"$BENCH_ROOT/bin/$name"
done
cargo build --offline --release -p horizon-client --example shared_json_startup_profile
cp "$CARGO_TARGET_DIR/release/examples/shared_json_startup_profile" "$BENCH_ROOT/bin/current"
python3 tools/profile_shared_json.py \
--resources /absolute/path/to/.local/horizon-client/26.3 \
--baseline-binary "$BENCH_ROOT/bin/baseline" \
--a01-binary "$BENCH_ROOT/bin/a01" \
--cf-binary "$BENCH_ROOT/bin/cf" \
--cd-binary "$BENCH_ROOT/bin/cd" \
--binary "$BENCH_ROOT/bin/current" \
--repeats 10 --output "$BENCH_ROOT/five-way.json"
```
The source tree of each historical revision is exact. The baseline profiler is
an added standalone measurement example, and therefore does not alter its
historical loader logic. Comparisons use alternating forward/reverse process
order, separate processes, Linux `wait4` CPU time and peak RSS, and saved raw
samples with 25th/75th percentiles, extrema, build hashes and system load.
Keep concurrent compilation and other CPU-intensive jobs idle if possible.
`ru_maxrss` records process peak residency and cannot establish the real game's
memory usage after rendering begins. If system load rises, preserve rather than
discard outliers and report the uncertainty.
## Decoding passes and buffer lifetime
```sh
cargo build --offline --release -p horizon-client --example gameplay_decode_profile
python3 tools/profile_gameplay_decode.py \
--resources /absolute/path/to/.local/horizon-client/26.3 \
--repeats 10 --output "$BENCH_ROOT/decode.json"
python3 tools/profile_shared_json.py \
--resources /absolute/path/to/.local/horizon-client/26.3 \
--variant released="$BENCH_ROOT/bin/current"@deferred \
--variant retained="$BENCH_ROOT/bin/current"@deferred-held \
--repeats 10 --output "$BENCH_ROOT/lifetime.json"
```
The decoder profile measures the `Validate` pass and typed `Gameplay` pass
separately, including the JSON read in `total_ms`. The primary facts loader
continues both passes to preserve JSON validation, error precedence and useful
diagnostics, including overwritten fields and raw geometry. The lifetime
comparison measures current process `VmRSS` after materialisation, plus peak
RSS across the process. An explicit `drop` releases owned Rust values, but the
allocator may retain physical pages, so immediate RSS savings are not implied.
When finished, `git worktree remove` each temporary historical worktree. Do
not `git clean` or reset the active PR working tree.
+23
View File
@@ -0,0 +1,23 @@
//! Historical baseline comparator for PR #607; one normal independent loading sequence.
use horizon_client::{assets::Assets, blocks::BlockFacts};
use horizon_world::level::Behaviours;
use std::{path::Path, time::Instant};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = std::env::args().skip(1);
let root = args.next().ok_or("expected prepared resource directory")?;
if args.next().as_deref() != Some("baseline") {
return Err("expected baseline".into());
}
let root = Path::new(&root);
let total = Instant::now();
let assets = Assets::load(root)?;
let started = Instant::now();
let facts = BlockFacts::load(root, assets.registry)?;
let behaviours = Behaviours::load(assets.registry, root)?;
println!("phase_ms={:.3}", started.elapsed().as_secs_f64() * 1000.0);
println!("total_ms={:.3}", total.elapsed().as_secs_f64() * 1000.0);
println!("states={}", facts.states.len());
std::hint::black_box((facts, behaviours));
Ok(())
}
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""Profile the validation and typed-deserialization passes in separate processes.
Build `cargo build --release -p horizon-client --example gameplay_decode_profile`
then run this tool with the matching prepared resources. These passes are
both currently required for exact JSON error classification/precedence.
"""
import argparse
import hashlib
import json
import os
import statistics
from pathlib import Path
from profile_shared_json import percentile, run
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--binary", type=Path,
default=Path("target/release/examples/gameplay_decode_profile"))
parser.add_argument("--resources", type=Path, default=Path(".local/horizon-client/26.3"))
parser.add_argument("--repeats", type=int, default=8)
parser.add_argument("--output", type=Path)
args = parser.parse_args()
if args.repeats < 1:
parser.error("--repeats must be positive")
binary, resources = args.binary.resolve(), args.resources.resolve()
if not binary.is_file() or not resources.is_dir():
parser.error("release example or resources missing")
modes = ("validate", "typed")
samples = {mode: [] for mode in modes}
loads = [os.getloadavg()]
for i in range(args.repeats):
for mode in (modes if i % 2 == 0 else reversed(modes)):
samples[mode].append(run(binary, resources, mode))
loads.append(os.getloadavg())
result = {
"scope": "Isolated gameplay-facts.json validation/typed decoding; includes JSON file read",
"resources": str(resources),
"repeats": args.repeats,
"load_averages_before_after": loads,
"binary_sha256": hashlib.sha256(binary.read_bytes()).hexdigest(),
"metrics": {
mode: {
key: {"median": round(statistics.median(values), 3),
"p25": round(percentile(values, .25), 3),
"p75": round(percentile(values, .75), 3),
"min": round(min(values), 3), "max": round(max(values), 3),
"samples": [round(x, 3) for x in values]}
for key in rows[0]
for values in [[row[key] for row in rows]]
}
for mode, rows in samples.items()
},
}
data = json.dumps(result, indent=2)
print(data)
if args.output:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(data + "\n")
if __name__ == "__main__":
main()
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""Profile the asset/block-facts/behaviour loading phase in release executables.
Build `shared_json_startup_profile` with the same Cargo release profile at each
revision. With --a01-binary, --cf-binary and --cd-binary, the script compares
five versions in alternated separate processes; --baseline-binary optionally
supplies a build from the original pre-PR checkout. Without historical inputs,
legacy baseline/pr607/shared/deferred same-binary comparisons are supported.
The measurement excludes full client startup, renderer and first frame.
"""
import argparse
import hashlib
import json
import os
import statistics
import subprocess
import tempfile
from pathlib import Path
def run(binary, resources, mode):
with tempfile.TemporaryFile(mode="w+t") as output:
proc = subprocess.Popen([str(binary), str(resources), mode], stdout=output,
stderr=subprocess.PIPE)
_, status, usage = os.wait4(proc.pid, 0)
proc.returncode = os.waitstatus_to_exitcode(status)
_, stderr = proc.communicate()
if proc.returncode:
raise RuntimeError(f"{binary} {mode}: {stderr.decode(errors='replace')}")
output.seek(0)
fields = dict(line.rstrip().split("=", 1) for line in output if "=" in line)
measurements = {
"phase_ms": float(fields["phase_ms"]),
"total_ms": float(fields["total_ms"]),
"cpu_ms": (usage.ru_utime + usage.ru_stime) * 1000.0,
"peak_rss_kib": usage.ru_maxrss,
}
for field in ("behaviour_json_ms", "facts_ms", "behaviours_ms", "post_rss_kib"):
if field in fields:
measurements[field] = float(fields[field])
return measurements
def percentile(values, percent):
ordered = sorted(values)
position = (len(ordered) - 1) * percent
low = int(position)
return ordered[low] + (ordered[min(low + 1, len(ordered) - 1)] - ordered[low]) * (position - low)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--binary", type=Path, default=Path("target/release/examples/shared_json_startup_profile"))
parser.add_argument("--resources", type=Path, default=Path(".local/horizon-client/26.3"))
parser.add_argument("--repeats", type=int, default=5)
parser.add_argument("--reference-binary", type=Path, help="Legacy comparison to cf837118")
parser.add_argument("--baseline-binary", type=Path, help="Optional original main build; expects baseline mode")
parser.add_argument("--a01-binary", type=Path, help="Release executable built at a01d47f2")
parser.add_argument("--cf-binary", type=Path, help="Release executable built at cf837118")
parser.add_argument("--cd-binary", type=Path, help="Release executable built at cd61e11b")
parser.add_argument("--variant", action="append", metavar="LABEL=PATH@MODE",
help="Compare arbitrary release variants, e.g. pool=target/...@deferred")
parser.add_argument("--output", type=Path)
args = parser.parse_args()
if args.repeats < 1:
parser.error("--repeats must be positive")
binary, resources = args.binary.resolve(), args.resources.resolve()
if not resources.is_dir():
parser.error("resources directory missing")
historical = any((args.a01_binary, args.cf_binary, args.cd_binary, args.baseline_binary))
if args.variant:
if historical or args.reference_binary:
parser.error("--variant cannot be mixed with historical comparison flags")
commands = {}
for specification in args.variant:
if "=" not in specification or "@" not in specification:
parser.error("--variant must be LABEL=PATH@MODE")
name, executable_mode = specification.split("=", 1)
executable, binary_mode = executable_mode.rsplit("@", 1)
if not name or not executable or not binary_mode or name in commands:
parser.error("variant names must be unique and all fields nonempty")
commands[name] = (Path(executable).resolve(), binary_mode)
elif historical:
if not all((args.a01_binary, args.cf_binary, args.cd_binary)):
parser.error("historical comparisons require --a01-binary, --cf-binary and --cd-binary")
commands = {
"baseline": ((args.baseline_binary or args.a01_binary).resolve(), "baseline"),
"a01d47f2": (args.a01_binary.resolve(), "shared"),
"cf837118": (args.cf_binary.resolve(), "deferred"),
"cd61e11b": (args.cd_binary.resolve(), "deferred"),
"current": (binary, "deferred"),
}
elif args.reference_binary:
commands = {
"baseline": (binary, "baseline"),
"pr607": (binary, "pr607"),
"cf837118": (args.reference_binary.resolve(), "deferred"),
"current": (binary, "deferred"),
}
else:
commands = {mode: (binary, mode) for mode in ("baseline", "pr607", "shared", "deferred")}
for executable, _ in commands.values():
if not executable.is_file():
parser.error(f"release executable missing: {executable}")
modes = list(commands)
samples = {mode: [] for mode in modes}
orders = []
initial_load = os.getloadavg()
for i in range(args.repeats):
order = modes if i % 2 == 0 else list(reversed(modes))
orders.append(list(order))
for mode in order:
executable, binary_mode = commands[mode]
samples[mode].append(run(executable, resources, binary_mode))
result = {
"scope": "Assets + BlockFacts + Behaviours loader only; no full startup or first frame",
"resources": str(resources),
"repeats": args.repeats,
"ordering": orders,
"load_average_before": initial_load,
"load_average_after": os.getloadavg(),
"executables": {
mode: {"path": str(executable), "mode": binary_mode,
"sha256": hashlib.sha256(executable.read_bytes()).hexdigest()}
for mode, (executable, binary_mode) in commands.items()
},
"metrics": {
mode: {
key: {
"median": round(statistics.median(values), 3),
"p25": round(percentile(values, .25), 3),
"p75": round(percentile(values, .75), 3),
"min": round(min(values), 3),
"max": round(max(values), 3),
"samples": [round(value, 3) for value in values],
}
for key in rows[0]
for values in [[row[key] for row in rows]]
}
for mode, rows in samples.items()
},
}
data = json.dumps(result, indent=2)
print(data)
if args.output:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(data + "\n")
if __name__ == "__main__":
main()
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env python3
"""Compare quad centroids, sorted triangle indices and cached viewpoints with vanilla 26.3."""
import argparse
import json
import os
import random
import subprocess
try:
from . import lab, test_rust_parity as base, test_model_baking_parity as baking
except ImportError:
import lab, test_rust_parity as base, test_model_baking_parity as baking
def cases():
rng = random.Random(563)
# Equal distances and a skewed quad detect unstable ties and averaging all four corners.
yield {'origin': [0, 0, 0], 'quads': [
[[-1, 0, 0]] * 4, [[1, 0, 0]] * 4,
[[0, 0, 0], [100, 100, 100], [2, 2, 2], [200, 200, 200]]],
'cameras': [[0, 0, 0], [0.1, 0.1, 0.1], [1, 0, 0], [-1, 0, 0]]}
for count in [0, 1, 2, 64, *[rng.randrange(3, 100) for _ in range(200)]]:
origin = [rng.choice([-30000000, -64, -16, 0, 16, 30000000]) for _ in range(3)]
# SectionPos packs Y into fewer bits; world-border coordinates apply to X/Z.
origin[1] = rng.choice([-64, -16, 0, 16, 304])
quads = [[[rng.uniform(-1, 17) for _ in range(3)] for _ in range(4)] for _ in range(count)]
# Walk through block and section boundaries, including negative and diagonal viewpoints.
cameras = [[o + d for o in origin] for d in [-32.5, -32.1, -31.9, -16, -0.1, 0, 0.9, 1.1, 15.9, 16, 32, 48]]
cameras += [[origin[i] + rng.uniform(-64, 64) for i in range(3)] for _ in range(8)]
yield {'origin': origin, 'quads': quads, 'cameras': cameras}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--profile', default='fast', help='Cargo build profile')
args = parser.parse_args()
lock, jars, _ = base.verify_artifacts()
build = lab.LOCAL / 'translucency-parity'
classes = build / 'classes'
classes.mkdir(parents=True, exist_ok=True)
inputs = build / 'inputs.jsonl'
inputs.write_text(''.join(json.dumps(c) + '\n' for c in cases()), encoding='utf-8')
dependencies = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()]))
def run(command, name):
with (build / (name + '.log')).open('w', encoding='utf-8') as log:
result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, stdout=log, stderr=subprocess.STDOUT, timeout=600)
if result.returncode:
raise RuntimeError((build / (name + '.log')).read_text()[-4000:])
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', dependencies, '-d', classes,
lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTranslucencyOracle.java'], 'compile-java')
vanilla, rust = build / 'vanilla.jsonl', build / 'rust.jsonl'
run(['java', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaTranslucencyOracle', inputs, vanilla], 'vanilla')
run(['cargo', 'run', '--quiet', '--locked', '--profile', args.profile, '-p', 'horizon-client', '--example', 'translucency_fixture', '--', inputs, rust], 'rust')
expected = [json.loads(line) for line in vanilla.read_text().splitlines()]
actual = [json.loads(line) for line in rust.read_text().splitlines()]
assert len(expected) == len(actual), 'case count differs'
for i, (a, b) in enumerate(zip(expected, actual)):
assert a == b, f'sorting mismatch in case {i}; inspect {build}'
frames = sum(len(c['frames']) for c in expected)
print(f'translucency parity ok: {len(expected)} cases, {frames} camera views; centroids, indices and cache decisions match exactly')
if __name__ == '__main__':
main()